OSDN Git Service

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