You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1454 lines
57 KiB

Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Windows system calls.
  5. package windows
  6. import (
  7. errorspkg "errors"
  8. "sync"
  9. "syscall"
  10. "time"
  11. "unicode/utf16"
  12. "unsafe"
  13. )
  14. type Handle uintptr
  15. const (
  16. InvalidHandle = ^Handle(0)
  17. // Flags for DefineDosDevice.
  18. DDD_EXACT_MATCH_ON_REMOVE = 0x00000004
  19. DDD_NO_BROADCAST_SYSTEM = 0x00000008
  20. DDD_RAW_TARGET_PATH = 0x00000001
  21. DDD_REMOVE_DEFINITION = 0x00000002
  22. // Return values for GetDriveType.
  23. DRIVE_UNKNOWN = 0
  24. DRIVE_NO_ROOT_DIR = 1
  25. DRIVE_REMOVABLE = 2
  26. DRIVE_FIXED = 3
  27. DRIVE_REMOTE = 4
  28. DRIVE_CDROM = 5
  29. DRIVE_RAMDISK = 6
  30. // File system flags from GetVolumeInformation and GetVolumeInformationByHandle.
  31. FILE_CASE_SENSITIVE_SEARCH = 0x00000001
  32. FILE_CASE_PRESERVED_NAMES = 0x00000002
  33. FILE_FILE_COMPRESSION = 0x00000010
  34. FILE_DAX_VOLUME = 0x20000000
  35. FILE_NAMED_STREAMS = 0x00040000
  36. FILE_PERSISTENT_ACLS = 0x00000008
  37. FILE_READ_ONLY_VOLUME = 0x00080000
  38. FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000
  39. FILE_SUPPORTS_ENCRYPTION = 0x00020000
  40. FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
  41. FILE_SUPPORTS_HARD_LINKS = 0x00400000
  42. FILE_SUPPORTS_OBJECT_IDS = 0x00010000
  43. FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000
  44. FILE_SUPPORTS_REPARSE_POINTS = 0x00000080
  45. FILE_SUPPORTS_SPARSE_FILES = 0x00000040
  46. FILE_SUPPORTS_TRANSACTIONS = 0x00200000
  47. FILE_SUPPORTS_USN_JOURNAL = 0x02000000
  48. FILE_UNICODE_ON_DISK = 0x00000004
  49. FILE_VOLUME_IS_COMPRESSED = 0x00008000
  50. FILE_VOLUME_QUOTAS = 0x00000020
  51. // Flags for LockFileEx.
  52. LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
  53. LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
  54. // Return values of SleepEx and other APC functions
  55. STATUS_USER_APC = 0x000000C0
  56. WAIT_IO_COMPLETION = STATUS_USER_APC
  57. )
  58. // StringToUTF16 is deprecated. Use UTF16FromString instead.
  59. // If s contains a NUL byte this function panics instead of
  60. // returning an error.
  61. func StringToUTF16(s string) []uint16 {
  62. a, err := UTF16FromString(s)
  63. if err != nil {
  64. panic("windows: string with NUL passed to StringToUTF16")
  65. }
  66. return a
  67. }
  68. // UTF16FromString returns the UTF-16 encoding of the UTF-8 string
  69. // s, with a terminating NUL added. If s contains a NUL byte at any
  70. // location, it returns (nil, syscall.EINVAL).
  71. func UTF16FromString(s string) ([]uint16, error) {
  72. for i := 0; i < len(s); i++ {
  73. if s[i] == 0 {
  74. return nil, syscall.EINVAL
  75. }
  76. }
  77. return utf16.Encode([]rune(s + "\x00")), nil
  78. }
  79. // UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
  80. // with a terminating NUL removed.
  81. func UTF16ToString(s []uint16) string {
  82. for i, v := range s {
  83. if v == 0 {
  84. s = s[0:i]
  85. break
  86. }
  87. }
  88. return string(utf16.Decode(s))
  89. }
  90. // StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.
  91. // If s contains a NUL byte this function panics instead of
  92. // returning an error.
  93. func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
  94. // UTF16PtrFromString returns pointer to the UTF-16 encoding of
  95. // the UTF-8 string s, with a terminating NUL added. If s
  96. // contains a NUL byte at any location, it returns (nil, syscall.EINVAL).
  97. func UTF16PtrFromString(s string) (*uint16, error) {
  98. a, err := UTF16FromString(s)
  99. if err != nil {
  100. return nil, err
  101. }
  102. return &a[0], nil
  103. }
  104. func Getpagesize() int { return 4096 }
  105. // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
  106. // This is useful when interoperating with Windows code requiring callbacks.
  107. // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
  108. func NewCallback(fn interface{}) uintptr {
  109. return syscall.NewCallback(fn)
  110. }
  111. // NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
  112. // This is useful when interoperating with Windows code requiring callbacks.
  113. // The argument is expected to be a function with with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
  114. func NewCallbackCDecl(fn interface{}) uintptr {
  115. return syscall.NewCallbackCDecl(fn)
  116. }
  117. // windows api calls
  118. //sys GetLastError() (lasterr error)
  119. //sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
  120. //sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW
  121. //sys FreeLibrary(handle Handle) (err error)
  122. //sys GetProcAddress(module Handle, procname string) (proc uintptr, err error)
  123. //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
  124. //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW
  125. //sys GetVersion() (ver uint32, err error)
  126. //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
  127. //sys ExitProcess(exitcode uint32)
  128. //sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process
  129. //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
  130. //sys ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
  131. //sys WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
  132. //sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)
  133. //sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
  134. //sys CloseHandle(handle Handle) (err error)
  135. //sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]
  136. //sys SetStdHandle(stdhandle uint32, handle Handle) (err error)
  137. //sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
  138. //sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
  139. //sys FindClose(handle Handle) (err error)
  140. //sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
  141. //sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error)
  142. //sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
  143. //sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
  144. //sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
  145. //sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
  146. //sys DeleteFile(path *uint16) (err error) = DeleteFileW
  147. //sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
  148. //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
  149. //sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
  150. //sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
  151. //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
  152. //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
  153. //sys SetEndOfFile(handle Handle) (err error)
  154. //sys GetSystemTimeAsFileTime(time *Filetime)
  155. //sys GetSystemTimePreciseAsFileTime(time *Filetime)
  156. //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
  157. //sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error)
  158. //sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error)
  159. //sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error)
  160. //sys CancelIo(s Handle) (err error)
  161. //sys CancelIoEx(s Handle, o *Overlapped) (err error)
  162. //sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW
  163. //sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error)
  164. //sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW
  165. //sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath
  166. //sys TerminateProcess(handle Handle, exitcode uint32) (err error)
  167. //sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
  168. //sys GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW
  169. //sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
  170. //sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
  171. //sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
  172. //sys waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects
  173. //sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
  174. //sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
  175. //sys GetFileType(filehandle Handle) (n uint32, err error)
  176. //sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
  177. //sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
  178. //sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
  179. //sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
  180. //sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
  181. //sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
  182. //sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
  183. //sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock
  184. //sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
  185. //sys getTickCount64() (ms uint64) = kernel32.GetTickCount64
  186. //sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
  187. //sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
  188. //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
  189. //sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
  190. //sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
  191. //sys CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
  192. //sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
  193. //sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
  194. //sys FlushFileBuffers(handle Handle) (err error)
  195. //sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
  196. //sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
  197. //sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
  198. //sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW
  199. //sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
  200. //sys UnmapViewOfFile(addr uintptr) (err error)
  201. //sys FlushViewOfFile(addr uintptr, length uintptr) (err error)
  202. //sys VirtualLock(addr uintptr, length uintptr) (err error)
  203. //sys VirtualUnlock(addr uintptr, length uintptr) (err error)
  204. //sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc
  205. //sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree
  206. //sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect
  207. //sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
  208. //sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
  209. //sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
  210. //sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) [failretval==InvalidHandle] = crypt32.CertOpenStore
  211. //sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
  212. //sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
  213. //sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
  214. //sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
  215. //sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
  216. //sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
  217. //sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
  218. //sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
  219. //sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
  220. //sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
  221. //sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW
  222. //sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
  223. //sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
  224. //sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
  225. //sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
  226. //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode
  227. //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo
  228. //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
  229. //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
  230. //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
  231. //sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
  232. //sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
  233. //sys Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error)
  234. //sys Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error)
  235. //sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
  236. // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
  237. //sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
  238. //sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
  239. //sys GetCurrentThreadId() (id uint32)
  240. //sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW
  241. //sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateEventExW
  242. //sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW
  243. //sys SetEvent(event Handle) (err error) = kernel32.SetEvent
  244. //sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent
  245. //sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent
  246. //sys CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) = kernel32.CreateMutexW
  247. //sys CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateMutexExW
  248. //sys OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW
  249. //sys ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex
  250. //sys SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx
  251. //sys CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW
  252. //sys AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject
  253. //sys TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject
  254. //sys SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode
  255. //sys ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread
  256. //sys SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass
  257. //sys GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass
  258. //sys SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error)
  259. //sys GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error)
  260. //sys GetProcessId(process Handle) (id uint32, err error)
  261. //sys OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error)
  262. //sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost
  263. // Volume Management Functions
  264. //sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW
  265. //sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW
  266. //sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW
  267. //sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW
  268. //sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW
  269. //sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW
  270. //sys FindVolumeClose(findVolume Handle) (err error)
  271. //sys FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error)
  272. //sys GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) = GetDiskFreeSpaceExW
  273. //sys GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW
  274. //sys GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0]
  275. //sys GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW
  276. //sys GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW
  277. //sys GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW
  278. //sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW
  279. //sys GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW
  280. //sys GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW
  281. //sys QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW
  282. //sys SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW
  283. //sys SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW
  284. //sys MessageBox(hwnd Handle, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW
  285. //sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx
  286. //sys InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint32, forceAppsClosed bool, rebootAfterShutdown bool, reason uint32) (err error) = advapi32.InitiateSystemShutdownExW
  287. //sys SetProcessShutdownParameters(level uint32, flags uint32) (err error) = kernel32.SetProcessShutdownParameters
  288. //sys GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) = kernel32.GetProcessShutdownParameters
  289. //sys clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) = ole32.CLSIDFromString
  290. //sys stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) = ole32.StringFromGUID2
  291. //sys coCreateGuid(pguid *GUID) (ret error) = ole32.CoCreateGuid
  292. //sys CoTaskMemFree(address unsafe.Pointer) = ole32.CoTaskMemFree
  293. //sys rtlGetVersion(info *OsVersionInfoEx) (ret error) = ntdll.RtlGetVersion
  294. //sys rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) = ntdll.RtlGetNtVersionNumbers
  295. //sys getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetProcessPreferredUILanguages
  296. //sys getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetThreadPreferredUILanguages
  297. //sys getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetUserPreferredUILanguages
  298. //sys getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) = kernel32.GetSystemPreferredUILanguages
  299. // Process Status API (PSAPI)
  300. //sys EnumProcesses(processIds []uint32, bytesReturned *uint32) (err error) = psapi.EnumProcesses
  301. // syscall interface implementation for other packages
  302. // GetCurrentProcess returns the handle for the current process.
  303. // It is a pseudo handle that does not need to be closed.
  304. // The returned error is always nil.
  305. //
  306. // Deprecated: use CurrentProcess for the same Handle without the nil
  307. // error.
  308. func GetCurrentProcess() (Handle, error) {
  309. return CurrentProcess(), nil
  310. }
  311. // CurrentProcess returns the handle for the current process.
  312. // It is a pseudo handle that does not need to be closed.
  313. func CurrentProcess() Handle { return Handle(^uintptr(1 - 1)) }
  314. // GetCurrentThread returns the handle for the current thread.
  315. // It is a pseudo handle that does not need to be closed.
  316. // The returned error is always nil.
  317. //
  318. // Deprecated: use CurrentThread for the same Handle without the nil
  319. // error.
  320. func GetCurrentThread() (Handle, error) {
  321. return CurrentThread(), nil
  322. }
  323. // CurrentThread returns the handle for the current thread.
  324. // It is a pseudo handle that does not need to be closed.
  325. func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) }
  326. // GetProcAddressByOrdinal retrieves the address of the exported
  327. // function from module by ordinal.
  328. func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) {
  329. r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0)
  330. proc = uintptr(r0)
  331. if proc == 0 {
  332. if e1 != 0 {
  333. err = errnoErr(e1)
  334. } else {
  335. err = syscall.EINVAL
  336. }
  337. }
  338. return
  339. }
  340. func Exit(code int) { ExitProcess(uint32(code)) }
  341. func makeInheritSa() *SecurityAttributes {
  342. var sa SecurityAttributes
  343. sa.Length = uint32(unsafe.Sizeof(sa))
  344. sa.InheritHandle = 1
  345. return &sa
  346. }
  347. func Open(path string, mode int, perm uint32) (fd Handle, err error) {
  348. if len(path) == 0 {
  349. return InvalidHandle, ERROR_FILE_NOT_FOUND
  350. }
  351. pathp, err := UTF16PtrFromString(path)
  352. if err != nil {
  353. return InvalidHandle, err
  354. }
  355. var access uint32
  356. switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {
  357. case O_RDONLY:
  358. access = GENERIC_READ
  359. case O_WRONLY:
  360. access = GENERIC_WRITE
  361. case O_RDWR:
  362. access = GENERIC_READ | GENERIC_WRITE
  363. }
  364. if mode&O_CREAT != 0 {
  365. access |= GENERIC_WRITE
  366. }
  367. if mode&O_APPEND != 0 {
  368. access &^= GENERIC_WRITE
  369. access |= FILE_APPEND_DATA
  370. }
  371. sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)
  372. var sa *SecurityAttributes
  373. if mode&O_CLOEXEC == 0 {
  374. sa = makeInheritSa()
  375. }
  376. var createmode uint32
  377. switch {
  378. case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
  379. createmode = CREATE_NEW
  380. case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
  381. createmode = CREATE_ALWAYS
  382. case mode&O_CREAT == O_CREAT:
  383. createmode = OPEN_ALWAYS
  384. case mode&O_TRUNC == O_TRUNC:
  385. createmode = TRUNCATE_EXISTING
  386. default:
  387. createmode = OPEN_EXISTING
  388. }
  389. var attrs uint32 = FILE_ATTRIBUTE_NORMAL
  390. if perm&S_IWRITE == 0 {
  391. attrs = FILE_ATTRIBUTE_READONLY
  392. }
  393. h, e := CreateFile(pathp, access, sharemode, sa, createmode, attrs, 0)
  394. return h, e
  395. }
  396. func Read(fd Handle, p []byte) (n int, err error) {
  397. var done uint32
  398. e := ReadFile(fd, p, &done, nil)
  399. if e != nil {
  400. if e == ERROR_BROKEN_PIPE {
  401. // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin
  402. return 0, nil
  403. }
  404. return 0, e
  405. }
  406. if raceenabled {
  407. if done > 0 {
  408. raceWriteRange(unsafe.Pointer(&p[0]), int(done))
  409. }
  410. raceAcquire(unsafe.Pointer(&ioSync))
  411. }
  412. return int(done), nil
  413. }
  414. func Write(fd Handle, p []byte) (n int, err error) {
  415. if raceenabled {
  416. raceReleaseMerge(unsafe.Pointer(&ioSync))
  417. }
  418. var done uint32
  419. e := WriteFile(fd, p, &done, nil)
  420. if e != nil {
  421. return 0, e
  422. }
  423. if raceenabled && done > 0 {
  424. raceReadRange(unsafe.Pointer(&p[0]), int(done))
  425. }
  426. return int(done), nil
  427. }
  428. var ioSync int64
  429. func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {
  430. var w uint32
  431. switch whence {
  432. case 0:
  433. w = FILE_BEGIN
  434. case 1:
  435. w = FILE_CURRENT
  436. case 2:
  437. w = FILE_END
  438. }
  439. hi := int32(offset >> 32)
  440. lo := int32(offset)
  441. // use GetFileType to check pipe, pipe can't do seek
  442. ft, _ := GetFileType(fd)
  443. if ft == FILE_TYPE_PIPE {
  444. return 0, syscall.EPIPE
  445. }
  446. rlo, e := SetFilePointer(fd, lo, &hi, w)
  447. if e != nil {
  448. return 0, e
  449. }
  450. return int64(hi)<<32 + int64(rlo), nil
  451. }
  452. func Close(fd Handle) (err error) {
  453. return CloseHandle(fd)
  454. }
  455. var (
  456. Stdin = getStdHandle(STD_INPUT_HANDLE)
  457. Stdout = getStdHandle(STD_OUTPUT_HANDLE)
  458. Stderr = getStdHandle(STD_ERROR_HANDLE)
  459. )
  460. func getStdHandle(stdhandle uint32) (fd Handle) {
  461. r, _ := GetStdHandle(stdhandle)
  462. CloseOnExec(r)
  463. return r
  464. }
  465. const ImplementsGetwd = true
  466. func Getwd() (wd string, err error) {
  467. b := make([]uint16, 300)
  468. n, e := GetCurrentDirectory(uint32(len(b)), &b[0])
  469. if e != nil {
  470. return "", e
  471. }
  472. return string(utf16.Decode(b[0:n])), nil
  473. }
  474. func Chdir(path string) (err error) {
  475. pathp, err := UTF16PtrFromString(path)
  476. if err != nil {
  477. return err
  478. }
  479. return SetCurrentDirectory(pathp)
  480. }
  481. func Mkdir(path string, mode uint32) (err error) {
  482. pathp, err := UTF16PtrFromString(path)
  483. if err != nil {
  484. return err
  485. }
  486. return CreateDirectory(pathp, nil)
  487. }
  488. func Rmdir(path string) (err error) {
  489. pathp, err := UTF16PtrFromString(path)
  490. if err != nil {
  491. return err
  492. }
  493. return RemoveDirectory(pathp)
  494. }
  495. func Unlink(path string) (err error) {
  496. pathp, err := UTF16PtrFromString(path)
  497. if err != nil {
  498. return err
  499. }
  500. return DeleteFile(pathp)
  501. }
  502. func Rename(oldpath, newpath string) (err error) {
  503. from, err := UTF16PtrFromString(oldpath)
  504. if err != nil {
  505. return err
  506. }
  507. to, err := UTF16PtrFromString(newpath)
  508. if err != nil {
  509. return err
  510. }
  511. return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)
  512. }
  513. func ComputerName() (name string, err error) {
  514. var n uint32 = MAX_COMPUTERNAME_LENGTH + 1
  515. b := make([]uint16, n)
  516. e := GetComputerName(&b[0], &n)
  517. if e != nil {
  518. return "", e
  519. }
  520. return string(utf16.Decode(b[0:n])), nil
  521. }
  522. func DurationSinceBoot() time.Duration {
  523. return time.Duration(getTickCount64()) * time.Millisecond
  524. }
  525. func Ftruncate(fd Handle, length int64) (err error) {
  526. curoffset, e := Seek(fd, 0, 1)
  527. if e != nil {
  528. return e
  529. }
  530. defer Seek(fd, curoffset, 0)
  531. _, e = Seek(fd, length, 0)
  532. if e != nil {
  533. return e
  534. }
  535. e = SetEndOfFile(fd)
  536. if e != nil {
  537. return e
  538. }
  539. return nil
  540. }
  541. func Gettimeofday(tv *Timeval) (err error) {
  542. var ft Filetime
  543. GetSystemTimeAsFileTime(&ft)
  544. *tv = NsecToTimeval(ft.Nanoseconds())
  545. return nil
  546. }
  547. func Pipe(p []Handle) (err error) {
  548. if len(p) != 2 {
  549. return syscall.EINVAL
  550. }
  551. var r, w Handle
  552. e := CreatePipe(&r, &w, makeInheritSa(), 0)
  553. if e != nil {
  554. return e
  555. }
  556. p[0] = r
  557. p[1] = w
  558. return nil
  559. }
  560. func Utimes(path string, tv []Timeval) (err error) {
  561. if len(tv) != 2 {
  562. return syscall.EINVAL
  563. }
  564. pathp, e := UTF16PtrFromString(path)
  565. if e != nil {
  566. return e
  567. }
  568. h, e := CreateFile(pathp,
  569. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
  570. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
  571. if e != nil {
  572. return e
  573. }
  574. defer Close(h)
  575. a := NsecToFiletime(tv[0].Nanoseconds())
  576. w := NsecToFiletime(tv[1].Nanoseconds())
  577. return SetFileTime(h, nil, &a, &w)
  578. }
  579. func UtimesNano(path string, ts []Timespec) (err error) {
  580. if len(ts) != 2 {
  581. return syscall.EINVAL
  582. }
  583. pathp, e := UTF16PtrFromString(path)
  584. if e != nil {
  585. return e
  586. }
  587. h, e := CreateFile(pathp,
  588. FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
  589. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
  590. if e != nil {
  591. return e
  592. }
  593. defer Close(h)
  594. a := NsecToFiletime(TimespecToNsec(ts[0]))
  595. w := NsecToFiletime(TimespecToNsec(ts[1]))
  596. return SetFileTime(h, nil, &a, &w)
  597. }
  598. func Fsync(fd Handle) (err error) {
  599. return FlushFileBuffers(fd)
  600. }
  601. func Chmod(path string, mode uint32) (err error) {
  602. p, e := UTF16PtrFromString(path)
  603. if e != nil {
  604. return e
  605. }
  606. attrs, e := GetFileAttributes(p)
  607. if e != nil {
  608. return e
  609. }
  610. if mode&S_IWRITE != 0 {
  611. attrs &^= FILE_ATTRIBUTE_READONLY
  612. } else {
  613. attrs |= FILE_ATTRIBUTE_READONLY
  614. }
  615. return SetFileAttributes(p, attrs)
  616. }
  617. func LoadGetSystemTimePreciseAsFileTime() error {
  618. return procGetSystemTimePreciseAsFileTime.Find()
  619. }
  620. func LoadCancelIoEx() error {
  621. return procCancelIoEx.Find()
  622. }
  623. func LoadSetFileCompletionNotificationModes() error {
  624. return procSetFileCompletionNotificationModes.Find()
  625. }
  626. func WaitForMultipleObjects(handles []Handle, waitAll bool, waitMilliseconds uint32) (event uint32, err error) {
  627. // Every other win32 array API takes arguments as "pointer, count", except for this function. So we
  628. // can't declare it as a usual [] type, because mksyscall will use the opposite order. We therefore
  629. // trivially stub this ourselves.
  630. var handlePtr *Handle
  631. if len(handles) > 0 {
  632. handlePtr = &handles[0]
  633. }
  634. return waitForMultipleObjects(uint32(len(handles)), uintptr(unsafe.Pointer(handlePtr)), waitAll, waitMilliseconds)
  635. }
  636. // net api calls
  637. const socket_error = uintptr(^uint32(0))
  638. //sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup
  639. //sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
  640. //sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl
  641. //sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
  642. //sys sendto(s Handle, buf []byte, flags int32, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto
  643. //sys recvfrom(s Handle, buf []byte, flags int32, from *RawSockaddrAny, fromlen *int32) (n int32, err error) [failretval==-1] = ws2_32.recvfrom
  644. //sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
  645. //sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
  646. //sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
  647. //sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect
  648. //sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname
  649. //sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername
  650. //sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen
  651. //sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown
  652. //sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket
  653. //sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx
  654. //sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs
  655. //sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv
  656. //sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend
  657. //sys WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom
  658. //sys WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo
  659. //sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname
  660. //sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname
  661. //sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs
  662. //sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname
  663. //sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W
  664. //sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree
  665. //sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W
  666. //sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW
  667. //sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW
  668. //sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry
  669. //sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo
  670. //sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes
  671. //sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW
  672. //sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses
  673. //sys GetACP() (acp uint32) = kernel32.GetACP
  674. //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar
  675. // For testing: clients can set this flag to force
  676. // creation of IPv6 sockets to return EAFNOSUPPORT.
  677. var SocketDisableIPv6 bool
  678. type RawSockaddrInet4 struct {
  679. Family uint16
  680. Port uint16
  681. Addr [4]byte /* in_addr */
  682. Zero [8]uint8
  683. }
  684. type RawSockaddrInet6 struct {
  685. Family uint16
  686. Port uint16
  687. Flowinfo uint32
  688. Addr [16]byte /* in6_addr */
  689. Scope_id uint32
  690. }
  691. type RawSockaddr struct {
  692. Family uint16
  693. Data [14]int8
  694. }
  695. type RawSockaddrAny struct {
  696. Addr RawSockaddr
  697. Pad [100]int8
  698. }
  699. type Sockaddr interface {
  700. sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs
  701. }
  702. type SockaddrInet4 struct {
  703. Port int
  704. Addr [4]byte
  705. raw RawSockaddrInet4
  706. }
  707. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {
  708. if sa.Port < 0 || sa.Port > 0xFFFF {
  709. return nil, 0, syscall.EINVAL
  710. }
  711. sa.raw.Family = AF_INET
  712. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  713. p[0] = byte(sa.Port >> 8)
  714. p[1] = byte(sa.Port)
  715. for i := 0; i < len(sa.Addr); i++ {
  716. sa.raw.Addr[i] = sa.Addr[i]
  717. }
  718. return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
  719. }
  720. type SockaddrInet6 struct {
  721. Port int
  722. ZoneId uint32
  723. Addr [16]byte
  724. raw RawSockaddrInet6
  725. }
  726. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {
  727. if sa.Port < 0 || sa.Port > 0xFFFF {
  728. return nil, 0, syscall.EINVAL
  729. }
  730. sa.raw.Family = AF_INET6
  731. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  732. p[0] = byte(sa.Port >> 8)
  733. p[1] = byte(sa.Port)
  734. sa.raw.Scope_id = sa.ZoneId
  735. for i := 0; i < len(sa.Addr); i++ {
  736. sa.raw.Addr[i] = sa.Addr[i]
  737. }
  738. return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
  739. }
  740. type RawSockaddrUnix struct {
  741. Family uint16
  742. Path [UNIX_PATH_MAX]int8
  743. }
  744. type SockaddrUnix struct {
  745. Name string
  746. raw RawSockaddrUnix
  747. }
  748. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {
  749. name := sa.Name
  750. n := len(name)
  751. if n > len(sa.raw.Path) {
  752. return nil, 0, syscall.EINVAL
  753. }
  754. if n == len(sa.raw.Path) && name[0] != '@' {
  755. return nil, 0, syscall.EINVAL
  756. }
  757. sa.raw.Family = AF_UNIX
  758. for i := 0; i < n; i++ {
  759. sa.raw.Path[i] = int8(name[i])
  760. }
  761. // length is family (uint16), name, NUL.
  762. sl := int32(2)
  763. if n > 0 {
  764. sl += int32(n) + 1
  765. }
  766. if sa.raw.Path[0] == '@' {
  767. sa.raw.Path[0] = 0
  768. // Don't count trailing NUL for abstract address.
  769. sl--
  770. }
  771. return unsafe.Pointer(&sa.raw), sl, nil
  772. }
  773. func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {
  774. switch rsa.Addr.Family {
  775. case AF_UNIX:
  776. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  777. sa := new(SockaddrUnix)
  778. if pp.Path[0] == 0 {
  779. // "Abstract" Unix domain socket.
  780. // Rewrite leading NUL as @ for textual display.
  781. // (This is the standard convention.)
  782. // Not friendly to overwrite in place,
  783. // but the callers below don't care.
  784. pp.Path[0] = '@'
  785. }
  786. // Assume path ends at NUL.
  787. // This is not technically the Linux semantics for
  788. // abstract Unix domain sockets--they are supposed
  789. // to be uninterpreted fixed-size binary blobs--but
  790. // everyone uses this convention.
  791. n := 0
  792. for n < len(pp.Path) && pp.Path[n] != 0 {
  793. n++
  794. }
  795. bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
  796. sa.Name = string(bytes)
  797. return sa, nil
  798. case AF_INET:
  799. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  800. sa := new(SockaddrInet4)
  801. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  802. sa.Port = int(p[0])<<8 + int(p[1])
  803. for i := 0; i < len(sa.Addr); i++ {
  804. sa.Addr[i] = pp.Addr[i]
  805. }
  806. return sa, nil
  807. case AF_INET6:
  808. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  809. sa := new(SockaddrInet6)
  810. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  811. sa.Port = int(p[0])<<8 + int(p[1])
  812. sa.ZoneId = pp.Scope_id
  813. for i := 0; i < len(sa.Addr); i++ {
  814. sa.Addr[i] = pp.Addr[i]
  815. }
  816. return sa, nil
  817. }
  818. return nil, syscall.EAFNOSUPPORT
  819. }
  820. func Socket(domain, typ, proto int) (fd Handle, err error) {
  821. if domain == AF_INET6 && SocketDisableIPv6 {
  822. return InvalidHandle, syscall.EAFNOSUPPORT
  823. }
  824. return socket(int32(domain), int32(typ), int32(proto))
  825. }
  826. func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {
  827. v := int32(value)
  828. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))
  829. }
  830. func Bind(fd Handle, sa Sockaddr) (err error) {
  831. ptr, n, err := sa.sockaddr()
  832. if err != nil {
  833. return err
  834. }
  835. return bind(fd, ptr, n)
  836. }
  837. func Connect(fd Handle, sa Sockaddr) (err error) {
  838. ptr, n, err := sa.sockaddr()
  839. if err != nil {
  840. return err
  841. }
  842. return connect(fd, ptr, n)
  843. }
  844. func Getsockname(fd Handle) (sa Sockaddr, err error) {
  845. var rsa RawSockaddrAny
  846. l := int32(unsafe.Sizeof(rsa))
  847. if err = getsockname(fd, &rsa, &l); err != nil {
  848. return
  849. }
  850. return rsa.Sockaddr()
  851. }
  852. func Getpeername(fd Handle) (sa Sockaddr, err error) {
  853. var rsa RawSockaddrAny
  854. l := int32(unsafe.Sizeof(rsa))
  855. if err = getpeername(fd, &rsa, &l); err != nil {
  856. return
  857. }
  858. return rsa.Sockaddr()
  859. }
  860. func Listen(s Handle, n int) (err error) {
  861. return listen(s, int32(n))
  862. }
  863. func Shutdown(fd Handle, how int) (err error) {
  864. return shutdown(fd, int32(how))
  865. }
  866. func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {
  867. rsa, l, err := to.sockaddr()
  868. if err != nil {
  869. return err
  870. }
  871. return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine)
  872. }
  873. func LoadGetAddrInfo() error {
  874. return procGetAddrInfoW.Find()
  875. }
  876. var connectExFunc struct {
  877. once sync.Once
  878. addr uintptr
  879. err error
  880. }
  881. func LoadConnectEx() error {
  882. connectExFunc.once.Do(func() {
  883. var s Handle
  884. s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
  885. if connectExFunc.err != nil {
  886. return
  887. }
  888. defer CloseHandle(s)
  889. var n uint32
  890. connectExFunc.err = WSAIoctl(s,
  891. SIO_GET_EXTENSION_FUNCTION_POINTER,
  892. (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),
  893. uint32(unsafe.Sizeof(WSAID_CONNECTEX)),
  894. (*byte)(unsafe.Pointer(&connectExFunc.addr)),
  895. uint32(unsafe.Sizeof(connectExFunc.addr)),
  896. &n, nil, 0)
  897. })
  898. return connectExFunc.err
  899. }
  900. func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {
  901. r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0)
  902. if r1 == 0 {
  903. if e1 != 0 {
  904. err = error(e1)
  905. } else {
  906. err = syscall.EINVAL
  907. }
  908. }
  909. return
  910. }
  911. func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {
  912. err := LoadConnectEx()
  913. if err != nil {
  914. return errorspkg.New("failed to find ConnectEx: " + err.Error())
  915. }
  916. ptr, n, err := sa.sockaddr()
  917. if err != nil {
  918. return err
  919. }
  920. return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)
  921. }
  922. var sendRecvMsgFunc struct {
  923. once sync.Once
  924. sendAddr uintptr
  925. recvAddr uintptr
  926. err error
  927. }
  928. func loadWSASendRecvMsg() error {
  929. sendRecvMsgFunc.once.Do(func() {
  930. var s Handle
  931. s, sendRecvMsgFunc.err = Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  932. if sendRecvMsgFunc.err != nil {
  933. return
  934. }
  935. defer CloseHandle(s)
  936. var n uint32
  937. sendRecvMsgFunc.err = WSAIoctl(s,
  938. SIO_GET_EXTENSION_FUNCTION_POINTER,
  939. (*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)),
  940. uint32(unsafe.Sizeof(WSAID_WSARECVMSG)),
  941. (*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)),
  942. uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)),
  943. &n, nil, 0)
  944. if sendRecvMsgFunc.err != nil {
  945. return
  946. }
  947. sendRecvMsgFunc.err = WSAIoctl(s,
  948. SIO_GET_EXTENSION_FUNCTION_POINTER,
  949. (*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)),
  950. uint32(unsafe.Sizeof(WSAID_WSASENDMSG)),
  951. (*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)),
  952. uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)),
  953. &n, nil, 0)
  954. })
  955. return sendRecvMsgFunc.err
  956. }
  957. func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *Overlapped, croutine *byte) error {
  958. err := loadWSASendRecvMsg()
  959. if err != nil {
  960. return err
  961. }
  962. r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
  963. if r1 == socket_error {
  964. if e1 != 0 {
  965. err = errnoErr(e1)
  966. } else {
  967. err = syscall.EINVAL
  968. }
  969. }
  970. return err
  971. }
  972. func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overlapped, croutine *byte) error {
  973. err := loadWSASendRecvMsg()
  974. if err != nil {
  975. return err
  976. }
  977. r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0)
  978. if r1 == socket_error {
  979. if e1 != 0 {
  980. err = errnoErr(e1)
  981. } else {
  982. err = syscall.EINVAL
  983. }
  984. }
  985. return err
  986. }
  987. // Invented structures to support what package os expects.
  988. type Rusage struct {
  989. CreationTime Filetime
  990. ExitTime Filetime
  991. KernelTime Filetime
  992. UserTime Filetime
  993. }
  994. type WaitStatus struct {
  995. ExitCode uint32
  996. }
  997. func (w WaitStatus) Exited() bool { return true }
  998. func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }
  999. func (w WaitStatus) Signal() Signal { return -1 }
  1000. func (w WaitStatus) CoreDump() bool { return false }
  1001. func (w WaitStatus) Stopped() bool { return false }
  1002. func (w WaitStatus) Continued() bool { return false }
  1003. func (w WaitStatus) StopSignal() Signal { return -1 }
  1004. func (w WaitStatus) Signaled() bool { return false }
  1005. func (w WaitStatus) TrapCause() int { return -1 }
  1006. // Timespec is an invented structure on Windows, but here for
  1007. // consistency with the corresponding package for other operating systems.
  1008. type Timespec struct {
  1009. Sec int64
  1010. Nsec int64
  1011. }
  1012. func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
  1013. func NsecToTimespec(nsec int64) (ts Timespec) {
  1014. ts.Sec = nsec / 1e9
  1015. ts.Nsec = nsec % 1e9
  1016. return
  1017. }
  1018. // TODO(brainman): fix all needed for net
  1019. func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS }
  1020. func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
  1021. var rsa RawSockaddrAny
  1022. l := int32(unsafe.Sizeof(rsa))
  1023. n32, err := recvfrom(fd, p, int32(flags), &rsa, &l)
  1024. n = int(n32)
  1025. if err != nil {
  1026. return
  1027. }
  1028. from, err = rsa.Sockaddr()
  1029. return
  1030. }
  1031. func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) {
  1032. ptr, l, err := to.sockaddr()
  1033. if err != nil {
  1034. return err
  1035. }
  1036. return sendto(fd, p, int32(flags), ptr, l)
  1037. }
  1038. func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS }
  1039. // The Linger struct is wrong but we only noticed after Go 1.
  1040. // sysLinger is the real system call structure.
  1041. // BUG(brainman): The definition of Linger is not appropriate for direct use
  1042. // with Setsockopt and Getsockopt.
  1043. // Use SetsockoptLinger instead.
  1044. type Linger struct {
  1045. Onoff int32
  1046. Linger int32
  1047. }
  1048. type sysLinger struct {
  1049. Onoff uint16
  1050. Linger uint16
  1051. }
  1052. type IPMreq struct {
  1053. Multiaddr [4]byte /* in_addr */
  1054. Interface [4]byte /* in_addr */
  1055. }
  1056. type IPv6Mreq struct {
  1057. Multiaddr [16]byte /* in6_addr */
  1058. Interface uint32
  1059. }
  1060. func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, syscall.EWINDOWS }
  1061. func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {
  1062. sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}
  1063. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))
  1064. }
  1065. func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {
  1066. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)
  1067. }
  1068. func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {
  1069. return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))
  1070. }
  1071. func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) {
  1072. return syscall.EWINDOWS
  1073. }
  1074. func Getpid() (pid int) { return int(GetCurrentProcessId()) }
  1075. func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {
  1076. // NOTE(rsc): The Win32finddata struct is wrong for the system call:
  1077. // the two paths are each one uint16 short. Use the correct struct,
  1078. // a win32finddata1, and then copy the results out.
  1079. // There is no loss of expressivity here, because the final
  1080. // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.
  1081. // For Go 1.1, we might avoid the allocation of win32finddata1 here
  1082. // by adding a final Bug [2]uint16 field to the struct and then
  1083. // adjusting the fields in the result directly.
  1084. var data1 win32finddata1
  1085. handle, err = findFirstFile1(name, &data1)
  1086. if err == nil {
  1087. copyFindData(data, &data1)
  1088. }
  1089. return
  1090. }
  1091. func FindNextFile(handle Handle, data *Win32finddata) (err error) {
  1092. var data1 win32finddata1
  1093. err = findNextFile1(handle, &data1)
  1094. if err == nil {
  1095. copyFindData(data, &data1)
  1096. }
  1097. return
  1098. }
  1099. func getProcessEntry(pid int) (*ProcessEntry32, error) {
  1100. snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
  1101. if err != nil {
  1102. return nil, err
  1103. }
  1104. defer CloseHandle(snapshot)
  1105. var procEntry ProcessEntry32
  1106. procEntry.Size = uint32(unsafe.Sizeof(procEntry))
  1107. if err = Process32First(snapshot, &procEntry); err != nil {
  1108. return nil, err
  1109. }
  1110. for {
  1111. if procEntry.ProcessID == uint32(pid) {
  1112. return &procEntry, nil
  1113. }
  1114. err = Process32Next(snapshot, &procEntry)
  1115. if err != nil {
  1116. return nil, err
  1117. }
  1118. }
  1119. }
  1120. func Getppid() (ppid int) {
  1121. pe, err := getProcessEntry(Getpid())
  1122. if err != nil {
  1123. return -1
  1124. }
  1125. return int(pe.ParentProcessID)
  1126. }
  1127. // TODO(brainman): fix all needed for os
  1128. func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS }
  1129. func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS }
  1130. func Symlink(path, link string) (err error) { return syscall.EWINDOWS }
  1131. func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS }
  1132. func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1133. func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1134. func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS }
  1135. func Getuid() (uid int) { return -1 }
  1136. func Geteuid() (euid int) { return -1 }
  1137. func Getgid() (gid int) { return -1 }
  1138. func Getegid() (egid int) { return -1 }
  1139. func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS }
  1140. type Signal int
  1141. func (s Signal) Signal() {}
  1142. func (s Signal) String() string {
  1143. if 0 <= s && int(s) < len(signals) {
  1144. str := signals[s]
  1145. if str != "" {
  1146. return str
  1147. }
  1148. }
  1149. return "signal " + itoa(int(s))
  1150. }
  1151. func LoadCreateSymbolicLink() error {
  1152. return procCreateSymbolicLinkW.Find()
  1153. }
  1154. // Readlink returns the destination of the named symbolic link.
  1155. func Readlink(path string, buf []byte) (n int, err error) {
  1156. fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,
  1157. FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)
  1158. if err != nil {
  1159. return -1, err
  1160. }
  1161. defer CloseHandle(fd)
  1162. rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  1163. var bytesReturned uint32
  1164. err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
  1165. if err != nil {
  1166. return -1, err
  1167. }
  1168. rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
  1169. var s string
  1170. switch rdb.ReparseTag {
  1171. case IO_REPARSE_TAG_SYMLINK:
  1172. data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1173. p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1174. s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
  1175. case IO_REPARSE_TAG_MOUNT_POINT:
  1176. data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
  1177. p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
  1178. s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
  1179. default:
  1180. // the path is not a symlink or junction but another type of reparse
  1181. // point
  1182. return -1, syscall.ENOENT
  1183. }
  1184. n = copy(buf, []byte(s))
  1185. return n, nil
  1186. }
  1187. // GUIDFromString parses a string in the form of
  1188. // "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" into a GUID.
  1189. func GUIDFromString(str string) (GUID, error) {
  1190. guid := GUID{}
  1191. str16, err := syscall.UTF16PtrFromString(str)
  1192. if err != nil {
  1193. return guid, err
  1194. }
  1195. err = clsidFromString(str16, &guid)
  1196. if err != nil {
  1197. return guid, err
  1198. }
  1199. return guid, nil
  1200. }
  1201. // GenerateGUID creates a new random GUID.
  1202. func GenerateGUID() (GUID, error) {
  1203. guid := GUID{}
  1204. err := coCreateGuid(&guid)
  1205. if err != nil {
  1206. return guid, err
  1207. }
  1208. return guid, nil
  1209. }
  1210. // String returns the canonical string form of the GUID,
  1211. // in the form of "{XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}".
  1212. func (guid GUID) String() string {
  1213. var str [100]uint16
  1214. chars := stringFromGUID2(&guid, &str[0], int32(len(str)))
  1215. if chars <= 1 {
  1216. return ""
  1217. }
  1218. return string(utf16.Decode(str[:chars-1]))
  1219. }
  1220. // KnownFolderPath returns a well-known folder path for the current user, specified by one of
  1221. // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.
  1222. func KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {
  1223. return Token(0).KnownFolderPath(folderID, flags)
  1224. }
  1225. // KnownFolderPath returns a well-known folder path for the user token, specified by one of
  1226. // the FOLDERID_ constants, and chosen and optionally created based on a KF_ flag.
  1227. func (t Token) KnownFolderPath(folderID *KNOWNFOLDERID, flags uint32) (string, error) {
  1228. var p *uint16
  1229. err := shGetKnownFolderPath(folderID, flags, t, &p)
  1230. if err != nil {
  1231. return "", err
  1232. }
  1233. defer CoTaskMemFree(unsafe.Pointer(p))
  1234. return UTF16ToString((*[(1 << 30) - 1]uint16)(unsafe.Pointer(p))[:]), nil
  1235. }
  1236. // RtlGetVersion returns the version of the underlying operating system, ignoring
  1237. // manifest semantics but is affected by the application compatibility layer.
  1238. func RtlGetVersion() *OsVersionInfoEx {
  1239. info := &OsVersionInfoEx{}
  1240. info.osVersionInfoSize = uint32(unsafe.Sizeof(*info))
  1241. // According to documentation, this function always succeeds.
  1242. // The function doesn't even check the validity of the
  1243. // osVersionInfoSize member. Disassembling ntdll.dll indicates
  1244. // that the documentation is indeed correct about that.
  1245. _ = rtlGetVersion(info)
  1246. return info
  1247. }
  1248. // RtlGetNtVersionNumbers returns the version of the underlying operating system,
  1249. // ignoring manifest semantics and the application compatibility layer.
  1250. func RtlGetNtVersionNumbers() (majorVersion, minorVersion, buildNumber uint32) {
  1251. rtlGetNtVersionNumbers(&majorVersion, &minorVersion, &buildNumber)
  1252. buildNumber &= 0xffff
  1253. return
  1254. }
  1255. // GetProcessPreferredUILanguages retrieves the process preferred UI languages.
  1256. func GetProcessPreferredUILanguages(flags uint32) ([]string, error) {
  1257. return getUILanguages(flags, getProcessPreferredUILanguages)
  1258. }
  1259. // GetThreadPreferredUILanguages retrieves the thread preferred UI languages for the current thread.
  1260. func GetThreadPreferredUILanguages(flags uint32) ([]string, error) {
  1261. return getUILanguages(flags, getThreadPreferredUILanguages)
  1262. }
  1263. // GetUserPreferredUILanguages retrieves information about the user preferred UI languages.
  1264. func GetUserPreferredUILanguages(flags uint32) ([]string, error) {
  1265. return getUILanguages(flags, getUserPreferredUILanguages)
  1266. }
  1267. // GetSystemPreferredUILanguages retrieves the system preferred UI languages.
  1268. func GetSystemPreferredUILanguages(flags uint32) ([]string, error) {
  1269. return getUILanguages(flags, getSystemPreferredUILanguages)
  1270. }
  1271. func getUILanguages(flags uint32, f func(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) error) ([]string, error) {
  1272. size := uint32(128)
  1273. for {
  1274. var numLanguages uint32
  1275. buf := make([]uint16, size)
  1276. err := f(flags, &numLanguages, &buf[0], &size)
  1277. if err == ERROR_INSUFFICIENT_BUFFER {
  1278. continue
  1279. }
  1280. if err != nil {
  1281. return nil, err
  1282. }
  1283. buf = buf[:size]
  1284. if numLanguages == 0 || len(buf) == 0 { // GetProcessPreferredUILanguages may return numLanguages==0 with "\0\0"
  1285. return []string{}, nil
  1286. }
  1287. if buf[len(buf)-1] == 0 {
  1288. buf = buf[:len(buf)-1] // remove terminating null
  1289. }
  1290. languages := make([]string, 0, numLanguages)
  1291. from := 0
  1292. for i, c := range buf {
  1293. if c == 0 {
  1294. languages = append(languages, string(utf16.Decode(buf[from:i])))
  1295. from = i + 1
  1296. }
  1297. }
  1298. return languages, nil
  1299. }
  1300. }