OSDN Git Service

* debug.h (console_printf): Define for non-debugging condition.
[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 Red Hat, Inc.
4
5 This file is part of Cygwin.
6
7 This software is a copyrighted work licensed under the terms of the
8 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
9 details. */
10
11 #include "winsup.h"
12 #include <pwd.h>
13 #include <unistd.h>
14 #include <winnls.h>
15 #include <wininet.h>
16 #include <utmp.h>
17 #include <limits.h>
18 #include <stdlib.h>
19 #include <lm.h>
20 #include <sys/cygwin.h>
21 #include "pinfo.h"
22 #include "security.h"
23 #include "path.h"
24 #include "fhandler.h"
25 #include "dtable.h"
26 #include "cygerrno.h"
27 #include "cygheap.h"
28 #include "registry.h"
29 #include "child_info.h"
30 #include "environ.h"
31 #include "pwdgrp.h"
32
33 /* Initialize the part of cygheap_user that does not depend on files.
34    The information is used in shared.cc for the user shared.
35    Final initialization occurs in uinfo_init */
36 void
37 cygheap_user::init ()
38 {
39   char user_name[UNLEN + 1];
40   DWORD user_name_len = UNLEN + 1;
41
42   set_name (GetUserName (user_name, &user_name_len) ? user_name : "unknown");
43
44   if (!wincap.has_security ())
45     return;
46
47   HANDLE ptok;
48   DWORD siz;
49   PSECURITY_DESCRIPTOR psd;
50
51   if (!OpenProcessToken (hMainProc, TOKEN_ADJUST_DEFAULT | TOKEN_QUERY,
52                          &ptok))
53     {
54       system_printf ("OpenProcessToken(): %E");
55       return;
56     }
57   if (!GetTokenInformation (ptok, TokenPrimaryGroup,
58                             &groups.pgsid, sizeof (cygsid), &siz))
59     system_printf ("GetTokenInformation (TokenPrimaryGroup): %E");
60
61   /* Get the SID from current process and store it in effec_cygsid */
62   if (!GetTokenInformation (ptok, TokenUser, &effec_cygsid, sizeof (cygsid), &siz))
63     {
64       system_printf ("GetTokenInformation (TokenUser): %E");
65       goto out;
66     }
67
68   /* Set token owner to the same value as token user */
69   if (!SetTokenInformation (ptok, TokenOwner, &effec_cygsid, sizeof (cygsid)))
70     debug_printf ("SetTokenInformation(TokenOwner): %E");
71
72   /* Standard way to build a security descriptor with the usual DACL */
73   char sa_buf[1024];
74   psd = (PSECURITY_DESCRIPTOR) (sec_user_nih (sa_buf, sid()))->lpSecurityDescriptor;
75
76   BOOL acl_exists, dummy;
77   TOKEN_DEFAULT_DACL dacl;
78   if (GetSecurityDescriptorDacl (psd, &acl_exists, 
79                                  &dacl.DefaultDacl, &dummy)
80       && acl_exists && dacl.DefaultDacl)
81     {
82       /* Set the default DACL and the process DACL */
83       if (!SetTokenInformation (ptok, TokenDefaultDacl, &dacl, sizeof (dacl)))
84         system_printf ("SetTokenInformation (TokenDefaultDacl): %E");
85       if (!SetKernelObjectSecurity (hMainProc, DACL_SECURITY_INFORMATION, psd))
86         system_printf ("SetKernelObjectSecurity: %E");
87     }
88   else
89     system_printf("Cannot get dacl: %E");
90  out:
91   CloseHandle (ptok);
92 }
93
94 void
95 internal_getlogin (cygheap_user &user)
96 {
97   struct passwd *pw = NULL;
98
99   if (wincap.has_security ())
100     {
101       cygpsid psid = user.sid ();
102       pw = internal_getpwsid (psid);
103     }
104
105   if (!pw && !(pw = internal_getpwnam (user.name ()))
106       && !(pw = internal_getpwuid (DEFAULT_UID)))
107     debug_printf ("user not found in augmented /etc/passwd");
108   else
109     {
110       myself->uid = pw->pw_uid;
111       myself->gid = pw->pw_gid;
112       user.set_name (pw->pw_name);
113       if (wincap.has_security ())
114         {
115           cygsid gsid;
116           if (gsid.getfromgr (internal_getgrgid (pw->pw_gid)))
117             {
118               HANDLE ptok;
119               if (gsid != user.groups.pgsid
120                   && OpenProcessToken (hMainProc, TOKEN_ADJUST_DEFAULT, &ptok))
121                 {
122                   /* Set primary group to the group in /etc/passwd. */
123                   if (!SetTokenInformation (ptok, TokenPrimaryGroup,
124                                             &gsid, sizeof gsid))
125                     debug_printf ("SetTokenInformation(TokenPrimaryGroup): %E");
126                   else
127                     user.groups.pgsid = gsid;
128                   CloseHandle (ptok);
129                 }
130             }
131           else
132             debug_printf ("gsid not found in augmented /etc/group");
133         }
134     }
135   (void) cygheap->user.ontherange (CH_HOME, pw);
136
137   return;
138 }
139
140 void
141 uinfo_init ()
142 {
143   if (child_proc_info && !cygheap->user.has_impersonation_tokens ())
144     return;
145
146   if (!child_proc_info)
147     internal_getlogin (cygheap->user); /* Set the cygheap->user. */
148   /* Conditions must match those in spawn to allow starting child
149      processes with ruid != euid and rgid != egid. */
150   else if (cygheap->user.issetuid ()
151            && cygheap->user.saved_uid == cygheap->user.real_uid
152            && cygheap->user.saved_gid == cygheap->user.real_gid
153            && !cygheap->user.groups.issetgroups ())
154     {
155       cygheap->user.reimpersonate ();
156       return;
157     }
158   else
159     cygheap->user.close_impersonation_tokens ();
160
161   cygheap->user.saved_uid = cygheap->user.real_uid = myself->uid;
162   cygheap->user.saved_gid = cygheap->user.real_gid = myself->gid;
163   cygheap->user.external_token = INVALID_HANDLE_VALUE;
164   cygheap->user.internal_token = INVALID_HANDLE_VALUE;
165   cygheap->user.current_token = INVALID_HANDLE_VALUE;
166   cygheap->user.set_saved_sid ();       /* Update the original sid */
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 homepath_env_buf[CYG_MAX_PATH + 1];
241   char homedrive_env_buf[3];
242   char *newhomedrive = NULL;
243   char *newhomepath = NULL;
244
245
246   debug_printf ("what %d, pw %p", what, pw);
247   if (what == CH_HOME)
248     {
249       char *p;
250       if (homedrive)
251         newhomedrive = homedrive;
252       else if ((p = getenv ("HOMEDRIVE")))
253         newhomedrive = p;
254
255       if (homepath)
256         newhomepath = homepath;
257       else if ((p = getenv ("HOMEPATH")))
258         newhomepath = p;
259
260       if ((p = getenv ("HOME")))
261         debug_printf ("HOME is already in the environment %s", p);
262       else
263         {
264           if (pw && pw->pw_dir && *pw->pw_dir)
265             {
266               debug_printf ("Set HOME (from /etc/passwd) to %s", pw->pw_dir);
267               setenv ("HOME", pw->pw_dir, 1);
268             }
269           else if (!newhomedrive || !newhomepath)
270             setenv ("HOME", "/", 1);
271           else
272             {
273               char home[CYG_MAX_PATH];
274               char buf[CYG_MAX_PATH + 1];
275               strcpy (buf, newhomedrive);
276               strcat (buf, newhomepath);
277               cygwin_conv_to_full_posix_path (buf, home);
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       if (!pw)
287         pw = internal_getpwnam (name ());
288       if (pw && pw->pw_dir && *pw->pw_dir)
289         cygwin_conv_to_full_win32_path (pw->pw_dir, homepath_env_buf);
290       else
291         {
292           homepath_env_buf[0] = homepath_env_buf[1] = '\0';
293           if (logsrv ())
294             {
295               WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
296               sys_mbstowcs (wlogsrv, logsrv (),
297                             sizeof (wlogsrv) / sizeof (*wlogsrv));
298              sys_mbstowcs (wuser, winname (), sizeof (wuser) / sizeof (*wuser));
299               if (!(ret = NetUserGetInfo (wlogsrv, wuser, 3, (LPBYTE *) &ui)))
300                 {
301                   sys_wcstombs (homepath_env_buf, ui->usri3_home_dir, CYG_MAX_PATH);
302                   if (!homepath_env_buf[0])
303                     {
304                       sys_wcstombs (homepath_env_buf, ui->usri3_home_dir_drive,
305                                     CYG_MAX_PATH);
306                       if (homepath_env_buf[0])
307                         strcat (homepath_env_buf, "\\");
308                       else
309                         cygwin_conv_to_full_win32_path ("/", homepath_env_buf);
310                     }
311                 }
312             }
313           if (ui)
314             NetApiBufferFree (ui);
315         }
316
317       if (homepath_env_buf[1] != ':')
318         {
319           newhomedrive = almost_null;
320           newhomepath = homepath_env_buf;
321         }
322       else
323         {
324           homedrive_env_buf[0] = homepath_env_buf[0];
325           homedrive_env_buf[1] = homepath_env_buf[1];
326           homedrive_env_buf[2] = '\0';
327           newhomedrive = homedrive_env_buf;
328           newhomepath = homepath_env_buf + 2;
329         }
330     }
331
332   if (newhomedrive && newhomedrive != homedrive)
333     cfree_and_set (homedrive, (newhomedrive == almost_null)
334                               ? almost_null : cstrdup (newhomedrive));
335
336   if (newhomepath && newhomepath != homepath)
337     cfree_and_set (homepath, cstrdup (newhomepath));
338
339   switch (what)
340     {
341     case CH_HOMEDRIVE:
342       return homedrive;
343     case CH_HOMEPATH:
344       return homepath;
345     default:
346       return homepath;
347     }
348 }
349
350 const char *
351 cygheap_user::test_uid (char *&what, const char *name, size_t namelen)
352 {
353   if (!what && !issetuid ())
354     what = getwinenveq (name, namelen, HEAP_STR);
355   return what;
356 }
357
358 const char *
359 cygheap_user::env_logsrv (const char *name, size_t namelen)
360 {
361   if (test_uid (plogsrv, name, namelen))
362     return plogsrv;
363
364   const char *mydomain = domain ();
365   const char *myname = winname ();
366   if (!mydomain || strcasematch (myname, "SYSTEM"))
367     return almost_null;
368
369   char logsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
370   cfree_and_set (plogsrv, almost_null);
371   if (get_logon_server (mydomain, logsrv, NULL))
372     plogsrv = cstrdup (logsrv);
373   return plogsrv;
374 }
375
376 const char *
377 cygheap_user::env_domain (const char *name, size_t namelen)
378 {
379   if (pwinname && test_uid (pdomain, name, namelen))
380     return pdomain;
381
382   char username[UNLEN + 1];
383   DWORD ulen = sizeof (username);
384   char userdomain[DNLEN + 1];
385   DWORD dlen = sizeof (userdomain);
386   SID_NAME_USE use;
387
388   cfree_and_set (pwinname, almost_null);
389   cfree_and_set (pdomain, almost_null);
390   if (!LookupAccountSid (NULL, sid (), username, &ulen,
391                          userdomain, &dlen, &use))
392     __seterrno ();
393   else
394     {
395       pwinname = cstrdup (username);
396       pdomain = cstrdup (userdomain);
397     }
398   return pdomain;
399 }
400
401 const char *
402 cygheap_user::env_userprofile (const char *name, size_t namelen)
403 {
404   if (test_uid (puserprof, name, namelen))
405     return puserprof;
406
407   char userprofile_env_buf[CYG_MAX_PATH + 1];
408   cfree_and_set (puserprof, almost_null);
409   /* FIXME: Should this just be setting a puserprofile like everything else? */
410   const char *myname = winname ();
411   if (myname && strcasematch (myname, "SYSTEM")
412       && get_registry_hive_path (sid (), userprofile_env_buf))
413     puserprof = cstrdup (userprofile_env_buf);
414
415   return puserprof;
416 }
417
418 const char *
419 cygheap_user::env_homepath (const char *name, size_t namelen)
420 {
421   return ontherange (CH_HOMEPATH);
422 }
423
424 const char *
425 cygheap_user::env_homedrive (const char *name, size_t namelen)
426 {
427   return ontherange (CH_HOMEDRIVE);
428 }
429
430 const char *
431 cygheap_user::env_name (const char *name, size_t namelen)
432 {
433   if (!test_uid (pwinname, name, namelen))
434     (void) domain ();
435   return pwinname;
436 }
437
438 char *
439 pwdgrp::next_str (char c)
440 {
441   char *res = lptr;
442   lptr = strechr (lptr, c);
443   if (*lptr)
444     *lptr++ = '\0';
445   return res;
446 }
447
448 bool
449 pwdgrp::next_num (unsigned long& n)
450 {
451   char *p = next_str (':');
452   char *cp;
453   n = strtoul (p, &cp, 10);
454   return p != cp && !*cp;
455 }
456
457 char *
458 pwdgrp::add_line (char *eptr)
459 {
460   if (eptr)
461     {
462       lptr = eptr;
463       eptr = strchr (lptr, '\n');
464       if (eptr)
465         {
466           if (eptr > lptr && eptr[-1] == '\r')
467             eptr[-1] = '\0';
468           else
469             *eptr = '\0';
470           eptr++;
471         }
472       if (curr_lines >= max_lines)
473         {
474           max_lines += 10;
475           *pwdgrp_buf = realloc (*pwdgrp_buf, max_lines * pwdgrp_buf_elem_size);
476         }
477       if ((this->*parse) ())
478         curr_lines++;
479     }
480   return eptr;
481 }
482
483 void
484 pwdgrp::load (const char *posix_fname)
485 {
486   const char *res;
487   static const char failed[] = "failed";
488   static const char succeeded[] = "succeeded";
489
490   if (buf)
491     free (buf);
492   buf = NULL;
493   curr_lines = 0;
494
495   pc.check (posix_fname);
496   etc_ix = etc::init (etc_ix, pc);
497
498   paranoid_printf ("%s", posix_fname);
499
500   if (pc.error || !pc.exists () || !pc.isdisk () || pc.isdir ())
501     {
502       paranoid_printf ("strange path_conv problem");
503       res = failed;
504     }
505   else
506     {
507       HANDLE fh = CreateFile (pc, GENERIC_READ, wincap.shared (), NULL,
508                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
509       if (fh == INVALID_HANDLE_VALUE)
510         {
511           paranoid_printf ("%s CreateFile failed, %E");
512           res = failed;
513         }
514       else
515         {
516           DWORD size = GetFileSize (fh, NULL), read_bytes;
517           buf = (char *) malloc (size + 1);
518           if (!ReadFile (fh, buf, size, &read_bytes, NULL))
519             {
520               paranoid_printf ("ReadFile failed, %E");
521               CloseHandle (fh);
522               if (buf)
523                 free (buf);
524               buf = NULL;
525               res = failed;
526             }
527           else
528             {
529               CloseHandle (fh);
530               buf[read_bytes] = '\0';
531               char *eptr = buf;
532               while ((eptr = add_line (eptr)))
533                 continue;
534               debug_printf ("%s curr_lines %d", posix_fname, curr_lines);
535               res = succeeded;
536             }
537         }
538     }
539
540   debug_printf ("%s load %s", posix_fname, res);
541   initialized = true;
542   return;
543 }