This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[tprouty/samba.git] / source / 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.  This must be unique within and across all
85         smbd processes.  It is the 'id_num' from Samba's session.c code.
86
87         The 4 byte 'ut_id' component is vital to distinguish connections,
88         of which there could be several hundred 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 bytes encode the session 'id_num' (see above).
109         Our caller (session.c) should note our 16-bit limitation.
110
111 ****************************************************************************/
112
113 #include <utmp.h>
114
115 #ifdef HAVE_UTMPX_H
116 #include <utmpx.h>
117 #endif
118
119 /* BSD systems: some may need lastlog.h (SunOS 4), some may not (FreeBSD) */
120 /* Some System-V systems (e.g. Solaris 2) declare this too. */
121 #ifdef HAVE_LASTLOG_H
122 #include <lastlog.h>
123 #endif
124
125 /****************************************************************************
126  Default paths to various {u,w}tmp{,x} files.
127 ****************************************************************************/
128
129 #ifdef  HAVE_UTMPX_H
130
131 static const char *ux_pathname =
132 # if defined (UTMPX_FILE)
133         UTMPX_FILE ;
134 # elif defined (_UTMPX_FILE)
135         _UTMPX_FILE ;
136 # elif defined (_PATH_UTMPX)
137         _PATH_UTMPX ;
138 # else
139         "" ;
140 # endif
141
142 static const char *wx_pathname =
143 # if defined (WTMPX_FILE)
144         WTMPX_FILE ;
145 # elif defined (_WTMPX_FILE)
146         _WTMPX_FILE ;
147 # elif defined (_PATH_WTMPX)
148         _PATH_WTMPX ;
149 # else
150         "" ;
151 # endif
152
153 #endif  /* HAVE_UTMPX_H */
154
155 static const char *ut_pathname =
156 # if defined (UTMP_FILE)
157         UTMP_FILE ;
158 # elif defined (_UTMP_FILE)
159         _UTMP_FILE ;
160 # elif defined (_PATH_UTMP)
161         _PATH_UTMP ;
162 # else
163         "" ;
164 # endif
165
166 static const char *wt_pathname =
167 # if defined (WTMP_FILE)
168         WTMP_FILE ;
169 # elif defined (_WTMP_FILE)
170         _WTMP_FILE ;
171 # elif defined (_PATH_WTMP)
172         _PATH_WTMP ;
173 # else
174         "" ;
175 # endif
176
177 /* BSD-like systems might want "lastlog" support. */
178 /* *** Not yet implemented */
179 #ifndef HAVE_PUTUTLINE          /* see "pututline_my()" */
180 static const char *ll_pathname =
181 # if defined (_PATH_LASTLOG)    /* what other names (if any?) */
182         _PATH_LASTLOG ;
183 # else
184         "" ;
185 # endif /* _PATH_LASTLOG */
186 #endif  /* HAVE_PUTUTLINE */
187
188 /*
189  * Get name of {u,w}tmp{,x} file.
190  *      return: fname contains filename
191  *              Possibly empty if this code not yet ported to this system.
192  *
193  * utmp{,x}:  try "utmp dir", then default (a define)
194  * wtmp{,x}:  try "wtmp dir", then "utmp dir", then default (a define)
195  */
196 static void uw_pathname(pstring fname, const char *uw_name, const char *uw_default)
197 {
198         pstring dirname;
199
200         pstrcpy(dirname, "");
201
202         /* For w-files, first look for explicit "wtmp dir" */
203         if (uw_name[0] == 'w') {
204                 pstrcpy(dirname,lp_wtmpdir());
205                 trim_string(dirname,"","/");
206         }
207
208         /* For u-files and non-explicit w-dir, look for "utmp dir" */
209         if (dirname == 0 || strlen(dirname) == 0) {
210                 pstrcpy(dirname,lp_utmpdir());
211                 trim_string(dirname,"","/");
212         }
213
214         /* If explicit directory above, use it */
215         if (dirname != 0 && strlen(dirname) != 0) {
216                 pstrcpy(fname, dirname);
217                 pstrcat(fname, "/");
218                 pstrcat(fname, uw_name);
219                 return;
220         }
221
222         /* No explicit directory: attempt to use default paths */
223         if (strlen(uw_default) == 0) {
224                 /* No explicit setting, no known default.
225                  * Has it yet been ported to this OS?
226                  */
227                 DEBUG(2,("uw_pathname: unable to determine pathname\n"));
228         }
229         pstrcpy(fname, uw_default);
230 }
231
232 #ifndef HAVE_PUTUTLINE
233
234 /****************************************************************************
235  Update utmp file directly.  No subroutine interface: probably a BSD system.
236 ****************************************************************************/
237
238 static void pututline_my(pstring uname, struct utmp *u, BOOL claim)
239 {
240         DEBUG(1,("pututline_my: not yet implemented\n"));
241         /* BSD implementor: may want to consider (or not) adjusting "lastlog" */
242 }
243 #endif /* HAVE_PUTUTLINE */
244
245 #ifndef HAVE_UPDWTMP
246
247 /****************************************************************************
248  Update wtmp file directly.  No subroutine interface: probably a BSD system.
249  Credit: Michail Vidiassov <master@iaas.msu.ru>
250 ****************************************************************************/
251
252 static void updwtmp_my(pstring wname, struct utmp *u, BOOL claim)
253 {
254         int fd;
255         struct stat buf;
256
257         if (! claim) {
258                 /*
259                  * BSD-like systems:
260                  *      may use empty ut_name to distinguish a logout record.
261                  *
262                  * May need "if defined(SUNOS4)" etc. around some of these,
263                  * but try to avoid if possible.
264                  *
265                  * SunOS 4:
266                  *      man page indicates ut_name and ut_host both NULL
267                  * FreeBSD 4.0:
268                  *      man page appears not to specify (hints non-NULL)
269                  *      A correspondent suggest at least ut_name should be NULL
270                  */
271                 memset((char *)&u->ut_name, '\0', sizeof(u->ut_name));
272                 memset((char *)&u->ut_host, '\0', sizeof(u->ut_host));
273         }
274         /* Stolen from logwtmp function in libutil.
275          * May be more locking/blocking is needed?
276          */
277         if ((fd = open(wname, O_WRONLY|O_APPEND, 0)) < 0)
278                 return;
279         if (fstat(fd, &buf) == 0) {
280                 if (write(fd, (char *)u, sizeof(struct utmp)) != sizeof(struct utmp))
281                 (void) ftruncate(fd, buf.st_size);
282         }
283         (void) close(fd);
284 }
285 #endif /* HAVE_UPDWTMP */
286
287 /****************************************************************************
288  Update via utmp/wtmp (not utmpx/wtmpx).
289 ****************************************************************************/
290
291 static void utmp_nox_update(struct utmp *u, BOOL claim)
292 {
293         pstring uname, wname;
294 #if defined(PUTUTLINE_RETURNS_UTMP)
295         struct utmp *urc;
296 #endif /* PUTUTLINE_RETURNS_UTMP */
297
298         uw_pathname(uname, "utmp", ut_pathname);
299         DEBUG(2,("utmp_nox_update: uname:%s\n", uname));
300
301 #ifdef HAVE_PUTUTLINE
302         if (strlen(uname) != 0) {
303                 utmpname(uname);
304         }
305
306 # if defined(PUTUTLINE_RETURNS_UTMP)
307         setutent();
308         urc = pututline(u);
309         endutent();
310         if (urc == NULL) {
311                 DEBUG(2,("utmp_nox_update: pututline() failed\n"));
312                 return;
313         }
314 # else  /* PUTUTLINE_RETURNS_UTMP */
315         setutent();
316         pututline(u);
317         endutent();
318 # endif /* PUTUTLINE_RETURNS_UTMP */
319
320 #else   /* HAVE_PUTUTLINE */
321         if (strlen(uname) != 0) {
322                 pututline_my(uname, u, claim);
323         }
324 #endif /* HAVE_PUTUTLINE */
325
326         uw_pathname(wname, "wtmp", wt_pathname);
327         DEBUG(2,("utmp_nox_update: wname:%s\n", wname));
328         if (strlen(wname) != 0) {
329 #ifdef HAVE_UPDWTMP
330                 updwtmp(wname, u);
331                 /*
332                  * updwtmp() and the newer updwtmpx() may be unsymmetrical.
333                  * At least one OS, Solaris 2.x declares the former in the
334                  * "utmpx" (latter) file and context.
335                  * In the Solaris case this is irrelevant: it has both and
336                  * we always prefer the "x" case, so doesn't come here.
337                  * But are there other systems, with no "x", which lack
338                  * updwtmp() perhaps?
339                  */
340 #else
341                 updwtmp_my(wname, u, claim);
342 #endif /* HAVE_UPDWTMP */
343         }
344 }
345
346 /****************************************************************************
347  Copy a string in the utmp structure.
348 ****************************************************************************/
349
350 static void utmp_strcpy(char *dest, const char *src, size_t n)
351 {
352         size_t len = 0;
353
354         memset(dest, '\0', n);
355         if (src)
356                 len = strlen(src);
357         if (len >= n) {
358                 memcpy(dest, src, n);
359         } else {
360                 if (len)
361                         memcpy(dest, src, len);
362         }
363 }
364
365 /****************************************************************************
366  Update via utmpx/wtmpx (preferred) or via utmp/wtmp.
367 ****************************************************************************/
368
369 static void sys_utmp_update(struct utmp *u, const char *hostname, BOOL claim)
370 {
371 #if !defined(HAVE_UTMPX_H)
372         /* No utmpx stuff.  Drop to non-x stuff */
373         utmp_nox_update(u, claim);
374 #elif !defined(HAVE_PUTUTXLINE)
375         /* Odd.  Have utmpx.h but no "pututxline()".  Drop to non-x stuff */
376         DEBUG(1,("utmp_update: have utmpx.h but no pututxline() function\n"));
377         utmp_nox_update(u, claim);
378 #elif !defined(HAVE_GETUTMPX)
379         /* Odd.  Have utmpx.h but no "getutmpx()".  Drop to non-x stuff */
380         DEBUG(1,("utmp_update: have utmpx.h but no getutmpx() function\n"));
381         utmp_nox_update(u, claim);
382 #else
383         pstring uname, wname;
384         struct utmpx ux, *uxrc;
385
386         getutmpx(u, &ux);
387
388 #if defined(HAVE_UX_UT_SYSLEN)
389         if (hostname)
390                 ux.ut_syslen = strlen(hostname) + 1;    /* include end NULL */
391         else
392                 ux.ut_syslen = 0;
393 #endif
394         utmp_strcpy(ux.ut_host, hostname, sizeof(ux.ut_host));
395
396         uw_pathname(uname, "utmpx", ux_pathname);
397         uw_pathname(wname, "wtmpx", wx_pathname);
398         DEBUG(2,("utmp_update: uname:%s wname:%s\n", uname, wname));
399         /*
400          * Check for either uname or wname being empty.
401          * Some systems, such as Redhat 6, have a "utmpx.h" which doesn't
402          * define default filenames.
403          * Also, our local installation has not provided an override.
404          * Drop to non-x method.  (E.g. RH6 has good defaults in "utmp.h".)
405          */
406         if ((strlen(uname) == 0) || (strlen(wname) == 0)) {
407                 utmp_nox_update(u, claim);
408         } else {
409                 utmpxname(uname);
410                 setutxent();
411                 uxrc = pututxline(&ux);
412                 endutxent();
413                 if (uxrc == NULL) {
414                         DEBUG(2,("utmp_update: pututxline() failed\n"));
415                         return;
416                 }
417                 updwtmpx(wname, &ux);
418         }
419 #endif /* HAVE_UTMPX_H */
420 }
421
422 #if defined(HAVE_UT_UT_ID)
423 /****************************************************************************
424  Encode the unique connection number into "ut_id".
425 ****************************************************************************/
426
427 static int ut_id_encode(int i, char *fourbyte)
428 {
429         int nbase;
430         const char *ut_id_encstr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
431         
432         fourbyte[0] = 'S';
433         fourbyte[1] = 'M';
434
435 /*
436  * Encode remaining 2 bytes from 'i'.
437  * 'ut_id_encstr' is the character set on which modulo arithmetic is done.
438  * Example: digits would produce the base-10 numbers from '001'.
439  */
440         nbase = strlen(ut_id_encstr);
441
442         fourbyte[3] = ut_id_encstr[i % nbase];
443         i /= nbase;
444         fourbyte[2] = ut_id_encstr[i % nbase];
445         i /= nbase;
446
447         return(i);      /* 0: good; else overflow */
448 }
449 #endif /* defined(HAVE_UT_UT_ID) */
450
451
452 /*
453   fill a system utmp structure given all the info we can gather 
454 */
455 static BOOL sys_utmp_fill(struct utmp *u,
456                           const char *username, const char *hostname,
457                           struct in_addr *ipaddr,
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         utmp_strcpy(u->ut_user, username, sizeof(u->ut_user));
470 #elif defined(HAVE_UT_UT_NAME)
471         utmp_strcpy(u->ut_name, username, sizeof(u->ut_name));
472 #endif
473
474         /*
475          * ut_line:
476          *      If size limit proves troublesome, then perhaps use "ut_id_encode()".
477          */
478         if (strlen(id_str) > sizeof(u->ut_line)) {
479                 DEBUG(1,("id_str [%s] is too long for %d char utmp field\n",
480                          id_str, sizeof(u->ut_line)));
481                 return False;
482         }
483         utmp_strcpy(u->ut_line, id_str, sizeof(u->ut_line));
484
485 #if defined(HAVE_UT_UT_PID)
486         u->ut_pid = sys_getpid();
487 #endif
488
489 /*
490  * ut_time, ut_tv: 
491  *      Some have one, some the other.  Many have both, but defined (aliased).
492  *      It is easier and clearer simply to let the following take its course.
493  *      But note that we do the more precise ut_tv as the final assignment.
494  */
495 #if defined(HAVE_UT_UT_TIME)
496         gettimeofday(&timeval, NULL);
497         u->ut_time = timeval.tv_sec;
498 #elif defined(HAVE_UT_UT_TV)
499         gettimeofday(&timeval, NULL);
500         u->ut_tv = timeval;
501 #else
502 #error "with-utmp must have UT_TIME or UT_TV"
503 #endif
504
505 #if defined(HAVE_UT_UT_HOST)
506         utmp_strcpy(u->ut_host, hostname, sizeof(u->ut_host));
507 #endif
508 #if defined(HAVE_UT_UT_ADDR)
509         if (ipaddr)
510                 u->ut_addr = ipaddr->s_addr;
511         /*
512          * "(unsigned long) ut_addr" apparently exists on at least HP-UX 10.20.
513          * Volunteer to implement, please ...
514          */
515 #endif
516
517 #if defined(HAVE_UT_UT_ID)
518         if (ut_id_encode(id_num, u->ut_id) != 0) {
519                 DEBUG(1,("utmp_fill: cannot encode id %d\n", id_num));
520                 return False;
521         }
522 #endif
523
524         return True;
525 }
526
527 /****************************************************************************
528  Close a connection.
529 ****************************************************************************/
530
531 void sys_utmp_yield(const char *username, const char *hostname, 
532                     struct in_addr *ipaddr,
533                     const char *id_str, int id_num)
534 {
535         struct utmp u;
536
537         ZERO_STRUCT(u);
538
539 #if defined(HAVE_UT_UT_EXIT)
540         u.ut_exit.e_termination = 0;
541         u.ut_exit.e_exit = 0;
542 #endif
543
544 #if defined(HAVE_UT_UT_TYPE)
545         u.ut_type = DEAD_PROCESS;
546 #endif
547
548         if (!sys_utmp_fill(&u, username, hostname, ipaddr, id_str, id_num)) return;
549
550         sys_utmp_update(&u, NULL, False);
551 }
552
553 /****************************************************************************
554  Claim a entry in whatever utmp system the OS uses.
555 ****************************************************************************/
556
557 void sys_utmp_claim(const char *username, const char *hostname, 
558                     struct in_addr *ipaddr,
559                     const char *id_str, int id_num)
560 {
561         struct utmp u;
562
563         ZERO_STRUCT(u);
564
565 #if defined(HAVE_UT_UT_TYPE)
566         u.ut_type = USER_PROCESS;
567 #endif
568
569         if (!sys_utmp_fill(&u, username, hostname, ipaddr, id_str, id_num)) return;
570
571         sys_utmp_update(&u, hostname, True);
572 }
573
574 #else /* WITH_UTMP */
575  void dummy_utmp(void) {}
576 #endif