OSDN Git Service

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