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