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