ggstd 0.1.0

Partial implementation of Go standard library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// Copyright 2023 The rust-ggstd authors. All rights reserved.
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

use crate::winapi_;

use super::utf16_from_string;
use super::utf16_to_string;

// package syscall

// import (
// 	"unsafe"
// )

// const (
// 	STANDARD_RIGHTS_REQUIRED = 0xf0000
// 	STANDARD_RIGHTS_READ     = 0x20000
// 	STANDARD_RIGHTS_WRITE    = 0x20000
// 	STANDARD_RIGHTS_EXECUTE  = 0x20000
// 	STANDARD_RIGHTS_ALL      = 0x1F0000
// )

// const (
// 	NameUnknown          = 0
// 	NameFullyQualifiedDN = 1
pub const NAME_SAM_COMPATIBLE: u32 = 2;
pub const NAME_DISPLAY: u32 = 3;
// 	NameUniqueId         = 6
// 	NameCanonical        = 7
// 	NameUserPrincipal    = 8
// 	NameCanonicalEx      = 9
// 	NameServicePrincipal = 10
// 	NameDnsDomain        = 12
// )

// // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
// // https://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx
// //sys	TranslateName(accName *uint16, accNameFormat u32, desiredNameFormat u32, translatedName *uint16, nSize *u32) (err error) [failretval&0xff==0] = secur32.TranslateNameW
extern "system" {
    pub fn TranslateNameW(
        lpAccountName: winapi_::LPCWSTR,
        AccountNameFormat: u32,
        DesiredNameFormat: u32,
        lpTranslatedName: winapi_::LPWSTR,
        nSize: *mut u32,
    ) -> winapi_::BOOLEAN;
}

// //sys	GetUserNameEx(nameFormat u32, nameBuffre *uint16, nSize *u32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW

/// translate_account_name converts a directory service
/// object name from one format to another.
pub fn translate_account_name(
    username: &str,
    from_format: u32,
    to_format: u32,
) -> std::io::Result<String> {
    let u = utf16_from_string(username);
    let mut n = 50_u32;
    let mut b = vec![0_u16; n as usize];
    loop {
        let e =
            unsafe { TranslateNameW(u.as_ptr(), from_format, to_format, b.as_mut_ptr(), &mut n) };
        if e == 0 {
            let last_err = std::io::Error::last_os_error();
            if last_err.raw_os_error().unwrap() == winapi_::ERROR_INSUFFICIENT_BUFFER as i32 {
                b.resize(n as usize, 0);
                continue;
            }
            return Err(last_err);
        }
        return Ok(utf16_to_string(&b[..n as usize]));
    }
}

// const (
// 	// do not reorder
// 	NetSetupUnknownStatus = iota
// 	NetSetupUnjoined
// 	NetSetupWorkgroupName
// 	NetSetupDomainName
// )

// type UserInfo10 struct {
// 	Name       *uint16
// 	Comment    *uint16
// 	UsrComment *uint16
// 	FullName   *uint16
// }

// //sys	NetUserGetInfo(serverName *uint16, userName *uint16, level u32, buf **byte) (neterr error) = netapi32.NetUserGetInfo
// //sys	NetGetJoinInformation(server *uint16, name **uint16, bufType *u32) (neterr error) = netapi32.NetGetJoinInformation
// //sys	NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree

// const (
// 	// do not reorder
// 	SidTypeUser = 1 + iota
// 	SidTypeGroup
// 	SidTypeDomain
// 	SidTypeAlias
// 	SidTypeWellKnownGroup
// 	SidTypeDeletedAccount
// 	SidTypeInvalid
// 	SidTypeUnknown
// 	SidTypeComputer
// 	SidTypeLabel
// )

// //sys	LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *u32, refdDomainName *uint16, refdDomainNameLen *u32, use *u32) (err error) = advapi32.LookupAccountSidW
// //sys	LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *u32, refdDomainName *uint16, refdDomainNameLen *u32, use *u32) (err error) = advapi32.LookupAccountNameW
// //sys	ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW
// //sys	ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW
// //sys	GetLengthSid(sid *SID) (len u32) = advapi32.GetLengthSid
// //sys	CopySid(destSidLen u32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid

// /// The security identifier (SID) structure is a variable-length
// /// structure used to uniquely identify users or groups.
// struct SID {}

// // StringToSid converts a string-format security identifier
// // sid into a valid, functional sid.
// fn StringToSid(s string) (*SID, error) {
// 	var sid *SID
// 	p, e := UTF16PtrFromString(s)
// 	if e != nil {
// 		return nil, e
// 	}
// 	e = ConvertStringSidToSid(p, &sid)
// 	if e != nil {
// 		return nil, e
// 	}
// 	defer LocalFree((Handle)(unsafe.Pointer(sid)))
// 	return sid.Copy()
// }

// // LookupSID retrieves a security identifier sid for the account
// // and the name of the domain on which the account was found.
// // System specify target computer to search.
// fn LookupSID(system, account string) (sid *SID, domain string, accType u32, err error) {
// 	if len(account) == 0 {
// 		return nil, "", 0, EINVAL
// 	}
// 	acc, e := UTF16PtrFromString(account)
// 	if e != nil {
// 		return nil, "", 0, e
// 	}
// 	var sys *uint16
// 	if len(system) > 0 {
// 		sys, e = UTF16PtrFromString(system)
// 		if e != nil {
// 			return nil, "", 0, e
// 		}
// 	}
// 	n := u32(50)
// 	dn := u32(50)
// 	for {
// 		b := make([]byte, n)
// 		db := make([]uint16, dn)
// 		sid = (*SID)(unsafe.Pointer(&b[0]))
// 		e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType)
// 		if e == nil {
// 			return sid, UTF16ToString(db), accType, nil
// 		}
// 		if e != ERROR_INSUFFICIENT_BUFFER {
// 			return nil, "", 0, e
// 		}
// 		if n <= u32(len(b)) {
// 			return nil, "", 0, e
// 		}
// 	}
// }

// impl std::fmt::Display for winapi_::PSID {
//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//         todo!()
//     }
// }

/// String converts sid to a string format
/// suitable for display, storage, or transmission.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn sid_to_string(sid: winapi_::PSID) -> std::io::Result<String> {
    // fn (sid *SID) String() (string, error) {

    let mut raw_string: winapi_::LPWSTR = std::ptr::null_mut();
    let res = unsafe { winapi_::ConvertSidToStringSidW(sid, &mut raw_string) };
    if res == 0 {
        return Err(std::io::Error::last_os_error());
    }
    let s = super::utf16_ptr_to_string(raw_string);
    unsafe { winapi_::LocalFree(raw_string as *mut winapi_::c_void) };
    Ok(s)
}

// // Len returns the length, in bytes, of a valid security identifier sid.
// fn (sid *SID) Len() isize {
// 	return isize(GetLengthSid(sid))
// }

// // Copy creates a duplicate of security identifier sid.
// fn (sid *SID) Copy() (*SID, error) {
// 	b := make([]byte, sid.Len())
// 	sid2 := (*SID)(unsafe.Pointer(&b[0]))
// 	e := CopySid(u32(len(b)), sid2, sid)
// 	if e != nil {
// 		return nil, e
// 	}
// 	return sid2, nil
// }

#[derive(Debug)]
pub struct AccontLookupResult {
    pub account: String,
    pub domain: String,
    pub acc_type: u32,
}

/// lookup_account retrieves the name of the account for this sid
/// and the name of the first domain on which this sid is found.
/// System specify target computer to search for.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub fn lookup_account(sid: winapi_::PSID, system: &str) -> std::io::Result<AccontLookupResult> {
    let system_wide_str: Vec<u16>;
    let mut system_wide_str_ptr = std::ptr::null::<u16>();
    if !system.is_empty() {
        system_wide_str = super::utf16_from_string(system);
        system_wide_str_ptr = system_wide_str.as_ptr();
    }
    let mut n = 50_u32;
    let mut dn = 50_u32;
    let mut b = vec![0_u16; n as usize];
    let mut db = vec![0_u16; dn as usize];
    let mut acc_type = 0;
    loop {
        let ret = unsafe {
            winapi_::LookupAccountSidW(
                system_wide_str_ptr,
                sid,
                b.as_mut_ptr(),
                &mut n,
                db.as_mut_ptr(),
                &mut dn,
                &mut acc_type,
            )
        };
        if ret == 0 {
            let last_err = std::io::Error::last_os_error();
            if last_err.raw_os_error().unwrap() == winapi_::ERROR_INSUFFICIENT_BUFFER as i32 {
                if n as usize > b.len() || dn as usize > db.len() {
                    b.resize(n as usize, 0);
                    db.resize(dn as usize, 0);
                    continue;
                } else {
                    return Err(last_err);
                }
            }
            return Err(last_err);
        }
        return Ok(AccontLookupResult {
            account: super::utf16_to_string(&b),
            domain: super::utf16_to_string(&db),
            acc_type,
        });
    }
}

// const (
// 	// do not reorder
// 	TOKEN_ASSIGN_PRIMARY = 1 << iota
// 	TOKEN_DUPLICATE
// 	TOKEN_IMPERSONATE
// 	TOKEN_QUERY
// 	TOKEN_QUERY_SOURCE
// 	TOKEN_ADJUST_PRIVILEGES
// 	TOKEN_ADJUST_GROUPS
// 	TOKEN_ADJUST_DEFAULT
// 	TOKEN_ADJUST_SESSIONID

// 	TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
// 		TOKEN_ASSIGN_PRIMARY |
// 		TOKEN_DUPLICATE |
// 		TOKEN_IMPERSONATE |
// 		TOKEN_QUERY |
// 		TOKEN_QUERY_SOURCE |
// 		TOKEN_ADJUST_PRIVILEGES |
// 		TOKEN_ADJUST_GROUPS |
// 		TOKEN_ADJUST_DEFAULT |
// 		TOKEN_ADJUST_SESSIONID
// 	TOKEN_READ  = STANDARD_RIGHTS_READ | TOKEN_QUERY
// 	TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
// 		TOKEN_ADJUST_PRIVILEGES |
// 		TOKEN_ADJUST_GROUPS |
// 		TOKEN_ADJUST_DEFAULT
// 	TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE
// )

// const (
// 	// do not reorder
// 	TokenUser = 1 + iota
// 	TokenGroups
// 	TokenPrivileges
// 	TokenOwner
// 	TokenPrimaryGroup
// 	TokenDefaultDacl
// 	TokenSource
// 	TokenType
// 	TokenImpersonationLevel
// 	TokenStatistics
// 	TokenRestrictedSids
// 	TokenSessionId
// 	TokenGroupsAndPrivileges
// 	TokenSessionReference
// 	TokenSandBoxInert
// 	TokenAuditPolicy
// 	TokenOrigin
// 	TokenElevationType
// 	TokenLinkedToken
// 	TokenElevation
// 	TokenHasRestrictions
// 	TokenAccessInformation
// 	TokenVirtualizationAllowed
// 	TokenVirtualizationEnabled
// 	TokenIntegrityLevel
// 	TokenUIAccess
// 	TokenMandatoryPolicy
// 	TokenLogonSid
// 	MaxTokenInfoClass
// )

// type SIDAndAttributes struct {
// 	Sid        *SID
// 	Attributes u32
// }

#[derive(Debug)]
pub struct Tokenuser {
    raw_data: Vec<u8>,
    // actual data is winapi_::TOKEN_USER
}

impl Tokenuser {
    fn get(&self) -> *const winapi_::TOKEN_USER {
        self.raw_data.as_ptr() as winapi_::PTOKEN_USER
    }

    pub fn get_sid(&self) -> winapi_::PSID {
        let p = self.get();
        unsafe { (*p).User.Sid }
    }
}

#[derive(Debug)]
pub struct Tokenprimarygroup {
    raw_data: Vec<u8>,
    // 	PrimaryGroup *SID
    // actual data is winapi_::TokenUser
}

impl Tokenprimarygroup {
    fn get(&self) -> *const winapi_::TOKEN_PRIMARY_GROUP {
        self.raw_data.as_ptr() as winapi_::PTOKEN_PRIMARY_GROUP
    }

    pub fn get_sid(&self) -> winapi_::PSID {
        let p = self.get();
        unsafe { (*p).PrimaryGroup }
    }
}

// //sys	OpenProcessToken(h Handle, access u32, token *Token) (err error) = advapi32.OpenProcessToken
// //sys	GetTokenInformation(t Token, infoClass u32, info *byte, infoLen u32, returnedLen *u32) (err error) = advapi32.GetTokenInformation
// //sys	get_user_profile_directory(t Token, dir *uint16, dirLen *u32) (err error) = userenv.get_user_profile_directoryW

/// An access token contains the security information for a logon session.
/// The system creates an access token when a user logs on, and every
/// process executed on behalf of the user has a copy of the token.
/// The token identifies the user, the user's groups, and the user's
/// privileges. The system uses the token to control access to securable
/// objects and to control the ability of the user to perform various
/// system-related operations on the local computer.
#[derive(Debug)]
pub struct Token {
    pub h: winapi_::HANDLE,
}

impl Drop for Token {
    fn drop(&mut self) {
        _ = Token::close(self);
    }
}

/// open_current_process_token opens the access token
/// associated with current process.
pub fn open_current_process_token() -> std::io::Result<Token> {
    unsafe {
        let p = winapi_::GetCurrentProcess();
        let mut token: Token = Token {
            h: std::ptr::null_mut(),
        };
        let result = winapi_::OpenProcessToken(p, winapi_::TOKEN_QUERY, &mut token.h);
        get_error(result)?;
        Ok(token)
    }
}

impl Token {
    /// close releases access to access token.
    pub fn close(&mut self) -> std::io::Result<()> {
        unsafe { get_error(winapi_::CloseHandle(self.h)) }
    }

    /// get_info retrieves a specified type of information about an access token.
    fn get_info(&self, class: u32, init_size: usize) -> std::io::Result<Vec<u8>> {
        let mut n = init_size as u32;
        let mut b = vec![0_u8; n as usize];
        loop {
            let e = unsafe {
                winapi_::GetTokenInformation(
                    self.h,
                    class,
                    b.as_mut_ptr() as winapi_::LPVOID,
                    n,
                    &mut n,
                )
            };
            if e == 0 {
                let last_err = std::io::Error::last_os_error();
                if last_err.raw_os_error().unwrap() == winapi_::ERROR_INSUFFICIENT_BUFFER as i32 {
                    b.resize(n as usize, 0);
                    continue;
                }
                return Err(last_err);
            }
            return Ok(b);
        }
    }

    /// get_token_user retrieves access token t user account information.
    pub fn get_token_user(&self) -> std::io::Result<Tokenuser> {
        Ok(Tokenuser {
            raw_data: self.get_info(winapi_::TokenUser, 50)?,
        })
    }

    /// get_token_primary_group retrieves access token t primary group information.
    /// A pointer to a SID structure representing a group that will become
    /// the primary group of any objects created by a process using this access token.
    pub fn get_token_primary_group(&self) -> std::io::Result<Tokenprimarygroup> {
        Ok(Tokenprimarygroup {
            raw_data: self.get_info(winapi_::TokenPrimaryGroup, 50)?,
        })
    }

    /// get_user_profile_directory retrieves path to the
    /// root directory of the access token t user's profile.
    pub fn get_user_profile_directory(&self) -> std::io::Result<String> {
        let mut n = 100_u32;
        let mut b = vec![0_u16; n as usize];
        loop {
            let e = unsafe { winapi_::GetUserProfileDirectoryW(self.h, b.as_mut_ptr(), &mut n) };
            if e == 0 {
                let last_err = std::io::Error::last_os_error();
                if last_err.raw_os_error().unwrap() == winapi_::ERROR_INSUFFICIENT_BUFFER as i32 {
                    b.resize(n as usize, 0);
                    continue;
                }
                return Err(last_err);
            }
            return Ok(super::utf16_to_string(&b));
        }
    }
}

/// Check the numeric result of a WinAPI function.
/// In case of an error (zero value), return the last OS error,
/// otherwise return Ok.
pub fn get_error(res: winapi_::BOOL) -> std::io::Result<()> {
    if res == 0 {
        Err(std::io::Error::last_os_error())
    } else {
        Ok(())
    }
}

#[allow(clippy::missing_safety_doc)]
pub unsafe fn close_handle(h: winapi_::HANDLE) -> std::io::Result<()> {
    unsafe { get_error(winapi_::CloseHandle(h)) }
}