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