OSDN Git Service

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