OSDN Git Service

* winsup.h (NT_MAX_PATH): Revert ill-advised change to 32767.
[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 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 <pwd.h>
14 #include <unistd.h>
15 #include <winnls.h>
16 #include <wininet.h>
17 #include <utmp.h>
18 #include <limits.h>
19 #include <stdlib.h>
20 #include <lm.h>
21 #include <sys/cygwin.h>
22 #include "cygerrno.h"
23 #include "pinfo.h"
24 #include "security.h"
25 #include "path.h"
26 #include "fhandler.h"
27 #include "dtable.h"
28 #include "cygheap.h"
29 #include "registry.h"
30 #include "child_info.h"
31 #include "environ.h"
32 #include "pwdgrp.h"
33 #include "tls_pbuf.h"
34 #include "ntdll.h"
35
36 /* Initialize the part of cygheap_user that does not depend on files.
37    The information is used in shared.cc for the user shared.
38    Final initialization occurs in uinfo_init */
39 void
40 cygheap_user::init ()
41 {
42   char user_name[UNLEN + 1];
43   DWORD user_name_len = UNLEN + 1;
44
45   set_name (GetUserName (user_name, &user_name_len) ? user_name : "unknown");
46
47   DWORD siz;
48   PSECURITY_DESCRIPTOR psd;
49
50   if (!GetTokenInformation (hProcToken, TokenPrimaryGroup,
51                             &groups.pgsid, sizeof (cygsid), &siz))
52     system_printf ("GetTokenInformation (TokenPrimaryGroup), %E");
53
54   /* Get the SID from current process and store it in effec_cygsid */
55   if (!GetTokenInformation (hProcToken, TokenUser, &effec_cygsid,
56                             sizeof (cygsid), &siz))
57     {
58       system_printf ("GetTokenInformation (TokenUser), %E");
59       return;
60     }
61
62   /* Set token owner to the same value as token user */
63   if (!SetTokenInformation (hProcToken, TokenOwner, &effec_cygsid,
64                             sizeof (cygsid)))
65     debug_printf ("SetTokenInformation(TokenOwner), %E");
66
67   /* Standard way to build a security descriptor with the usual DACL */
68   PSECURITY_ATTRIBUTES sa_buf = (PSECURITY_ATTRIBUTES) alloca (1024);
69   psd = (PSECURITY_DESCRIPTOR)
70                 (sec_user_nih (sa_buf, sid()))->lpSecurityDescriptor;
71
72   BOOL acl_exists, dummy;
73   TOKEN_DEFAULT_DACL dacl;
74   if (GetSecurityDescriptorDacl (psd, &acl_exists, &dacl.DefaultDacl, &dummy)
75       && acl_exists && dacl.DefaultDacl)
76     {
77       NTSTATUS status;
78
79       /* Set the default DACL and the process DACL */
80       if (!SetTokenInformation (hProcToken, TokenDefaultDacl, &dacl,
81                                 sizeof (dacl)))
82         system_printf ("SetTokenInformation (TokenDefaultDacl), %E");
83       if ((status = NtSetSecurityObject (hMainProc, DACL_SECURITY_INFORMATION,
84                                          psd)))
85         system_printf ("NtSetSecurityObject, %lx", status);
86     }
87   else
88     system_printf("Cannot get dacl, %E");
89 }
90
91 void
92 internal_getlogin (cygheap_user &user)
93 {
94   struct passwd *pw = NULL;
95
96   cygpsid psid = user.sid ();
97   pw = internal_getpwsid (psid);
98
99   if (!pw && !(pw = internal_getpwnam (user.name ()))
100       && !(pw = internal_getpwuid (DEFAULT_UID)))
101     debug_printf ("user not found in augmented /etc/passwd");
102   else
103     {
104       cygsid gsid;
105
106       myself->uid = pw->pw_uid;
107       myself->gid = pw->pw_gid;
108       user.set_name (pw->pw_name);
109       if (gsid.getfromgr (internal_getgrgid (pw->pw_gid)))
110         {
111           if (gsid != user.groups.pgsid)
112             {
113               /* Set primary group to the group in /etc/passwd. */
114               if (!SetTokenInformation (hProcToken, TokenPrimaryGroup,
115                                         &gsid, sizeof gsid))
116                 debug_printf ("SetTokenInformation(TokenPrimaryGroup), %E");
117               else
118                 user.groups.pgsid = gsid;
119               clear_procimptoken ();
120             }
121         }
122       else
123         debug_printf ("gsid not found in augmented /etc/group");
124     }
125   cygheap->user.ontherange (CH_HOME, pw);
126 }
127
128 void
129 uinfo_init ()
130 {
131   if (child_proc_info && !cygheap->user.has_impersonation_tokens ())
132     return;
133
134   if (!child_proc_info)
135     internal_getlogin (cygheap->user); /* Set the cygheap->user. */
136   /* Conditions must match those in spawn to allow starting child
137      processes with ruid != euid and rgid != egid. */
138   else if (cygheap->user.issetuid ()
139            && cygheap->user.saved_uid == cygheap->user.real_uid
140            && cygheap->user.saved_gid == cygheap->user.real_gid
141            && !cygheap->user.groups.issetgroups ())
142     {
143       cygheap->user.reimpersonate ();
144       return;
145     }
146   else
147     cygheap->user.close_impersonation_tokens ();
148
149   cygheap->user.saved_uid = cygheap->user.real_uid = myself->uid;
150   cygheap->user.saved_gid = cygheap->user.real_gid = myself->gid;
151   cygheap->user.external_token = NO_IMPERSONATION;
152   cygheap->user.internal_token = NO_IMPERSONATION;
153   cygheap->user.curr_primary_token = NO_IMPERSONATION;
154   cygheap->user.curr_imp_token = NO_IMPERSONATION;
155   cygheap->user.set_saved_sid ();       /* Update the original sid */
156   cygheap->user.reimpersonate ();
157 }
158
159 extern "C" int
160 getlogin_r (char *name, size_t namesize)
161 {
162   char *login = getlogin ();
163   size_t len = strlen (login) + 1;
164   if (len > namesize)
165     return ERANGE;
166   myfault efault;
167   if (efault.faulted ())
168     return EFAULT;
169   strncpy (name, login, len);
170   return 0;
171 }
172
173 extern "C" char *
174 getlogin (void)
175 {
176   return strcpy (_my_tls.locals.username, cygheap->user.name ());
177 }
178
179 extern "C" __uid32_t
180 getuid32 (void)
181 {
182   return cygheap->user.real_uid;
183 }
184
185 extern "C" __uid16_t
186 getuid (void)
187 {
188   return cygheap->user.real_uid;
189 }
190
191 extern "C" __gid32_t
192 getgid32 (void)
193 {
194   return cygheap->user.real_gid;
195 }
196
197 extern "C" __gid16_t
198 getgid (void)
199 {
200   return cygheap->user.real_gid;
201 }
202
203 extern "C" __uid32_t
204 geteuid32 (void)
205 {
206   return myself->uid;
207 }
208
209 extern "C" __uid16_t
210 geteuid (void)
211 {
212   return myself->uid;
213 }
214
215 extern "C" __gid32_t
216 getegid32 (void)
217 {
218   return myself->gid;
219 }
220
221 extern "C" __gid16_t
222 getegid (void)
223 {
224   return myself->gid;
225 }
226
227 /* Not quite right - cuserid can change, getlogin can't */
228 extern "C" char *
229 cuserid (char *src)
230 {
231   if (!src)
232     return getlogin ();
233
234   strcpy (src, getlogin ());
235   return src;
236 }
237
238 const char *
239 cygheap_user::ontherange (homebodies what, struct passwd *pw)
240 {
241   LPUSER_INFO_3 ui = NULL;
242   WCHAR wuser[UNLEN + 1];
243   NET_API_STATUS ret;
244   char homedrive_env_buf[3];
245   char *newhomedrive = NULL;
246   char *newhomepath = NULL;
247   tmp_pathbuf tp;
248
249   debug_printf ("what %d, pw %p", what, pw);
250   if (what == CH_HOME)
251     {
252       char *p;
253       if (homedrive)
254         newhomedrive = homedrive;
255       else if ((p = getenv ("HOMEDRIVE")))
256         newhomedrive = p;
257
258       if (homepath)
259         newhomepath = homepath;
260       else if ((p = getenv ("HOMEPATH")))
261         newhomepath = p;
262
263       if ((p = getenv ("HOME")))
264         debug_printf ("HOME is already in the environment %s", p);
265       else
266         {
267           if (pw && pw->pw_dir && *pw->pw_dir)
268             {
269               debug_printf ("Set HOME (from /etc/passwd) to %s", pw->pw_dir);
270               setenv ("HOME", pw->pw_dir, 1);
271             }
272           else if (!newhomedrive || !newhomepath)
273             setenv ("HOME", "/", 1);
274           else
275             {
276               char *home = tp.c_get ();
277               char *buf = tp.c_get ();
278               strcpy (buf, newhomedrive);
279               strcat (buf, newhomepath);
280               cygwin_conv_path (CCP_WIN_A_TO_POSIX | CCP_ABSOLUTE, buf, home,
281                                 NT_MAX_PATH);
282               debug_printf ("Set HOME (from HOMEDRIVE/HOMEPATH) to %s", home);
283               setenv ("HOME", home, 1);
284             }
285         }
286     }
287
288   if (what != CH_HOME && homepath == NULL && newhomepath == NULL)
289     {
290       char *homepath_env_buf = tp.c_get ();
291       if (!pw)
292         pw = internal_getpwnam (name ());
293       if (pw && pw->pw_dir && *pw->pw_dir)
294         cygwin_conv_path (CCP_POSIX_TO_WIN_A, pw->pw_dir, homepath_env_buf,
295                           NT_MAX_PATH);
296       else
297         {
298           homepath_env_buf[0] = homepath_env_buf[1] = '\0';
299           if (logsrv ())
300             {
301               WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
302               sys_mbstowcs (wlogsrv, sizeof (wlogsrv) / sizeof (*wlogsrv),
303                             logsrv ());
304              sys_mbstowcs (wuser, sizeof (wuser) / sizeof (*wuser), winname ());
305               if (!(ret = NetUserGetInfo (wlogsrv, wuser, 3, (LPBYTE *) &ui)))
306                 {
307                   sys_wcstombs (homepath_env_buf, NT_MAX_PATH,
308                                 ui->usri3_home_dir);
309                   if (!homepath_env_buf[0])
310                     {
311                       sys_wcstombs (homepath_env_buf, NT_MAX_PATH,
312                                     ui->usri3_home_dir_drive);
313                       if (homepath_env_buf[0])
314                         strcat (homepath_env_buf, "\\");
315                       else
316                         cygwin_conv_path (CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
317                                           "/", homepath_env_buf, NT_MAX_PATH);
318                     }
319                 }
320             }
321           if (ui)
322             NetApiBufferFree (ui);
323         }
324
325       if (homepath_env_buf[1] != ':')
326         {
327           newhomedrive = almost_null;
328           newhomepath = homepath_env_buf;
329         }
330       else
331         {
332           homedrive_env_buf[0] = homepath_env_buf[0];
333           homedrive_env_buf[1] = homepath_env_buf[1];
334           homedrive_env_buf[2] = '\0';
335           newhomedrive = homedrive_env_buf;
336           newhomepath = homepath_env_buf + 2;
337         }
338     }
339
340   if (newhomedrive && newhomedrive != homedrive)
341     cfree_and_set (homedrive, (newhomedrive == almost_null)
342                               ? almost_null : cstrdup (newhomedrive));
343
344   if (newhomepath && newhomepath != homepath)
345     cfree_and_set (homepath, cstrdup (newhomepath));
346
347   switch (what)
348     {
349     case CH_HOMEDRIVE:
350       return homedrive;
351     case CH_HOMEPATH:
352       return homepath;
353     default:
354       return homepath;
355     }
356 }
357
358 const char *
359 cygheap_user::test_uid (char *&what, const char *name, size_t namelen)
360 {
361   if (!what && !issetuid ())
362     what = getwinenveq (name, namelen, HEAP_STR);
363   return what;
364 }
365
366 const char *
367 cygheap_user::env_logsrv (const char *name, size_t namelen)
368 {
369   if (test_uid (plogsrv, name, namelen))
370     return plogsrv;
371
372   const char *mydomain = domain ();
373   const char *myname = winname ();
374   if (!mydomain || ascii_strcasematch (myname, "SYSTEM"))
375     return almost_null;
376
377   char logsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
378   cfree_and_set (plogsrv, almost_null);
379   if (get_logon_server (mydomain, logsrv, NULL, false))
380     plogsrv = cstrdup (logsrv);
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 char *posix_fname)
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   pc.check (posix_fname);
532   etc_ix = etc::init (etc_ix, pc.get_nt_native_path ());
533
534   paranoid_printf ("%s", posix_fname);
535
536   if (pc.error || !pc.exists () || pc.isdir ())
537     {
538       paranoid_printf ("strange path_conv problem");
539       goto out;
540     }
541   status = NtOpenFile (&fh, FILE_READ_DATA,
542                        pc.get_object_attr (attr, sec_none_nih), &io,
543                        FILE_SHARE_VALID_FLAGS, 0);
544   if (!NT_SUCCESS (status))
545     {
546       paranoid_printf ("NtOpenFile(%S) failed, status %p",
547                         pc.get_nt_native_path (), status);
548       goto out;
549     }
550   status = NtQueryInformationFile (fh, &io, &fsi, sizeof fsi,
551                                    FileStandardInformation);
552   if (!NT_SUCCESS (status))
553     {
554       paranoid_printf ("NtQueryInformationFile(%S) failed, status %p",
555                        pc.get_nt_native_path (), status);
556       goto out;
557     }
558   /* FIXME: Should we test for HighPart set?  If so, the
559      passwd or group file is way beyond what we can handle. */
560   /* FIXME 2: It's still ugly that we keep the file in memory.
561      Big organizations have naturally large passwd files. */
562   buf = (char *) malloc (fsi.EndOfFile.LowPart + 1);
563   if (!buf)
564     {
565       paranoid_printf ("malloc (%d) failed", fsi.EndOfFile.LowPart);
566       goto out;
567     }
568   status = NtReadFile (fh, NULL, NULL, NULL, &io, buf,
569                        fsi.EndOfFile.LowPart, &off, NULL);
570   if (!NT_SUCCESS (status))
571     {
572       paranoid_printf ("NtReadFile(%S) failed, status %p",
573                        pc.get_nt_native_path (), status);
574       free (buf);
575       goto out;
576     }
577   buf[fsi.EndOfFile.LowPart] = '\0';
578   char *eptr = buf;
579   while ((eptr = add_line (eptr)))
580     continue;
581   debug_printf ("%s curr_lines %d", posix_fname, curr_lines);
582   res = succeeded;
583
584 out:
585   if (fh)
586     NtClose (fh);
587   debug_printf ("%s load %s", posix_fname, res);
588   initialized = true;
589 }