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