OSDN Git Service

Change length for domain buffers from INTERNET_MAX_HOST_NAME_LENGTH to
[pf3gnuchains/pf3gnuchains4x.git] / winsup / cygwin / uinfo.cc
1 /* uinfo.cc: user info (uid, gid, etc...)
2
3    Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4    2006, 2007, 2008 Red Hat, Inc.
5
6 This file is part of Cygwin.
7
8 This software is a copyrighted work licensed under the terms of the
9 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
10 details. */
11
12 #include "winsup.h"
13 #include <unistd.h>
14 #include <wininet.h>
15 #include <stdlib.h>
16 #include <lm.h>
17 #include <iptypes.h>
18 #include <sys/cygwin.h>
19 #include "cygerrno.h"
20 #include "pinfo.h"
21 #include "path.h"
22 #include "fhandler.h"
23 #include "dtable.h"
24 #include "cygheap.h"
25 #include "registry.h"
26 #include "child_info.h"
27 #include "environ.h"
28 #include "pwdgrp.h"
29 #include "tls_pbuf.h"
30 #include "ntdll.h"
31
32 /* Initialize the part of cygheap_user that does not depend on files.
33    The information is used in shared.cc for the user shared.
34    Final initialization occurs in uinfo_init */
35 void
36 cygheap_user::init ()
37 {
38   char user_name[UNLEN + 1];
39   DWORD user_name_len = UNLEN + 1;
40
41   set_name (GetUserName (user_name, &user_name_len) ? user_name : "unknown");
42
43   DWORD siz;
44   PSECURITY_DESCRIPTOR psd;
45
46   if (!GetTokenInformation (hProcToken, TokenPrimaryGroup,
47                             &groups.pgsid, sizeof (cygsid), &siz))
48     system_printf ("GetTokenInformation (TokenPrimaryGroup), %E");
49
50   /* Get the SID from current process and store it in effec_cygsid */
51   if (!GetTokenInformation (hProcToken, TokenUser, &effec_cygsid,
52                             sizeof (cygsid), &siz))
53     {
54       system_printf ("GetTokenInformation (TokenUser), %E");
55       return;
56     }
57
58   /* Set token owner to the same value as token user */
59   if (!SetTokenInformation (hProcToken, TokenOwner, &effec_cygsid,
60                             sizeof (cygsid)))
61     debug_printf ("SetTokenInformation(TokenOwner), %E");
62
63   /* Standard way to build a security descriptor with the usual DACL */
64   PSECURITY_ATTRIBUTES sa_buf = (PSECURITY_ATTRIBUTES) alloca (1024);
65   psd = (PSECURITY_DESCRIPTOR)
66                 (sec_user_nih (sa_buf, sid()))->lpSecurityDescriptor;
67
68   BOOL acl_exists, dummy;
69   TOKEN_DEFAULT_DACL dacl;
70   if (GetSecurityDescriptorDacl (psd, &acl_exists, &dacl.DefaultDacl, &dummy)
71       && acl_exists && dacl.DefaultDacl)
72     {
73       NTSTATUS status;
74
75       /* Set the default DACL and the process DACL */
76       if (!SetTokenInformation (hProcToken, TokenDefaultDacl, &dacl,
77                                 sizeof (dacl)))
78         system_printf ("SetTokenInformation (TokenDefaultDacl), %E");
79       if ((status = NtSetSecurityObject (hMainProc, DACL_SECURITY_INFORMATION,
80                                          psd)))
81         system_printf ("NtSetSecurityObject, %lx", status);
82     }
83   else
84     system_printf("Cannot get dacl, %E");
85 }
86
87 void
88 internal_getlogin (cygheap_user &user)
89 {
90   struct passwd *pw = NULL;
91
92   cygpsid psid = user.sid ();
93   pw = internal_getpwsid (psid);
94
95   if (!pw && !(pw = internal_getpwnam (user.name ()))
96       && !(pw = internal_getpwuid (DEFAULT_UID)))
97     debug_printf ("user not found in augmented /etc/passwd");
98   else
99     {
100       cygsid gsid;
101
102       myself->uid = pw->pw_uid;
103       myself->gid = pw->pw_gid;
104       user.set_name (pw->pw_name);
105       if (gsid.getfromgr (internal_getgrgid (pw->pw_gid)))
106         {
107           if (gsid != user.groups.pgsid)
108             {
109               /* Set primary group to the group in /etc/passwd. */
110               if (!SetTokenInformation (hProcToken, TokenPrimaryGroup,
111                                         &gsid, sizeof gsid))
112                 debug_printf ("SetTokenInformation(TokenPrimaryGroup), %E");
113               else
114                 user.groups.pgsid = gsid;
115               clear_procimptoken ();
116             }
117         }
118       else
119         debug_printf ("gsid not found in augmented /etc/group");
120     }
121   cygheap->user.ontherange (CH_HOME, pw);
122 }
123
124 void
125 uinfo_init ()
126 {
127   if (child_proc_info && !cygheap->user.has_impersonation_tokens ())
128     return;
129
130   if (!child_proc_info)
131     internal_getlogin (cygheap->user); /* Set the cygheap->user. */
132   /* Conditions must match those in spawn to allow starting child
133      processes with ruid != euid and rgid != egid. */
134   else if (cygheap->user.issetuid ()
135            && cygheap->user.saved_uid == cygheap->user.real_uid
136            && cygheap->user.saved_gid == cygheap->user.real_gid
137            && !cygheap->user.groups.issetgroups ())
138     {
139       cygheap->user.reimpersonate ();
140       return;
141     }
142   else
143     cygheap->user.close_impersonation_tokens ();
144
145   cygheap->user.saved_uid = cygheap->user.real_uid = myself->uid;
146   cygheap->user.saved_gid = cygheap->user.real_gid = myself->gid;
147   cygheap->user.external_token = NO_IMPERSONATION;
148   cygheap->user.internal_token = NO_IMPERSONATION;
149   cygheap->user.curr_primary_token = NO_IMPERSONATION;
150   cygheap->user.curr_imp_token = NO_IMPERSONATION;
151   cygheap->user.set_saved_sid ();       /* Update the original sid */
152   cygheap->user.reimpersonate ();
153 }
154
155 extern "C" int
156 getlogin_r (char *name, size_t namesize)
157 {
158   char *login = getlogin ();
159   size_t len = strlen (login) + 1;
160   if (len > namesize)
161     return ERANGE;
162   myfault efault;
163   if (efault.faulted ())
164     return EFAULT;
165   strncpy (name, login, len);
166   return 0;
167 }
168
169 extern "C" char *
170 getlogin (void)
171 {
172   return strcpy (_my_tls.locals.username, cygheap->user.name ());
173 }
174
175 extern "C" __uid32_t
176 getuid32 (void)
177 {
178   return cygheap->user.real_uid;
179 }
180
181 extern "C" __uid16_t
182 getuid (void)
183 {
184   return cygheap->user.real_uid;
185 }
186
187 extern "C" __gid32_t
188 getgid32 (void)
189 {
190   return cygheap->user.real_gid;
191 }
192
193 extern "C" __gid16_t
194 getgid (void)
195 {
196   return cygheap->user.real_gid;
197 }
198
199 extern "C" __uid32_t
200 geteuid32 (void)
201 {
202   return myself->uid;
203 }
204
205 extern "C" __uid16_t
206 geteuid (void)
207 {
208   return myself->uid;
209 }
210
211 extern "C" __gid32_t
212 getegid32 (void)
213 {
214   return myself->gid;
215 }
216
217 extern "C" __gid16_t
218 getegid (void)
219 {
220   return myself->gid;
221 }
222
223 /* Not quite right - cuserid can change, getlogin can't */
224 extern "C" char *
225 cuserid (char *src)
226 {
227   if (!src)
228     return getlogin ();
229
230   strcpy (src, getlogin ());
231   return src;
232 }
233
234 const char *
235 cygheap_user::ontherange (homebodies what, struct passwd *pw)
236 {
237   LPUSER_INFO_3 ui = NULL;
238   WCHAR wuser[UNLEN + 1];
239   NET_API_STATUS ret;
240   char homedrive_env_buf[3];
241   char *newhomedrive = NULL;
242   char *newhomepath = NULL;
243   tmp_pathbuf tp;
244
245   debug_printf ("what %d, pw %p", what, pw);
246   if (what == CH_HOME)
247     {
248       char *p;
249       if (homedrive)
250         newhomedrive = homedrive;
251       else if ((p = getenv ("HOMEDRIVE")))
252         newhomedrive = p;
253
254       if (homepath)
255         newhomepath = homepath;
256       else if ((p = getenv ("HOMEPATH")))
257         newhomepath = p;
258
259       if ((p = getenv ("HOME")))
260         debug_printf ("HOME is already in the environment %s", p);
261       else
262         {
263           if (pw && pw->pw_dir && *pw->pw_dir)
264             {
265               debug_printf ("Set HOME (from /etc/passwd) to %s", pw->pw_dir);
266               setenv ("HOME", pw->pw_dir, 1);
267             }
268           else if (!newhomedrive || !newhomepath)
269             setenv ("HOME", "/", 1);
270           else
271             {
272               char *home = tp.c_get ();
273               char *buf = tp.c_get ();
274               strcpy (buf, newhomedrive);
275               strcat (buf, newhomepath);
276               cygwin_conv_path (CCP_WIN_A_TO_POSIX | CCP_ABSOLUTE, buf, home,
277                                 NT_MAX_PATH);
278               debug_printf ("Set HOME (from HOMEDRIVE/HOMEPATH) to %s", home);
279               setenv ("HOME", home, 1);
280             }
281         }
282     }
283
284   if (what != CH_HOME && homepath == NULL && newhomepath == NULL)
285     {
286       char *homepath_env_buf = tp.c_get ();
287       if (!pw)
288         pw = internal_getpwnam (name ());
289       if (pw && pw->pw_dir && *pw->pw_dir)
290         cygwin_conv_path (CCP_POSIX_TO_WIN_A, pw->pw_dir, homepath_env_buf,
291                           NT_MAX_PATH);
292       else
293         {
294           homepath_env_buf[0] = homepath_env_buf[1] = '\0';
295           if (logsrv ())
296             {
297               WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
298               sys_mbstowcs (wlogsrv, sizeof (wlogsrv) / sizeof (*wlogsrv),
299                             logsrv ());
300              sys_mbstowcs (wuser, sizeof (wuser) / sizeof (*wuser), winname ());
301               if (!(ret = NetUserGetInfo (wlogsrv, wuser, 3, (LPBYTE *) &ui)))
302                 {
303                   sys_wcstombs (homepath_env_buf, NT_MAX_PATH,
304                                 ui->usri3_home_dir);
305                   if (!homepath_env_buf[0])
306                     {
307                       sys_wcstombs (homepath_env_buf, NT_MAX_PATH,
308                                     ui->usri3_home_dir_drive);
309                       if (homepath_env_buf[0])
310                         strcat (homepath_env_buf, "\\");
311                       else
312                         cygwin_conv_path (CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
313                                           "/", homepath_env_buf, NT_MAX_PATH);
314                     }
315                 }
316             }
317           if (ui)
318             NetApiBufferFree (ui);
319         }
320
321       if (homepath_env_buf[1] != ':')
322         {
323           newhomedrive = almost_null;
324           newhomepath = homepath_env_buf;
325         }
326       else
327         {
328           homedrive_env_buf[0] = homepath_env_buf[0];
329           homedrive_env_buf[1] = homepath_env_buf[1];
330           homedrive_env_buf[2] = '\0';
331           newhomedrive = homedrive_env_buf;
332           newhomepath = homepath_env_buf + 2;
333         }
334     }
335
336   if (newhomedrive && newhomedrive != homedrive)
337     cfree_and_set (homedrive, (newhomedrive == almost_null)
338                               ? almost_null : cstrdup (newhomedrive));
339
340   if (newhomepath && newhomepath != homepath)
341     cfree_and_set (homepath, cstrdup (newhomepath));
342
343   switch (what)
344     {
345     case CH_HOMEDRIVE:
346       return homedrive;
347     case CH_HOMEPATH:
348       return homepath;
349     default:
350       return homepath;
351     }
352 }
353
354 const char *
355 cygheap_user::test_uid (char *&what, const char *name, size_t namelen)
356 {
357   if (!what && !issetuid ())
358     what = getwinenveq (name, namelen, HEAP_STR);
359   return what;
360 }
361
362 const char *
363 cygheap_user::env_logsrv (const char *name, size_t namelen)
364 {
365   if (test_uid (plogsrv, name, namelen))
366     return plogsrv;
367
368   const char *mydomain = domain ();
369   const char *myname = winname ();
370   if (!mydomain || ascii_strcasematch (myname, "SYSTEM"))
371     return almost_null;
372
373   WCHAR wdomain[MAX_DOMAIN_NAME_LEN + 1];
374   WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
375   sys_mbstowcs (wdomain, MAX_DOMAIN_NAME_LEN + 1, mydomain);
376   cfree_and_set (plogsrv, almost_null);
377   if (get_logon_server (wdomain, wlogsrv, false))
378     sys_wcstombs_alloc (&plogsrv, HEAP_STR, wlogsrv);
379   return plogsrv;
380 }
381
382 const char *
383 cygheap_user::env_domain (const char *name, size_t namelen)
384 {
385   if (pwinname && test_uid (pdomain, name, namelen))
386     return pdomain;
387
388   char username[UNLEN + 1];
389   DWORD ulen = sizeof (username);
390   char userdomain[DNLEN + 1];
391   DWORD dlen = sizeof (userdomain);
392   SID_NAME_USE use;
393
394   cfree_and_set (pwinname, almost_null);
395   cfree_and_set (pdomain, almost_null);
396   if (!LookupAccountSid (NULL, sid (), username, &ulen,
397                          userdomain, &dlen, &use))
398     __seterrno ();
399   else
400     {
401       pwinname = cstrdup (username);
402       pdomain = cstrdup (userdomain);
403     }
404   return pdomain;
405 }
406
407 const char *
408 cygheap_user::env_userprofile (const char *name, size_t namelen)
409 {
410   if (test_uid (puserprof, name, namelen))
411     return puserprof;
412
413   WCHAR userprofile_env_buf[NT_MAX_PATH];
414   WCHAR win_id[UNLEN + 1]; /* Large enough for SID */
415
416   cfree_and_set (puserprof, almost_null);
417   if (get_registry_hive_path (get_windows_id (win_id), userprofile_env_buf))
418     sys_wcstombs_alloc (&puserprof, HEAP_STR, userprofile_env_buf);
419
420   return puserprof;
421 }
422
423 const char *
424 cygheap_user::env_homepath (const char *name, size_t namelen)
425 {
426   return ontherange (CH_HOMEPATH);
427 }
428
429 const char *
430 cygheap_user::env_homedrive (const char *name, size_t namelen)
431 {
432   return ontherange (CH_HOMEDRIVE);
433 }
434
435 const char *
436 cygheap_user::env_name (const char *name, size_t namelen)
437 {
438   if (!test_uid (pwinname, name, namelen))
439     domain ();
440   return pwinname;
441 }
442
443 const char *
444 cygheap_user::env_systemroot (const char *name, size_t namelen)
445 {
446   if (!psystemroot)
447     {
448       int size = GetWindowsDirectory (NULL, 0);
449       if (size > 0)
450         {
451           psystemroot = (char *) cmalloc_abort (HEAP_STR, ++size);
452           size = GetWindowsDirectory (psystemroot, size);
453           if (size <= 0)
454             {
455               cfree (psystemroot);
456               psystemroot = NULL;
457             }
458         }
459       if (size <= 0)
460         debug_printf ("GetWindowsDirectory(), %E");
461     }
462   return psystemroot;
463 }
464
465 char *
466 pwdgrp::next_str (char c)
467 {
468   char *res = lptr;
469   lptr = strechr (lptr, c);
470   if (*lptr)
471     *lptr++ = '\0';
472   return res;
473 }
474
475 bool
476 pwdgrp::next_num (unsigned long& n)
477 {
478   char *p = next_str (':');
479   char *cp;
480   n = strtoul (p, &cp, 10);
481   return p != cp && !*cp;
482 }
483
484 char *
485 pwdgrp::add_line (char *eptr)
486 {
487   if (eptr)
488     {
489       lptr = eptr;
490       eptr = strchr (lptr, '\n');
491       if (eptr)
492         {
493           if (eptr > lptr && eptr[-1] == '\r')
494             eptr[-1] = '\0';
495           else
496             *eptr = '\0';
497           eptr++;
498         }
499       if (curr_lines >= max_lines)
500         {
501           max_lines += 10;
502           *pwdgrp_buf = realloc (*pwdgrp_buf, max_lines * pwdgrp_buf_elem_size);
503         }
504       if ((this->*parse) ())
505         curr_lines++;
506     }
507   return eptr;
508 }
509
510 void
511 pwdgrp::load (const char *posix_fname)
512 {
513   static const char failed[] = "failed";
514   static const char succeeded[] = "succeeded";
515   const char *res = failed;
516   HANDLE fh = NULL;
517   LARGE_INTEGER off = { QuadPart:0LL };
518
519   NTSTATUS status;
520   OBJECT_ATTRIBUTES attr;
521   IO_STATUS_BLOCK io;
522   FILE_STANDARD_INFORMATION fsi;
523
524   if (buf)
525     free (buf);
526   buf = NULL;
527   curr_lines = 0;
528
529   pc.check (posix_fname);
530   etc_ix = etc::init (etc_ix, pc.get_nt_native_path ());
531
532   paranoid_printf ("%s", posix_fname);
533
534   if (pc.error || !pc.exists () || pc.isdir ())
535     {
536       paranoid_printf ("strange path_conv problem");
537       goto out;
538     }
539   status = NtOpenFile (&fh, FILE_READ_DATA,
540                        pc.get_object_attr (attr, sec_none_nih), &io,
541                        FILE_SHARE_VALID_FLAGS, 0);
542   if (!NT_SUCCESS (status))
543     {
544       paranoid_printf ("NtOpenFile(%S) failed, status %p",
545                         pc.get_nt_native_path (), status);
546       goto out;
547     }
548   status = NtQueryInformationFile (fh, &io, &fsi, sizeof fsi,
549                                    FileStandardInformation);
550   if (!NT_SUCCESS (status))
551     {
552       paranoid_printf ("NtQueryInformationFile(%S) failed, status %p",
553                        pc.get_nt_native_path (), status);
554       goto out;
555     }
556   /* FIXME: Should we test for HighPart set?  If so, the
557      passwd or group file is way beyond what we can handle. */
558   /* FIXME 2: It's still ugly that we keep the file in memory.
559      Big organizations have naturally large passwd files. */
560   buf = (char *) malloc (fsi.EndOfFile.LowPart + 1);
561   if (!buf)
562     {
563       paranoid_printf ("malloc (%d) failed", fsi.EndOfFile.LowPart);
564       goto out;
565     }
566   status = NtReadFile (fh, NULL, NULL, NULL, &io, buf,
567                        fsi.EndOfFile.LowPart, &off, NULL);
568   if (!NT_SUCCESS (status))
569     {
570       paranoid_printf ("NtReadFile(%S) failed, status %p",
571                        pc.get_nt_native_path (), status);
572       free (buf);
573       goto out;
574     }
575   buf[fsi.EndOfFile.LowPart] = '\0';
576   char *eptr = buf;
577   while ((eptr = add_line (eptr)))
578     continue;
579   debug_printf ("%s curr_lines %d", posix_fname, curr_lines);
580   res = succeeded;
581
582 out:
583   if (fh)
584     NtClose (fh);
585   debug_printf ("%s load %s", posix_fname, res);
586   initialized = true;
587 }