s3:g_lock: remove a nested event loop, replacing the inner loop by select
[Samba.git] / source3 / smbd / utmp.c
blob74774054e855d8ce04add9edb5f386ada7377e84
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
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.
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.
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/>.
21 #include "includes.h"
23 /****************************************************************************
24 Reflect connection status in utmp/wtmp files.
25 T.D.Lee@durham.ac.uk September 1999
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...
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.
40 OS observations and status:
41 Almost every OS seems to have its own quirks.
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...).
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().
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?
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.
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.
88 We need to be distinct from other entries in utmp/wtmp.
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.
102 Arbitrarily I have chosen to use a distinctive 'SM' for the
103 first two bytes.
105 The remaining two bytes encode the session 'id_num' (see above).
106 Our caller (session.c) should note our 16-bit limitation.
108 ****************************************************************************/
110 #ifndef WITH_UTMP
112 * Not WITH_UTMP? Simply supply dummy routines.
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)
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)
125 #else /* WITH_UTMP */
127 #include <utmp.h>
129 #ifdef HAVE_UTMPX_H
130 #include <utmpx.h>
131 #endif
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
139 /****************************************************************************
140 Default paths to various {u,w}tmp{,x} files.
141 ****************************************************************************/
143 #ifdef HAVE_UTMPX_H
145 static const char * const 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
156 static const char * const 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
167 #endif /* HAVE_UTMPX_H */
169 static const char * const 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
180 static const char * const 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
191 /* BSD-like systems might want "lastlog" support. */
192 #if 0 /* *** 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 #endif
204 * Get name of {u,w}tmp{,x} file.
205 * return: fname contains filename
206 * Possibly empty if this code not yet ported to this system.
208 * utmp{,x}: try "utmp dir", then default (a define)
209 * wtmp{,x}: try "wtmp dir", then "utmp dir", then default (a define)
211 static char *uw_pathname(TALLOC_CTX *ctx,
212 const char *uw_name,
213 const char *uw_default)
215 char *dirname = NULL;
217 /* For w-files, first look for explicit "wtmp dir" */
218 if (uw_name[0] == 'w') {
219 dirname = talloc_strdup(ctx, lp_wtmpdir());
220 if (!dirname) {
221 return NULL;
223 trim_char(dirname,'\0','/');
226 /* For u-files and non-explicit w-dir, look for "utmp dir" */
227 if ((dirname == NULL) || (strlen(dirname) == 0)) {
228 dirname = talloc_strdup(ctx, lp_utmpdir());
229 if (!dirname) {
230 return NULL;
232 trim_char(dirname,'\0','/');
235 /* If explicit directory above, use it */
236 if (dirname && strlen(dirname) != 0) {
237 return talloc_asprintf(ctx,
238 "%s/%s",
239 dirname,
240 uw_name);
243 /* No explicit directory: attempt to use default paths */
244 if (strlen(uw_default) == 0) {
245 /* No explicit setting, no known default.
246 * Has it yet been ported to this OS?
248 DEBUG(2,("uw_pathname: unable to determine pathname\n"));
250 return talloc_strdup(ctx, uw_default);
253 #ifndef HAVE_PUTUTLINE
254 /****************************************************************************
255 Update utmp file directly. No subroutine interface: probably a BSD system.
256 ****************************************************************************/
258 static void pututline_my(const char *uname, struct utmp *u, bool claim)
260 DEBUG(1,("pututline_my: not yet implemented\n"));
261 /* BSD implementor: may want to consider (or not) adjusting "lastlog" */
263 #endif /* HAVE_PUTUTLINE */
265 #ifndef HAVE_UPDWTMP
267 /****************************************************************************
268 Update wtmp file directly. No subroutine interface: probably a BSD system.
269 Credit: Michail Vidiassov <master@iaas.msu.ru>
270 ****************************************************************************/
272 static void updwtmp_my(const char *wname, struct utmp *u, bool claim)
274 int fd;
275 struct stat buf;
277 if (! claim) {
279 * BSD-like systems:
280 * may use empty ut_name to distinguish a logout record.
282 * May need "if defined(SUNOS4)" etc. around some of these,
283 * but try to avoid if possible.
285 * SunOS 4:
286 * man page indicates ut_name and ut_host both NULL
287 * FreeBSD 4.0:
288 * man page appears not to specify (hints non-NULL)
289 * A correspondent suggest at least ut_name should be NULL
291 #if defined(HAVE_UT_UT_NAME)
292 memset((char *)&u->ut_name, '\0', sizeof(u->ut_name));
293 #endif
294 #if defined(HAVE_UT_UT_HOST)
295 memset((char *)&u->ut_host, '\0', sizeof(u->ut_host));
296 #endif
298 /* Stolen from logwtmp function in libutil.
299 * May be more locking/blocking is needed?
301 if ((fd = open(wname, O_WRONLY|O_APPEND, 0)) < 0)
302 return;
303 if (fstat(fd, &buf) == 0) {
304 if (write(fd, (char *)u, sizeof(struct utmp)) != sizeof(struct utmp))
305 (void) ftruncate(fd, buf.st_size);
307 (void) close(fd);
309 #endif /* HAVE_UPDWTMP */
311 /****************************************************************************
312 Update via utmp/wtmp (not utmpx/wtmpx).
313 ****************************************************************************/
315 static void utmp_nox_update(struct utmp *u, bool claim)
317 char *uname = NULL;
318 char *wname = NULL;
319 #if defined(PUTUTLINE_RETURNS_UTMP)
320 struct utmp *urc;
321 #endif /* PUTUTLINE_RETURNS_UTMP */
323 uname = uw_pathname(talloc_tos(), "utmp", ut_pathname);
324 if (!uname) {
325 return;
327 DEBUG(2,("utmp_nox_update: uname:%s\n", uname));
329 #ifdef HAVE_PUTUTLINE
330 if (strlen(uname) != 0) {
331 utmpname(uname);
334 # if defined(PUTUTLINE_RETURNS_UTMP)
335 setutent();
336 urc = pututline(u);
337 endutent();
338 if (urc == NULL) {
339 DEBUG(2,("utmp_nox_update: pututline() failed\n"));
340 return;
342 # else /* PUTUTLINE_RETURNS_UTMP */
343 setutent();
344 pututline(u);
345 endutent();
346 # endif /* PUTUTLINE_RETURNS_UTMP */
348 #else /* HAVE_PUTUTLINE */
349 if (strlen(uname) != 0) {
350 pututline_my(uname, u, claim);
352 #endif /* HAVE_PUTUTLINE */
354 wname = uw_pathname(talloc_tos(), "wtmp", wt_pathname);
355 if (!wname) {
356 return;
358 DEBUG(2,("utmp_nox_update: wname:%s\n", wname));
359 if (strlen(wname) != 0) {
360 #ifdef HAVE_UPDWTMP
361 updwtmp(wname, u);
363 * updwtmp() and the newer updwtmpx() may be unsymmetrical.
364 * At least one OS, Solaris 2.x declares the former in the
365 * "utmpx" (latter) file and context.
366 * In the Solaris case this is irrelevant: it has both and
367 * we always prefer the "x" case, so doesn't come here.
368 * But are there other systems, with no "x", which lack
369 * updwtmp() perhaps?
371 #else
372 updwtmp_my(wname, u, claim);
373 #endif /* HAVE_UPDWTMP */
377 /****************************************************************************
378 Copy a string in the utmp structure.
379 ****************************************************************************/
381 static void utmp_strcpy(char *dest, const char *src, size_t n)
383 size_t len = 0;
385 memset(dest, '\0', n);
386 if (src)
387 len = strlen(src);
388 if (len >= n) {
389 memcpy(dest, src, n);
390 } else {
391 if (len)
392 memcpy(dest, src, len);
396 /****************************************************************************
397 Update via utmpx/wtmpx (preferred) or via utmp/wtmp.
398 ****************************************************************************/
400 static void sys_utmp_update(struct utmp *u, const char *hostname, bool claim)
402 #if !defined(HAVE_UTMPX_H)
403 /* No utmpx stuff. Drop to non-x stuff */
404 utmp_nox_update(u, claim);
405 #elif !defined(HAVE_PUTUTXLINE)
406 /* Odd. Have utmpx.h but no "pututxline()". Drop to non-x stuff */
407 DEBUG(1,("utmp_update: have utmpx.h but no pututxline() function\n"));
408 utmp_nox_update(u, claim);
409 #elif !defined(HAVE_GETUTMPX)
410 /* Odd. Have utmpx.h but no "getutmpx()". Drop to non-x stuff */
411 DEBUG(1,("utmp_update: have utmpx.h but no getutmpx() function\n"));
412 utmp_nox_update(u, claim);
413 #elif !defined(HAVE_UPDWTMPX)
414 /* Have utmpx.h but no "updwtmpx()". Drop to non-x stuff */
415 DEBUG(1,("utmp_update: have utmpx.h but no updwtmpx() function\n"));
416 utmp_nox_update(u, claim);
417 #else
418 char *uname = NULL;
419 char *wname = NULL;
420 struct utmpx ux, *uxrc;
422 getutmpx(u, &ux);
424 #if defined(HAVE_UX_UT_SYSLEN)
425 if (hostname)
426 ux.ut_syslen = strlen(hostname) + 1; /* include end NULL */
427 else
428 ux.ut_syslen = 0;
429 #endif
430 #if defined(HAVE_UT_UT_HOST)
431 utmp_strcpy(ux.ut_host, hostname, sizeof(ux.ut_host));
432 #endif
434 uname = uw_pathname(talloc_tos(), "utmpx", ux_pathname);
435 wname = uw_pathname(talloc_tos(), "wtmpx", wx_pathname);
436 if (uname && wname) {
437 DEBUG(2,("utmp_update: uname:%s wname:%s\n", uname, wname));
441 * Check for either uname or wname being empty.
442 * Some systems, such as Redhat 6, have a "utmpx.h" which doesn't
443 * define default filenames.
444 * Also, our local installation has not provided an override.
445 * Drop to non-x method. (E.g. RH6 has good defaults in "utmp.h".)
447 if (!uname || !wname || (strlen(uname) == 0) || (strlen(wname) == 0)) {
448 utmp_nox_update(u, claim);
449 } else {
450 utmpxname(uname);
451 setutxent();
452 uxrc = pututxline(&ux);
453 endutxent();
454 if (uxrc == NULL) {
455 DEBUG(2,("utmp_update: pututxline() failed\n"));
456 return;
458 updwtmpx(wname, &ux);
460 #endif /* HAVE_UTMPX_H */
463 #if defined(HAVE_UT_UT_ID)
464 /****************************************************************************
465 Encode the unique connection number into "ut_id".
466 ****************************************************************************/
468 static int ut_id_encode(int i, char *fourbyte)
470 int nbase;
471 const char *ut_id_encstr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
473 fourbyte[0] = 'S';
474 fourbyte[1] = 'M';
477 * Encode remaining 2 bytes from 'i'.
478 * 'ut_id_encstr' is the character set on which modulo arithmetic is done.
479 * Example: digits would produce the base-10 numbers from '001'.
481 nbase = strlen(ut_id_encstr);
483 fourbyte[3] = ut_id_encstr[i % nbase];
484 i /= nbase;
485 fourbyte[2] = ut_id_encstr[i % nbase];
486 i /= nbase;
488 return(i); /* 0: good; else overflow */
490 #endif /* defined(HAVE_UT_UT_ID) */
494 fill a system utmp structure given all the info we can gather
496 static bool sys_utmp_fill(struct utmp *u,
497 const char *username, const char *hostname,
498 const char *ip_addr_str,
499 const char *id_str, int id_num)
501 struct timeval timeval;
504 * ut_name, ut_user:
505 * Several (all?) systems seems to define one as the other.
506 * It is easier and clearer simply to let the following take its course,
507 * rather than to try to detect and optimise.
509 #if defined(HAVE_UT_UT_USER)
510 utmp_strcpy(u->ut_user, username, sizeof(u->ut_user));
511 #elif defined(HAVE_UT_UT_NAME)
512 utmp_strcpy(u->ut_name, username, sizeof(u->ut_name));
513 #endif
516 * ut_line:
517 * If size limit proves troublesome, then perhaps use "ut_id_encode()".
519 if (strlen(id_str) > sizeof(u->ut_line)) {
520 DEBUG(1,("id_str [%s] is too long for %lu char utmp field\n",
521 id_str, (unsigned long)sizeof(u->ut_line)));
522 return False;
524 utmp_strcpy(u->ut_line, id_str, sizeof(u->ut_line));
526 #if defined(HAVE_UT_UT_PID)
527 u->ut_pid = sys_getpid();
528 #endif
531 * ut_time, ut_tv:
532 * Some have one, some the other. Many have both, but defined (aliased).
533 * It is easier and clearer simply to let the following take its course.
534 * But note that we do the more precise ut_tv as the final assignment.
536 #if defined(HAVE_UT_UT_TIME)
537 GetTimeOfDay(&timeval);
538 u->ut_time = timeval.tv_sec;
539 #elif defined(HAVE_UT_UT_TV)
540 GetTimeOfDay(&timeval);
541 u->ut_tv = timeval;
542 #else
543 #error "with-utmp must have UT_TIME or UT_TV"
544 #endif
546 #if defined(HAVE_UT_UT_HOST)
547 utmp_strcpy(u->ut_host, hostname, sizeof(u->ut_host));
548 #endif
549 #if defined(HAVE_IPV6) && defined(HAVE_UT_UT_ADDR_V6)
550 memset(&u->ut_addr_v6, '\0', sizeof(u->ut_addr_v6));
551 if (ip_addr_str) {
552 struct in6_addr addr;
553 if (inet_pton(AF_INET6, ip_addr_str, &addr) > 0) {
554 memcpy(&u->ut_addr_v6, &addr, sizeof(addr));
557 #elif defined(HAVE_UT_UT_ADDR)
558 memset(&u->ut_addr, '\0', sizeof(u->ut_addr));
559 if (ip_addr_str) {
560 struct in_addr addr;
561 if (inet_pton(AF_INET, ip_addr_str, &addr) > 0) {
562 memcpy(&u->ut_addr, &addr, sizeof(addr));
566 * "(unsigned long) ut_addr" apparently exists on at least HP-UX 10.20.
567 * Volunteer to implement, please ...
569 #endif
571 #if defined(HAVE_UT_UT_ID)
572 if (ut_id_encode(id_num, u->ut_id) != 0) {
573 DEBUG(1,("utmp_fill: cannot encode id %d\n", id_num));
574 return False;
576 #endif
578 return True;
581 /****************************************************************************
582 Close a connection.
583 ****************************************************************************/
585 void sys_utmp_yield(const char *username, const char *hostname,
586 const char *ip_addr_str,
587 const char *id_str, int id_num)
589 struct utmp u;
591 ZERO_STRUCT(u);
593 #if defined(HAVE_UT_UT_EXIT)
594 u.ut_exit.e_termination = 0;
595 u.ut_exit.e_exit = 0;
596 #endif
598 #if defined(HAVE_UT_UT_TYPE)
599 u.ut_type = DEAD_PROCESS;
600 #endif
602 if (!sys_utmp_fill(&u, username, hostname, ip_addr_str, id_str, id_num))
603 return;
605 sys_utmp_update(&u, NULL, False);
608 /****************************************************************************
609 Claim a entry in whatever utmp system the OS uses.
610 ****************************************************************************/
612 void sys_utmp_claim(const char *username, const char *hostname,
613 const char *ip_addr_str,
614 const char *id_str, int id_num)
616 struct utmp u;
618 ZERO_STRUCT(u);
620 #if defined(HAVE_UT_UT_TYPE)
621 u.ut_type = USER_PROCESS;
622 #endif
624 if (!sys_utmp_fill(&u, username, hostname, ip_addr_str, id_str, id_num))
625 return;
627 sys_utmp_update(&u, hostname, True);
630 #endif /* WITH_UTMP */