Prepare release and bump version numbers to 2.17.0.2
[TortoiseGit.git] / src / TortoisePlink / Windows / utils / get_username.c
blob7901ac52546ebd4cd85743d02fcb4773559022c4
1 /*
2 * Implementation of get_username() for Windows.
3 */
5 #include "putty.h"
7 #ifndef SECURITY_WIN32
8 #define SECURITY_WIN32
9 #endif
10 #include <security.h>
12 char *get_username(void)
14 DWORD namelen;
15 char *user;
16 bool got_username = false;
17 DECL_WINDOWS_FUNCTION(static, BOOLEAN, GetUserNameExA,
18 (EXTENDED_NAME_FORMAT, LPSTR, PULONG));
21 static bool tried_usernameex = false;
22 if (!tried_usernameex) {
23 /* Not available on Win9x, so load dynamically */
24 HMODULE secur32 = load_system32_dll("secur32.dll");
25 /* If MIT Kerberos is installed, the following call to
26 GET_WINDOWS_FUNCTION makes Windows implicitly load
27 sspicli.dll WITHOUT proper path sanitizing, so better
28 load it properly before */
29 HMODULE sspicli = load_system32_dll("sspicli.dll");
30 (void)sspicli; /* squash compiler warning about unused variable */
31 GET_WINDOWS_FUNCTION(secur32, GetUserNameExA);
32 tried_usernameex = true;
36 if (p_GetUserNameExA) {
38 * If available, use the principal -- this avoids the problem
39 * that the local username is case-insensitive but Kerberos
40 * usernames are case-sensitive.
43 /* Get the length */
44 namelen = 0;
45 (void) p_GetUserNameExA(NameUserPrincipal, NULL, &namelen);
47 user = snewn(namelen, char);
48 got_username = p_GetUserNameExA(NameUserPrincipal, user, &namelen);
49 if (got_username) {
50 char *p = strchr(user, '@');
51 if (p) *p = 0;
52 } else {
53 sfree(user);
57 if (!got_username) {
58 /* Fall back to local user name */
59 namelen = 0;
60 if (!GetUserName(NULL, &namelen)) {
62 * Apparently this doesn't work at least on Windows XP SP2.
63 * Thus assume a maximum of 256. It will fail again if it
64 * doesn't fit.
66 namelen = 256;
69 user = snewn(namelen, char);
70 got_username = GetUserName(user, &namelen);
71 if (!got_username) {
72 sfree(user);
76 return got_username ? user : NULL;