This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[mdw/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 2 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, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 #ifdef WITH_UTMP
25
26 /****************************************************************************
27 Reflect connection status in utmp/wtmp files.
28         T.D.Lee@durham.ac.uk  September 1999
29
30         With grateful thanks since then to many who have helped port it to
31         different operating systems.  The variety of OS quirks thereby
32         uncovered is amazing...
33
34 Hints for porting:
35         o  Always attempt to use programmatic interface (pututline() etc.)
36            Indeed, at present only programmatic use is supported.
37         o  The only currently supported programmatic interface to "wtmp{,x}"
38            is through "updwtmp*()" routines.
39         o  The "x" (utmpx/wtmpx; HAVE_UTMPX_H) seems preferable.
40         o  The HAVE_* items should identify supported features.
41         o  If at all possible, avoid "if defined(MY-OS)" constructions.
42
43 OS observations and status:
44         Almost every OS seems to have its own quirks.
45
46         Solaris 2.x:
47                 Tested on 2.6 and 2.7; should be OK on other flavours.
48         AIX:
49                 Apparently has utmpx.h but doesn't implement.
50         OSF:
51                 Has utmpx.h, but (e.g.) no "getutmpx()".  (Is this like AIX ?)
52         Redhat 6:
53                 utmpx.h seems not to set default filenames.  non-x better.
54         IRIX 6.5:
55                 Not tested.  Appears to have "x".
56         HP-UX 9.x:
57                 Not tested.  Appears to lack "x".
58         HP-UX 10.x:
59                 Not tested.
60                 "updwtmp*()" routines seem absent, so no current wtmp* support.
61                 Has "ut_addr": probably trivial to implement (although remember
62                 that IPv6 is coming...).
63
64         FreeBSD:
65                 No "putut*()" type of interface.
66                 No "ut_type" and associated defines. 
67                 Write files directly.  Alternatively use its login(3)/logout(3).
68         SunOS 4:
69                 Not tested.  Resembles FreeBSD, but no login()/logout().
70
71 lastlog:
72         Should "lastlog" files, if any, be updated?
73         BSD systems (SunOS 4, FreeBSD):
74                 o  Prominent mention on man pages.
75         System-V (e.g. Solaris 2):
76                 o  No mention on man pages, even under "man -k".
77                 o  Has a "/var/adm/lastlog" file, but pututxline() etc. seem
78                    not to touch it.
79                 o  Despite downplaying (above), nevertheless has <lastlog.h>.
80         So perhaps UN*X "lastlog" facility is intended for tty/terminal only?
81
82 Notes:
83         Each connection requires a small number (starting at 0, working up)
84         to represent the line (unum).  This must be unique within and across
85         all smbd processes.
86
87         The 4 byte 'ut_id' component is vital to distinguish connections,
88         of which there could be several hundered or even thousand.
89         Entries seem to be printable characters, with optional NULL pads.
90
91         We need to be distinct from other entries in utmp/wtmp.
92
93         Observed things: therefore avoid them.  Add to this list please.
94         From Solaris 2.x (because that's what I have):
95                 'sN'    : run-levels; N: [0-9]
96                 'co'    : console
97                 'CC'    : arbitrary things;  C: [a-z]
98                 'rXNN'  : rlogin;  N: [0-9]; X: [0-9a-z]
99                 'tXNN'  : rlogin;  N: [0-9]; X: [0-9a-z]
100                 '/NNN'  : Solaris CDE
101                 'ftpZ'  : ftp (Z is the number 255, aka 0377, aka 0xff)
102         Mostly a record uses the same 'ut_id' in both "utmp" and "wtmp",
103         but differences have been seen.
104
105         Arbitrarily I have chosen to use a distinctive 'SM' for the
106         first two bytes.
107
108         The remaining two encode the "unum" (see above).
109
110         For "utmp consolidate" the suggestion was made to encode the pid into
111         those remaining two bytes (16 bits).  But recent UNIX (e.g Solaris 8)
112         is migrating to pids > 16 bits, so we ought not to do this.
113
114 ****************************************************************************/
115
116 #include <utmp.h>
117
118 #ifdef HAVE_UTMPX_H
119 #include <utmpx.h>
120 #endif
121
122 /* BSD systems: some may need lastlog.h (SunOS 4), some may not (FreeBSD) */
123 /* Some System-V systems (e.g. Solaris 2) declare this too. */
124 #ifdef HAVE_LASTLOG_H
125 #include <lastlog.h>
126 #endif
127
128 /****************************************************************************
129  Obtain/release a small number (0 upwards) unique within and across smbds.
130 ****************************************************************************/
131 /*
132  * Need a "small" number to represent this connection, unique within this
133  * smbd and across all smbds.
134  *
135  * claim:
136  *      Start at 0, hunt up for free, unique number "unum" by attempting to
137  *      store it as a key in a tdb database:
138  *              key: unum               data: pid+conn  
139  *      Also store its inverse, ready for yield function:
140  *              key: pid+conn           data: unum
141  *
142  * yield:
143  *      Find key: pid+conn; data is unum;  delete record
144  *      Find key: unum ; delete record.
145  *
146  * Comment:
147  *      The claim algorithm (a "for" loop attempting to store numbers in a tdb
148  *      database) will be increasingly inefficient with larger numbers of
149  *      connections.  Is it possible to write a suitable primitive within tdb?
150  *
151  *      However, by also storing the inverse key/data pair, we at least make
152  *      the yield algorithm efficient.
153  */
154
155 /****************************************************************************
156  Default paths to various {u,w}tmp{,x} files.
157 ****************************************************************************/
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 /****************************************************************************
265  Update utmp file directly.  No subroutine interface: probably a BSD system.
266 ****************************************************************************/
267
268 static void pututline_my(pstring uname, struct utmp *u, BOOL claim)
269 {
270         DEBUG(1,("pututline_my: not yet implemented\n"));
271         /* BSD implementor: may want to consider (or not) adjusting "lastlog" */
272 }
273 #endif /* HAVE_PUTUTLINE */
274
275 #ifndef HAVE_UPDWTMP
276
277 /****************************************************************************
278  Update wtmp file directly.  No subroutine interface: probably a BSD system.
279  Credit: Michail Vidiassov <master@iaas.msu.ru>
280 ****************************************************************************/
281
282 static void updwtmp_my(pstring wname, struct utmp *u, BOOL claim)
283 {
284         int fd;
285         struct stat buf;
286
287         if (! claim) {
288                 /*
289                  * BSD-like systems:
290                  *      may use empty ut_name to distinguish a logout record.
291                  *
292                  * May need "if defined(SUNOS4)" etc. around some of these,
293                  * but try to avoid if possible.
294                  *
295                  * SunOS 4:
296                  *      man page indicates ut_name and ut_host both NULL
297                  * FreeBSD 4.0:
298                  *      man page appears not to specify (hints non-NULL)
299                  *      A correspondent suggest at least ut_name should be NULL
300                  */
301                 memset((char *)&u->ut_name, '\0', sizeof(u->ut_name));
302                 memset((char *)&u->ut_host, '\0', sizeof(u->ut_host));
303         }
304         /* Stolen from logwtmp function in libutil.
305          * May be more locking/blocking is needed?
306          */
307         if ((fd = open(wname, O_WRONLY|O_APPEND, 0)) < 0)
308                 return;
309         if (fstat(fd, &buf) == 0) {
310                 if (write(fd, (char *)u, sizeof(struct utmp)) != sizeof(struct utmp))
311                 (void) ftruncate(fd, buf.st_size);
312         }
313         (void) close(fd);
314 }
315 #endif /* HAVE_UPDWTMP */
316
317 /****************************************************************************
318  Update via utmp/wtmp (not utmpx/wtmpx).
319 ****************************************************************************/
320
321 static void utmp_nox_update(struct utmp *u, BOOL claim)
322 {
323         pstring uname, wname;
324 #if defined(PUTUTLINE_RETURNS_UTMP)
325         struct utmp *urc;
326 #endif /* PUTUTLINE_RETURNS_UTMP */
327
328         uw_pathname(uname, "utmp", ut_pathname);
329         DEBUG(2,("utmp_nox_update: uname:%s\n", uname));
330
331 #ifdef HAVE_PUTUTLINE
332         if (strlen(uname) != 0) {
333                 utmpname(uname);
334         }
335
336 # if defined(PUTUTLINE_RETURNS_UTMP)
337         setutent();
338         urc = pututline(u);
339         endutent();
340         if (urc == NULL) {
341                 DEBUG(2,("utmp_nox_update: pututline() failed\n"));
342                 return;
343         }
344 # else  /* PUTUTLINE_RETURNS_UTMP */
345         setutent();
346         pututline(u);
347         endutent();
348 # endif /* PUTUTLINE_RETURNS_UTMP */
349
350 #else   /* HAVE_PUTUTLINE */
351         if (strlen(uname) != 0) {
352                 pututline_my(uname, u, claim);
353         }
354 #endif /* HAVE_PUTUTLINE */
355
356         uw_pathname(wname, "wtmp", wt_pathname);
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 #else
413         pstring uname, wname;
414         struct utmpx ux, *uxrc;
415
416         getutmpx(u, &ux);
417
418 #if defined(HAVE_UX_UT_SYSLEN)
419         if (hostname)
420                 ux.ut_syslen = strlen(hostname) + 1;    /* include end NULL */
421         else
422                 ux.ut_syslen = 0;
423 #endif
424         utmp_strcpy(ux.ut_host, hostname, sizeof(ux.ut_host));
425
426         uw_pathname(uname, "utmpx", ux_pathname);
427         uw_pathname(wname, "wtmpx", wx_pathname);
428         DEBUG(2,("utmp_update: uname:%s wname:%s\n", uname, wname));
429         /*
430          * Check for either uname or wname being empty.
431          * Some systems, such as Redhat 6, have a "utmpx.h" which doesn't
432          * define default filenames.
433          * Also, our local installation has not provided an override.
434          * Drop to non-x method.  (E.g. RH6 has good defaults in "utmp.h".)
435          */
436         if ((strlen(uname) == 0) || (strlen(wname) == 0)) {
437                 utmp_nox_update(u, claim);
438         } else {
439                 utmpxname(uname);
440                 setutxent();
441                 uxrc = pututxline(&ux);
442                 endutxent();
443                 if (uxrc == NULL) {
444                         DEBUG(2,("utmp_update: pututxline() failed\n"));
445                         return;
446                 }
447                 updwtmpx(wname, &ux);
448         }
449 #endif /* HAVE_UTMPX_H */
450 }
451
452 #if defined(HAVE_UT_UT_ID)
453 /****************************************************************************
454  Encode the unique connection number into "ut_id".
455 ****************************************************************************/
456
457 static int ut_id_encode(int i, char *fourbyte)
458 {
459         int nbase;
460         char *ut_id_encstr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
461         
462         fourbyte[0] = 'S';
463         fourbyte[1] = 'M';
464
465 /*
466  * Encode remaining 2 bytes from 'i'.
467  * 'ut_id_encstr' is the character set on which modulo arithmetic is done.
468  * Example: digits would produce the base-10 numbers from '001'.
469  */
470         nbase = strlen(ut_id_encstr);
471
472         fourbyte[3] = ut_id_encstr[i % nbase];
473         i /= nbase;
474         fourbyte[2] = ut_id_encstr[i % nbase];
475         i /= nbase;
476
477         return(i);      /* 0: good; else overflow */
478 }
479 #endif /* defined(HAVE_UT_UT_ID) */
480
481
482 /*
483   fill a system utmp structure given all the info we can gather 
484 */
485 static BOOL sys_utmp_fill(struct utmp *u,
486                           const char *username, const char *hostname,
487                           const char *id_str, int id_num)
488 {                         
489         struct timeval timeval;
490
491         /*
492          * ut_name, ut_user:
493          *      Several (all?) systems seems to define one as the other.
494          *      It is easier and clearer simply to let the following take its course,
495          *      rather than to try to detect and optimise.
496          */
497 #if defined(HAVE_UT_UT_USER)
498         utmp_strcpy(u->ut_user, username, sizeof(u->ut_user));
499 #elif defined(HAVE_UT_UT_NAME)
500         utmp_strcpy(u->ut_name, username, sizeof(u->ut_name));
501 #endif
502
503         /*
504          * ut_line:
505          *      If size limit proves troublesome, then perhaps use "ut_id_encode()".
506          *
507          * Temporary variable "line_tmp" avoids trouble:
508          * o  with unwanted trailing NULL if ut_line full;
509          * o  with overflow if ut_line would be more than full.
510          */
511         if (strlen(id_str) > sizeof(u->ut_line)) {
512                 DEBUG(1,("id_str [%s] is too long for %d char utmp field\n",
513                          id_str, sizeof(u->ut_line)));
514                 return False;
515         }
516         utmp_strcpy(u->ut_line, id_str, sizeof(u->ut_line));
517
518 #if defined(HAVE_UT_UT_PID)
519         u->ut_pid = sys_getpid();
520 #endif
521
522 /*
523  * ut_time, ut_tv: 
524  *      Some have one, some the other.  Many have both, but defined (aliased).
525  *      It is easier and clearer simply to let the following take its course.
526  *      But note that we do the more precise ut_tv as the final assignment.
527  */
528 #if defined(HAVE_UT_UT_TIME)
529         gettimeofday(&timeval, NULL);
530         u->ut_time = timeval.tv_sec;
531 #elif defined(HAVE_UT_UT_TV)
532         gettimeofday(&timeval, NULL);
533         u->ut_tv = timeval;
534 #else
535 #error "with-utmp must have UT_TIME or UT_TV"
536 #endif
537
538 #if defined(HAVE_UT_UT_HOST)
539         utmp_strcpy(u->ut_host, hostname, sizeof(u->ut_host));
540 #endif
541
542 #if defined(HAVE_UT_UT_ADDR)
543         /*
544          * "(unsigned long) ut_addr" apparently exists on at least HP-UX 10.20.
545          * Volunteer to implement, please ...
546          */
547 #endif
548
549 #if defined(HAVE_UT_UT_ID)
550         if (ut_id_encode(id_num, u->ut_id) != 0) {
551                 DEBUG(1,("utmp_fill: cannot encode id %d\n", id_num));
552                 return False;
553         }
554 #endif
555
556         return True;
557 }
558
559 /****************************************************************************
560  Close a connection.
561 ****************************************************************************/
562
563 void sys_utmp_yield(const char *username, const char *hostname, 
564                     const char *id_str, int id_num)
565 {
566         struct utmp u;
567
568         ZERO_STRUCT(u);
569
570 #if defined(HAVE_UT_UT_EXIT)
571         u.ut_exit.e_termination = 0;
572         u.ut_exit.e_exit = 0;
573 #endif
574
575 #if defined(HAVE_UT_UT_TYPE)
576         u.ut_type = DEAD_PROCESS;
577 #endif
578
579         if (!sys_utmp_fill(&u, username, hostname, id_str, id_num)) return;
580
581         sys_utmp_update(&u, NULL, False);
582 }
583
584 /****************************************************************************
585  Claim a entry in whatever utmp system the OS uses.
586 ****************************************************************************/
587
588 void sys_utmp_claim(const char *username, const char *hostname, 
589                     const char *id_str, int id_num)
590 {
591         struct utmp u;
592
593         ZERO_STRUCT(u);
594
595 #if defined(HAVE_UT_UT_TYPE)
596         u.ut_type = USER_PROCESS;
597 #endif
598
599         if (!sys_utmp_fill(&u, username, hostname, id_str, id_num)) return;
600
601         sys_utmp_update(&u, hostname, True);
602 }
603
604 #else /* WITH_UTMP */
605  void dummy_utmp(void) {}
606 #endif