OSDN Git Service

Reorganize header file inclusion throughout so that cygerrno.h comes first.
[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 "cygerrno.h"
22 #include "pinfo.h"
23 #include "security.h"
24 #include "path.h"
25 #include "fhandler.h"
26 #include "dtable.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 = NO_IMPERSONATION;
164   cygheap->user.internal_token = NO_IMPERSONATION;
165   cygheap->user.current_token = NO_IMPERSONATION;
166   cygheap->user.set_saved_sid ();       /* Update the original sid */
167 }
168
169 extern "C" int
170 getlogin_r (char *name, size_t namesize)
171 {
172   char *login = getlogin ();
173   size_t len = strlen (login) + 1;
174   if (len > namesize)
175     return ERANGE;
176   int err = __check_null_invalid_struct (name, len);
177   if (err)
178     return err;
179   strncpy (name, login, len);
180   return 0;
181 }
182
183 extern "C" char *
184 getlogin (void)
185 {
186   return strcpy (_my_tls.locals.username, cygheap->user.name ());
187 }
188
189 extern "C" __uid32_t
190 getuid32 (void)
191 {
192   return cygheap->user.real_uid;
193 }
194
195 extern "C" __uid16_t
196 getuid (void)
197 {
198   return cygheap->user.real_uid;
199 }
200
201 extern "C" __gid32_t
202 getgid32 (void)
203 {
204   return cygheap->user.real_gid;
205 }
206
207 extern "C" __gid16_t
208 getgid (void)
209 {
210   return cygheap->user.real_gid;
211 }
212
213 extern "C" __uid32_t
214 geteuid32 (void)
215 {
216   return myself->uid;
217 }
218
219 extern "C" __uid16_t
220 geteuid (void)
221 {
222   return myself->uid;
223 }
224
225 extern "C" __gid32_t
226 getegid32 (void)
227 {
228   return myself->gid;
229 }
230
231 extern "C" __gid16_t
232 getegid (void)
233 {
234   return myself->gid;
235 }
236
237 /* Not quite right - cuserid can change, getlogin can't */
238 extern "C" char *
239 cuserid (char *src)
240 {
241   if (!src)
242     return getlogin ();
243
244   strcpy (src, getlogin ());
245   return src;
246 }
247
248 const char *
249 cygheap_user::ontherange (homebodies what, struct passwd *pw)
250 {
251   LPUSER_INFO_3 ui = NULL;
252   WCHAR wuser[UNLEN + 1];
253   NET_API_STATUS ret;
254   char homepath_env_buf[CYG_MAX_PATH + 1];
255   char homedrive_env_buf[3];
256   char *newhomedrive = NULL;
257   char *newhomepath = NULL;
258
259
260   debug_printf ("what %d, pw %p", what, pw);
261   if (what == CH_HOME)
262     {
263       char *p;
264       if (homedrive)
265         newhomedrive = homedrive;
266       else if ((p = getenv ("HOMEDRIVE")))
267         newhomedrive = p;
268
269       if (homepath)
270         newhomepath = homepath;
271       else if ((p = getenv ("HOMEPATH")))
272         newhomepath = p;
273
274       if ((p = getenv ("HOME")))
275         debug_printf ("HOME is already in the environment %s", p);
276       else
277         {
278           if (pw && pw->pw_dir && *pw->pw_dir)
279             {
280               debug_printf ("Set HOME (from /etc/passwd) to %s", pw->pw_dir);
281               setenv ("HOME", pw->pw_dir, 1);
282             }
283           else if (!newhomedrive || !newhomepath)
284             setenv ("HOME", "/", 1);
285           else
286             {
287               char home[CYG_MAX_PATH];
288               char buf[CYG_MAX_PATH + 1];
289               strcpy (buf, newhomedrive);
290               strcat (buf, newhomepath);
291               cygwin_conv_to_full_posix_path (buf, home);
292               debug_printf ("Set HOME (from HOMEDRIVE/HOMEPATH) to %s", home);
293               setenv ("HOME", home, 1);
294             }
295         }
296     }
297
298   if (what != CH_HOME && homepath == NULL && newhomepath == NULL)
299     {
300       if (!pw)
301         pw = internal_getpwnam (name ());
302       if (pw && pw->pw_dir && *pw->pw_dir)
303         cygwin_conv_to_full_win32_path (pw->pw_dir, homepath_env_buf);
304       else
305         {
306           homepath_env_buf[0] = homepath_env_buf[1] = '\0';
307           if (logsrv ())
308             {
309               WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
310               sys_mbstowcs (wlogsrv, logsrv (),
311                             sizeof (wlogsrv) / sizeof (*wlogsrv));
312              sys_mbstowcs (wuser, winname (), sizeof (wuser) / sizeof (*wuser));
313               if (!(ret = NetUserGetInfo (wlogsrv, wuser, 3, (LPBYTE *) &ui)))
314                 {
315                   sys_wcstombs (homepath_env_buf, ui->usri3_home_dir, CYG_MAX_PATH);
316                   if (!homepath_env_buf[0])
317                     {
318                       sys_wcstombs (homepath_env_buf, ui->usri3_home_dir_drive,
319                                     CYG_MAX_PATH);
320                       if (homepath_env_buf[0])
321                         strcat (homepath_env_buf, "\\");
322                       else
323                         cygwin_conv_to_full_win32_path ("/", homepath_env_buf);
324                     }
325                 }
326             }
327           if (ui)
328             NetApiBufferFree (ui);
329         }
330
331       if (homepath_env_buf[1] != ':')
332         {
333           newhomedrive = almost_null;
334           newhomepath = homepath_env_buf;
335         }
336       else
337         {
338           homedrive_env_buf[0] = homepath_env_buf[0];
339           homedrive_env_buf[1] = homepath_env_buf[1];
340           homedrive_env_buf[2] = '\0';
341           newhomedrive = homedrive_env_buf;
342           newhomepath = homepath_env_buf + 2;
343         }
344     }
345
346   if (newhomedrive && newhomedrive != homedrive)
347     cfree_and_set (homedrive, (newhomedrive == almost_null)
348                               ? almost_null : cstrdup (newhomedrive));
349
350   if (newhomepath && newhomepath != homepath)
351     cfree_and_set (homepath, cstrdup (newhomepath));
352
353   switch (what)
354     {
355     case CH_HOMEDRIVE:
356       return homedrive;
357     case CH_HOMEPATH:
358       return homepath;
359     default:
360       return homepath;
361     }
362 }
363
364 const char *
365 cygheap_user::test_uid (char *&what, const char *name, size_t namelen)
366 {
367   if (!what && !issetuid ())
368     what = getwinenveq (name, namelen, HEAP_STR);
369   return what;
370 }
371
372 const char *
373 cygheap_user::env_logsrv (const char *name, size_t namelen)
374 {
375   if (test_uid (plogsrv, name, namelen))
376     return plogsrv;
377
378   const char *mydomain = domain ();
379   const char *myname = winname ();
380   if (!mydomain || strcasematch (myname, "SYSTEM"))
381     return almost_null;
382
383   char logsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
384   cfree_and_set (plogsrv, almost_null);
385   if (get_logon_server (mydomain, logsrv, NULL))
386     plogsrv = cstrdup (logsrv);
387   return plogsrv;
388 }
389
390 const char *
391 cygheap_user::env_domain (const char *name, size_t namelen)
392 {
393   if (pwinname && test_uid (pdomain, name, namelen))
394     return pdomain;
395
396   char username[UNLEN + 1];
397   DWORD ulen = sizeof (username);
398   char userdomain[DNLEN + 1];
399   DWORD dlen = sizeof (userdomain);
400   SID_NAME_USE use;
401
402   cfree_and_set (pwinname, almost_null);
403   cfree_and_set (pdomain, almost_null);
404   if (!LookupAccountSid (NULL, sid (), username, &ulen,
405                          userdomain, &dlen, &use))
406     __seterrno ();
407   else
408     {
409       pwinname = cstrdup (username);
410       pdomain = cstrdup (userdomain);
411     }
412   return pdomain;
413 }
414
415 const char *
416 cygheap_user::env_userprofile (const char *name, size_t namelen)
417 {
418   if (test_uid (puserprof, name, namelen))
419     return puserprof;
420
421   char userprofile_env_buf[CYG_MAX_PATH + 1];
422   char win_id[UNLEN + 1]; /* Large enough for SID */
423
424   cfree_and_set (puserprof, almost_null);
425   if (get_registry_hive_path (get_windows_id (win_id), userprofile_env_buf))
426     puserprof = cstrdup (userprofile_env_buf);
427
428   return puserprof;
429 }
430
431 const char *
432 cygheap_user::env_homepath (const char *name, size_t namelen)
433 {
434   return ontherange (CH_HOMEPATH);
435 }
436
437 const char *
438 cygheap_user::env_homedrive (const char *name, size_t namelen)
439 {
440   return ontherange (CH_HOMEDRIVE);
441 }
442
443 const char *
444 cygheap_user::env_name (const char *name, size_t namelen)
445 {
446   if (!test_uid (pwinname, name, namelen))
447     (void) domain ();
448   return pwinname;
449 }
450
451 const char *
452 cygheap_user::env_systemroot (const char *name, size_t namelen)
453 {
454   if (!psystemroot)
455     {
456       int size = GetWindowsDirectory (NULL, 0);
457       if (size > 0)
458         {
459           psystemroot = (char *) cmalloc (HEAP_STR, ++size);
460           size = GetWindowsDirectory (psystemroot, size);
461           if (size <= 0)
462             {
463               cfree (psystemroot);
464               psystemroot = NULL;
465             }
466         }
467       if (size <= 0)
468         debug_printf ("GetWindowsDirectory(), %E");
469     }
470   return psystemroot;
471 }
472
473 char *
474 pwdgrp::next_str (char c)
475 {
476   char *res = lptr;
477   lptr = strechr (lptr, c);
478   if (*lptr)
479     *lptr++ = '\0';
480   return res;
481 }
482
483 bool
484 pwdgrp::next_num (unsigned long& n)
485 {
486   char *p = next_str (':');
487   char *cp;
488   n = strtoul (p, &cp, 10);
489   return p != cp && !*cp;
490 }
491
492 char *
493 pwdgrp::add_line (char *eptr)
494 {
495   if (eptr)
496     {
497       lptr = eptr;
498       eptr = strchr (lptr, '\n');
499       if (eptr)
500         {
501           if (eptr > lptr && eptr[-1] == '\r')
502             eptr[-1] = '\0';
503           else
504             *eptr = '\0';
505           eptr++;
506         }
507       if (curr_lines >= max_lines)
508         {
509           max_lines += 10;
510           *pwdgrp_buf = realloc (*pwdgrp_buf, max_lines * pwdgrp_buf_elem_size);
511         }
512       if ((this->*parse) ())
513         curr_lines++;
514     }
515   return eptr;
516 }
517
518 void
519 pwdgrp::load (const char *posix_fname)
520 {
521   const char *res;
522   static const char failed[] = "failed";
523   static const char succeeded[] = "succeeded";
524
525   if (buf)
526     free (buf);
527   buf = NULL;
528   curr_lines = 0;
529
530   pc.check (posix_fname);
531   etc_ix = etc::init (etc_ix, pc);
532
533   paranoid_printf ("%s", posix_fname);
534
535   if (pc.error || !pc.exists () || pc.isdir ())
536     {
537       paranoid_printf ("strange path_conv problem");
538       res = failed;
539     }
540   else
541     {
542       HANDLE fh = CreateFile (pc, GENERIC_READ, wincap.shared (), NULL,
543                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
544       if (fh == INVALID_HANDLE_VALUE)
545         {
546           paranoid_printf ("%s CreateFile failed, %E");
547           res = failed;
548         }
549       else
550         {
551           DWORD size = GetFileSize (fh, NULL), read_bytes;
552           buf = (char *) malloc (size + 1);
553           if (!ReadFile (fh, buf, size, &read_bytes, NULL))
554             {
555               paranoid_printf ("ReadFile failed, %E");
556               CloseHandle (fh);
557               if (buf)
558                 free (buf);
559               buf = NULL;
560               res = failed;
561             }
562           else
563             {
564               CloseHandle (fh);
565               buf[read_bytes] = '\0';
566               char *eptr = buf;
567               while ((eptr = add_line (eptr)))
568                 continue;
569               debug_printf ("%s curr_lines %d", posix_fname, curr_lines);
570               res = succeeded;
571             }
572         }
573     }
574
575   debug_printf ("%s load %s", posix_fname, res);
576   initialized = true;
577   return;
578 }