Replace find_forced_user by a direct call to make_serverinfo_from_username
[samba.git] / source3 / smbd / utmp.c
1 /* 
2    Unix SMB/CIFS implementation.
3    utmp routines
4    Copyright (C) T.D.Lee@durham.ac.uk 1999
5    Heavily modified by Andrew Bartlett and Tridge, April 2001
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22
23 /****************************************************************************
24 Reflect connection status in utmp/wtmp files.
25         T.D.Lee@durham.ac.uk  September 1999
26
27         With grateful thanks since then to many who have helped port it to
28         different operating systems.  The variety of OS quirks thereby
29         uncovered is amazing...
30
31 Hints for porting:
32         o  Always attempt to use programmatic interface (pututline() etc.)
33            Indeed, at present only programmatic use is supported.
34         o  The only currently supported programmatic interface to "wtmp{,x}"
35            is through "updwtmp*()" routines.
36         o  The "x" (utmpx/wtmpx; HAVE_UTMPX_H) seems preferable.
37         o  The HAVE_* items should identify supported features.
38         o  If at all possible, avoid "if defined(MY-OS)" constructions.
39
40 OS observations and status:
41         Almost every OS seems to have its own quirks.
42
43         Solaris 2.x:
44                 Tested on 2.6 and 2.7; should be OK on other flavours.
45         AIX:
46                 Apparently has utmpx.h but doesn't implement.
47         OSF:
48                 Has utmpx.h, but (e.g.) no "getutmpx()".  (Is this like AIX ?)
49         Redhat 6:
50                 utmpx.h seems not to set default filenames.  non-x better.
51         IRIX 6.5:
52                 Not tested.  Appears to have "x".
53         HP-UX 9.x:
54                 Not tested.  Appears to lack "x".
55         HP-UX 10.x:
56                 Not tested.
57                 "updwtmp*()" routines seem absent, so no current wtmp* support.
58                 Has "ut_addr": probably trivial to implement (although remember
59                 that IPv6 is coming...).
60
61         FreeBSD:
62                 No "putut*()" type of interface.
63                 No "ut_type" and associated defines. 
64                 Write files directly.  Alternatively use its login(3)/logout(3).
65         SunOS 4:
66                 Not tested.  Resembles FreeBSD, but no login()/logout().
67
68 lastlog:
69         Should "lastlog" files, if any, be updated?
70         BSD systems (SunOS 4, FreeBSD):
71                 o  Prominent mention on man pages.
72         System-V (e.g. Solaris 2):
73                 o  No mention on man pages, even under "man -k".
74                 o  Has a "/var/adm/lastlog" file, but pututxline() etc. seem
75                    not to touch it.
76                 o  Despite downplaying (above), nevertheless has <lastlog.h>.
77         So perhaps UN*X "lastlog" facility is intended for tty/terminal only?
78
79 Notes:
80         Each connection requires a small number (starting at 0, working up)
81         to represent the line.  This must be unique within and across all
82         smbd processes.  It is the 'id_num' from Samba's session.c code.
83
84         The 4 byte 'ut_id' component is vital to distinguish connections,
85         of which there could be several hundred or even thousand.
86         Entries seem to be printable characters, with optional NULL pads.
87
88         We need to be distinct from other entries in utmp/wtmp.
89
90         Observed things: therefore avoid them.  Add to this list please.
91         From Solaris 2.x (because that's what I have):
92                 'sN'    : run-levels; N: [0-9]
93                 'co'    : console
94                 'CC'    : arbitrary things;  C: [a-z]
95                 'rXNN'  : rlogin;  N: [0-9]; X: [0-9a-z]
96                 'tXNN'  : rlogin;  N: [0-9]; X: [0-9a-z]
97                 '/NNN'  : Solaris CDE
98                 'ftpZ'  : ftp (Z is the number 255, aka 0377, aka 0xff)
99         Mostly a record uses the same 'ut_id' in both "utmp" and "wtmp",
100         but differences have been seen.
101
102         Arbitrarily I have chosen to use a distinctive 'SM' for the
103         first two bytes.
104
105         The remaining two bytes encode the session 'id_num' (see above).
106         Our caller (session.c) should note our 16-bit limitation.
107
108 ****************************************************************************/
109
110 #ifndef WITH_UTMP
111 /*
112  * Not WITH_UTMP?  Simply supply dummy routines.
113  */
114
115 void sys_utmp_claim(const char *username, const char *hostname,
116                         const char *ip_addr_str,
117                         const char *id_str, int id_num)
118 {}
119
120 void sys_utmp_yield(const char *username, const char *hostname,
121                         const char *ip_addr_str,
122                         const char *id_str, int id_num)
123 {}
124
125 #else /* WITH_UTMP */
126
127 #include <utmp.h>
128
129 #ifdef HAVE_UTMPX_H
130 #include <utmpx.h>
131 #endif
132
133 /* BSD systems: some may need lastlog.h (SunOS 4), some may not (FreeBSD) */
134 /* Some System-V systems (e.g. Solaris 2) declare this too. */
135 #ifdef HAVE_LASTLOG_H
136 #include <lastlog.h>
137 #endif
138
139 /****************************************************************************
140  Default paths to various {u,w}tmp{,x} files.
141 ****************************************************************************/
142
143 #ifdef  HAVE_UTMPX_H
144
145 static const char *ux_pathname =
146 # if defined (UTMPX_FILE)
147         UTMPX_FILE ;
148 # elif defined (_UTMPX_FILE)
149         _UTMPX_FILE ;
150 # elif defined (_PATH_UTMPX)
151         _PATH_UTMPX ;
152 # else
153         "" ;
154 # endif
155
156 static const char *wx_pathname =
157 # if defined (WTMPX_FILE)
158         WTMPX_FILE ;
159 # elif defined (_WTMPX_FILE)
160         _WTMPX_FILE ;
161 # elif defined (_PATH_WTMPX)
162         _PATH_WTMPX ;
163 # else
164         "" ;
165 # endif
166
167 #endif  /* HAVE_UTMPX_H */
168
169 static const char *ut_pathname =
170 # if defined (UTMP_FILE)
171         UTMP_FILE ;
172 # elif defined (_UTMP_FILE)
173         _UTMP_FILE ;
174 # elif defined (_PATH_UTMP)
175         _PATH_UTMP ;
176 # else
177         "" ;
178 # endif
179
180 static const char *wt_pathname =
181 # if defined (WTMP_FILE)
182         WTMP_FILE ;
183 # elif defined (_WTMP_FILE)
184         _WTMP_FILE ;
185 # elif defined (_PATH_WTMP)
186         _PATH_WTMP ;
187 # else
188         "" ;
189 # endif
190
191 /* BSD-like systems might want "lastlog" support. */
192 /* *** Not yet implemented */
193 #ifndef HAVE_PUTUTLINE          /* see "pututline_my()" */
194 static const char *ll_pathname =
195 # if defined (_PATH_LASTLOG)    /* what other names (if any?) */
196         _PATH_LASTLOG ;
197 # else
198         "" ;
199 # endif /* _PATH_LASTLOG */
200 #endif  /* HAVE_PUTUTLINE */
201
202 /*
203  * Get name of {u,w}tmp{,x} file.
204  *      return: fname contains filename
205  *              Possibly empty if this code not yet ported to this system.
206  *
207  * utmp{,x}:  try "utmp dir", then default (a define)
208  * wtmp{,x}:  try "wtmp dir", then "utmp dir", then default (a define)
209  */
210 static char *uw_pathname(TALLOC_CTX *ctx,
211                 const char *uw_name,
212                 const char *uw_default)
213 {
214         char *dirname = NULL;
215
216         /* For w-files, first look for explicit "wtmp dir" */
217         if (uw_name[0] == 'w') {
218                 dirname = talloc_strdup(ctx, lp_wtmpdir());
219                 if (!dirname) {
220                         return NULL;
221                 }
222                 trim_char(dirname,'\0','/');
223         }
224
225         /* For u-files and non-explicit w-dir, look for "utmp dir" */
226         if ((dirname == NULL) || (strlen(dirname) == 0)) {
227                 dirname = talloc_strdup(ctx, lp_utmpdir());
228                 if (!dirname) {
229                         return NULL;
230                 }
231                 trim_char(dirname,'\0','/');
232         }
233
234         /* If explicit directory above, use it */
235         if (dirname && strlen(dirname) != 0) {
236                 return talloc_asprintf(ctx,
237                                 "%s/%s",
238                                 dirname,
239                                 uw_name);
240         }
241
242         /* No explicit directory: attempt to use default paths */
243         if (strlen(uw_default) == 0) {
244                 /* No explicit setting, no known default.
245                  * Has it yet been ported to this OS?
246                  */
247                 DEBUG(2,("uw_pathname: unable to determine pathname\n"));
248         }
249         return talloc_strdup(ctx, uw_default);
250 }
251
252 #ifndef HAVE_PUTUTLINE
253 /****************************************************************************
254  Update utmp file directly.  No subroutine interface: probably a BSD system.
255 ****************************************************************************/
256
257 static void pututline_my(const char *uname, struct utmp *u, bool claim)
258 {
259         DEBUG(1,("pututline_my: not yet implemented\n"));
260         /* BSD implementor: may want to consider (or not) adjusting "lastlog" */
261 }
262 #endif /* HAVE_PUTUTLINE */
263
264 #ifndef HAVE_UPDWTMP
265
266 /****************************************************************************
267  Update wtmp file directly.  No subroutine interface: probably a BSD system.
268  Credit: Michail Vidiassov <master@iaas.msu.ru>
269 ****************************************************************************/
270
271 static void updwtmp_my(const char *wname, struct utmp *u, bool claim)
272 {
273         int fd;
274         struct stat buf;
275
276         if (! claim) {
277                 /*
278                  * BSD-like systems:
279                  *      may use empty ut_name to distinguish a logout record.
280                  *
281                  * May need "if defined(SUNOS4)" etc. around some of these,
282                  * but try to avoid if possible.
283                  *
284                  * SunOS 4:
285                  *      man page indicates ut_name and ut_host both NULL
286                  * FreeBSD 4.0:
287                  *      man page appears not to specify (hints non-NULL)
288                  *      A correspondent suggest at least ut_name should be NULL
289                  */
290 #if defined(HAVE_UT_UT_NAME)
291                 memset((char *)&u->ut_name, '\0', sizeof(u->ut_name));
292 #endif
293 #if defined(HAVE_UT_UT_HOST)
294                 memset((char *)&u->ut_host, '\0', sizeof(u->ut_host));
295 #endif
296         }
297         /* Stolen from logwtmp function in libutil.
298          * May be more locking/blocking is needed?
299          */
300         if ((fd = open(wname, O_WRONLY|O_APPEND, 0)) < 0)
301                 return;
302         if (fstat(fd, &buf) == 0) {
303                 if (write(fd, (char *)u, sizeof(struct utmp)) != sizeof(struct utmp))
304                 (void) ftruncate(fd, buf.st_size);
305         }
306         (void) close(fd);
307 }
308 #endif /* HAVE_UPDWTMP */
309
310 /****************************************************************************
311  Update via utmp/wtmp (not utmpx/wtmpx).
312 ****************************************************************************/
313
314 static void utmp_nox_update(struct utmp *u, bool claim)
315 {
316         char *uname = NULL;
317         char *wname = NULL;
318 #if defined(PUTUTLINE_RETURNS_UTMP)
319         struct utmp *urc;
320 #endif /* PUTUTLINE_RETURNS_UTMP */
321
322         uname = uw_pathname(talloc_tos(), "utmp", ut_pathname);
323         if (!uname) {
324                 return;
325         }
326         DEBUG(2,("utmp_nox_update: uname:%s\n", uname));
327
328 #ifdef HAVE_PUTUTLINE
329         if (strlen(uname) != 0) {
330                 utmpname(uname);
331         }
332
333 # if defined(PUTUTLINE_RETURNS_UTMP)
334         setutent();
335         urc = pututline(u);
336         endutent();
337         if (urc == NULL) {
338                 DEBUG(2,("utmp_nox_update: pututline() failed\n"));
339                 return;
340         }
341 # else  /* PUTUTLINE_RETURNS_UTMP */
342         setutent();
343         pututline(u);
344         endutent();
345 # endif /* PUTUTLINE_RETURNS_UTMP */
346
347 #else   /* HAVE_PUTUTLINE */
348         if (strlen(uname) != 0) {
349                 pututline_my(uname, u, claim);
350         }
351 #endif /* HAVE_PUTUTLINE */
352
353         wname = uw_pathname(talloc_tos(), "wtmp", wt_pathname);
354         if (!wname) {
355                 return;
356         }
357         DEBUG(2,("utmp_nox_update: wname:%s\n", wname));
358         if (strlen(wname) != 0) {
359 #ifdef HAVE_UPDWTMP
360                 updwtmp(wname, u);
361                 /*
362                  * updwtmp() and the newer updwtmpx() may be unsymmetrical.
363                  * At least one OS, Solaris 2.x declares the former in the
364                  * "utmpx" (latter) file and context.
365                  * In the Solaris case this is irrelevant: it has both and
366                  * we always prefer the "x" case, so doesn't come here.
367                  * But are there other systems, with no "x", which lack
368                  * updwtmp() perhaps?
369                  */
370 #else
371                 updwtmp_my(wname, u, claim);
372 #endif /* HAVE_UPDWTMP */
373         }
374 }
375
376 /****************************************************************************
377  Copy a string in the utmp structure.
378 ****************************************************************************/
379
380 static void utmp_strcpy(char *dest, const char *src, size_t n)
381 {
382         size_t len = 0;
383
384         memset(dest, '\0', n);
385         if (src)
386                 len = strlen(src);
387         if (len >= n) {
388                 memcpy(dest, src, n);
389         } else {
390                 if (len)
391                         memcpy(dest, src, len);
392         }
393 }
394
395 /****************************************************************************
396  Update via utmpx/wtmpx (preferred) or via utmp/wtmp.
397 ****************************************************************************/
398
399 static void sys_utmp_update(struct utmp *u, const char *hostname, bool claim)
400 {
401 #if !defined(HAVE_UTMPX_H)
402         /* No utmpx stuff.  Drop to non-x stuff */
403         utmp_nox_update(u, claim);
404 #elif !defined(HAVE_PUTUTXLINE)
405         /* Odd.  Have utmpx.h but no "pututxline()".  Drop to non-x stuff */
406         DEBUG(1,("utmp_update: have utmpx.h but no pututxline() function\n"));
407         utmp_nox_update(u, claim);
408 #elif !defined(HAVE_GETUTMPX)
409         /* Odd.  Have utmpx.h but no "getutmpx()".  Drop to non-x stuff */
410         DEBUG(1,("utmp_update: have utmpx.h but no getutmpx() function\n"));
411         utmp_nox_update(u, claim);
412 #elif !defined(HAVE_UPDWTMPX)
413         /* Have utmpx.h but no "updwtmpx()".  Drop to non-x stuff */
414         DEBUG(1,("utmp_update: have utmpx.h but no updwtmpx() function\n"));
415         utmp_nox_update(u, claim);
416 #else
417         char *uname = NULL;
418         char *wname = NULL;
419         struct utmpx ux, *uxrc;
420
421         getutmpx(u, &ux);
422
423 #if defined(HAVE_UX_UT_SYSLEN)
424         if (hostname)
425                 ux.ut_syslen = strlen(hostname) + 1;    /* include end NULL */
426         else
427                 ux.ut_syslen = 0;
428 #endif
429 #if defined(HAVE_UT_UT_HOST)
430         utmp_strcpy(ux.ut_host, hostname, sizeof(ux.ut_host));
431 #endif
432
433         uname = uw_pathname(talloc_tos(), "utmpx", ux_pathname);
434         wname = uw_pathname(talloc_tos(), "wtmpx", wx_pathname);
435         if (uname && wname) {
436                 DEBUG(2,("utmp_update: uname:%s wname:%s\n", uname, wname));
437         }
438
439         /*
440          * Check for either uname or wname being empty.
441          * Some systems, such as Redhat 6, have a "utmpx.h" which doesn't
442          * define default filenames.
443          * Also, our local installation has not provided an override.
444          * Drop to non-x method.  (E.g. RH6 has good defaults in "utmp.h".)
445          */
446         if (!uname || !wname || (strlen(uname) == 0) || (strlen(wname) == 0)) {
447                 utmp_nox_update(u, claim);
448         } else {
449                 utmpxname(uname);
450                 setutxent();
451                 uxrc = pututxline(&ux);
452                 endutxent();
453                 if (uxrc == NULL) {
454                         DEBUG(2,("utmp_update: pututxline() failed\n"));
455                         return;
456                 }
457                 updwtmpx(wname, &ux);
458         }
459 #endif /* HAVE_UTMPX_H */
460 }
461
462 #if defined(HAVE_UT_UT_ID)
463 /****************************************************************************
464  Encode the unique connection number into "ut_id".
465 ****************************************************************************/
466
467 static int ut_id_encode(int i, char *fourbyte)
468 {
469         int nbase;
470         const char *ut_id_encstr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
471
472         fourbyte[0] = 'S';
473         fourbyte[1] = 'M';
474
475 /*
476  * Encode remaining 2 bytes from 'i'.
477  * 'ut_id_encstr' is the character set on which modulo arithmetic is done.
478  * Example: digits would produce the base-10 numbers from '001'.
479  */
480         nbase = strlen(ut_id_encstr);
481
482         fourbyte[3] = ut_id_encstr[i % nbase];
483         i /= nbase;
484         fourbyte[2] = ut_id_encstr[i % nbase];
485         i /= nbase;
486
487         return(i);      /* 0: good; else overflow */
488 }
489 #endif /* defined(HAVE_UT_UT_ID) */
490
491
492 /*
493   fill a system utmp structure given all the info we can gather
494 */
495 static bool sys_utmp_fill(struct utmp *u,
496                         const char *username, const char *hostname,
497                         const char *ip_addr_str,
498                         const char *id_str, int id_num)
499 {
500         struct timeval timeval;
501
502         /*
503          * ut_name, ut_user:
504          *      Several (all?) systems seems to define one as the other.
505          *      It is easier and clearer simply to let the following take its course,
506          *      rather than to try to detect and optimise.
507          */
508 #if defined(HAVE_UT_UT_USER)
509         utmp_strcpy(u->ut_user, username, sizeof(u->ut_user));
510 #elif defined(HAVE_UT_UT_NAME)
511         utmp_strcpy(u->ut_name, username, sizeof(u->ut_name));
512 #endif
513
514         /*
515          * ut_line:
516          *      If size limit proves troublesome, then perhaps use "ut_id_encode()".
517          */
518         if (strlen(id_str) > sizeof(u->ut_line)) {
519                 DEBUG(1,("id_str [%s] is too long for %lu char utmp field\n",
520                          id_str, (unsigned long)sizeof(u->ut_line)));
521                 return False;
522         }
523         utmp_strcpy(u->ut_line, id_str, sizeof(u->ut_line));
524
525 #if defined(HAVE_UT_UT_PID)
526         u->ut_pid = sys_getpid();
527 #endif
528
529 /*
530  * ut_time, ut_tv:
531  *      Some have one, some the other.  Many have both, but defined (aliased).
532  *      It is easier and clearer simply to let the following take its course.
533  *      But note that we do the more precise ut_tv as the final assignment.
534  */
535 #if defined(HAVE_UT_UT_TIME)
536         GetTimeOfDay(&timeval);
537         u->ut_time = timeval.tv_sec;
538 #elif defined(HAVE_UT_UT_TV)
539         GetTimeOfDay(&timeval);
540         u->ut_tv = timeval;
541 #else
542 #error "with-utmp must have UT_TIME or UT_TV"
543 #endif
544
545 #if defined(HAVE_UT_UT_HOST)
546         utmp_strcpy(u->ut_host, hostname, sizeof(u->ut_host));
547 #endif
548 #if defined(HAVE_IPV6) && defined(HAVE_UT_UT_ADDR_V6)
549         memset(&u->ut_addr_v6, '\0', sizeof(u->ut_addr_v6));
550         if (ip_addr_str) {
551                 struct in6_addr addr;
552                 if (inet_pton(AF_INET6, ip_addr_str, &addr) > 0) {
553                         memcpy(&u->ut_addr_v6, &addr, sizeof(addr));
554                 }
555         }
556 #elif defined(HAVE_UT_UT_ADDR)
557         memset(&u->ut_addr, '\0', sizeof(u->ut_addr));
558         if (ip_addr_str) {
559                 struct in_addr addr;
560                 if (inet_pton(AF_INET, ip_addr_str, &addr) > 0) {
561                         memcpy(&u->ut_addr, &addr, sizeof(addr));
562                 }
563         }
564         /*
565          * "(unsigned long) ut_addr" apparently exists on at least HP-UX 10.20.
566          * Volunteer to implement, please ...
567          */
568 #endif
569
570 #if defined(HAVE_UT_UT_ID)
571         if (ut_id_encode(id_num, u->ut_id) != 0) {
572                 DEBUG(1,("utmp_fill: cannot encode id %d\n", id_num));
573                 return False;
574         }
575 #endif
576
577         return True;
578 }
579
580 /****************************************************************************
581  Close a connection.
582 ****************************************************************************/
583
584 void sys_utmp_yield(const char *username, const char *hostname,
585                         const char *ip_addr_str,
586                         const char *id_str, int id_num)
587 {
588         struct utmp u;
589
590         ZERO_STRUCT(u);
591
592 #if defined(HAVE_UT_UT_EXIT)
593         u.ut_exit.e_termination = 0;
594         u.ut_exit.e_exit = 0;
595 #endif
596
597 #if defined(HAVE_UT_UT_TYPE)
598         u.ut_type = DEAD_PROCESS;
599 #endif
600
601         if (!sys_utmp_fill(&u, username, hostname, ip_addr_str, id_str, id_num))
602                 return;
603
604         sys_utmp_update(&u, NULL, False);
605 }
606
607 /****************************************************************************
608  Claim a entry in whatever utmp system the OS uses.
609 ****************************************************************************/
610
611 void sys_utmp_claim(const char *username, const char *hostname,
612                         const char *ip_addr_str,
613                         const char *id_str, int id_num)
614 {
615         struct utmp u;
616
617         ZERO_STRUCT(u);
618
619 #if defined(HAVE_UT_UT_TYPE)
620         u.ut_type = USER_PROCESS;
621 #endif
622
623         if (!sys_utmp_fill(&u, username, hostname, ip_addr_str, id_str, id_num))
624                 return;
625
626         sys_utmp_update(&u, hostname, True);
627 }
628
629 #endif /* WITH_UTMP */