r23779: Change from v2 or later to v3 or later.
[samba.git] / source3 / smbd / session.c
1 /* 
2    Unix SMB/CIFS implementation.
3    session handling for utmp and PAM
4
5    Copyright (C) tridge@samba.org       2001
6    Copyright (C) abartlet@samba.org     2001
7    Copyright (C) Gerald (Jerry) Carter  2006   
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 /* a "session" is claimed when we do a SessionSetupX operation
25    and is yielded when the corresponding vuid is destroyed.
26
27    sessions are used to populate utmp and PAM session structures
28 */
29
30 #include "includes.h"
31
32 /********************************************************************
33 ********************************************************************/
34
35 static struct db_context *session_db_ctx(void)
36 {
37         static struct db_context *ctx;
38
39         if (ctx)
40                 return ctx;
41
42         ctx = db_open(NULL, lock_path("sessionid.tdb"), 0,
43                       TDB_CLEAR_IF_FIRST|TDB_DEFAULT, 
44                       O_RDWR | O_CREAT, 0644);
45         return ctx;
46 }
47
48 BOOL session_init(void)
49 {
50         if (session_db_ctx() == NULL) {
51                 DEBUG(1,("session_init: failed to open sessionid tdb\n"));
52                 return False;
53         }
54
55         return True;
56 }
57
58 /********************************************************************
59  called when a session is created
60 ********************************************************************/
61
62 BOOL session_claim(user_struct *vuser)
63 {
64         TDB_DATA key, data;
65         int i = 0;
66         struct sockaddr sa;
67         struct in_addr *client_ip;
68         struct sessionid sessionid;
69         struct server_id pid = procid_self();
70         fstring keystr;
71         char * hostname;
72         struct db_context *ctx;
73         struct db_record *rec;
74         NTSTATUS status;
75
76         vuser->session_keystr = NULL;
77
78         /* don't register sessions for the guest user - its just too
79            expensive to go through pam session code for browsing etc */
80         if (vuser->guest) {
81                 return True;
82         }
83
84         if (!(ctx = session_db_ctx())) {
85                 return False;
86         }
87
88         ZERO_STRUCT(sessionid);
89
90         data.dptr = NULL;
91         data.dsize = 0;
92
93         if (lp_utmp()) {
94
95                 for (i=1;i<MAX_SESSION_ID;i++) {
96
97                         /*
98                          * This is very inefficient and needs fixing -- vl
99                          */
100
101                         struct server_id sess_pid;
102
103                         snprintf(keystr, sizeof(keystr), "ID/%d", i);
104                         key = string_term_tdb_data(keystr);
105
106                         rec = ctx->fetch_locked(ctx, NULL, key);
107
108                         if (rec == NULL) {
109                                 DEBUG(1, ("Could not lock \"%s\"\n", keystr));
110                                 return False;
111                         }
112
113                         if (rec->value.dsize != sizeof(sessionid)) {
114                                 DEBUG(1, ("Re-using invalid record\n"));
115                                 break;
116                         }
117
118                         sess_pid = ((struct sessionid *)rec->value.dptr)->pid;
119
120                         if (!process_exists(sess_pid)) {
121                                 DEBUG(5, ("%s has died -- re-using session\n",
122                                           procid_str_static(&sess_pid)));
123                                 break;
124                         }
125
126                         TALLOC_FREE(rec);
127                 }
128                 
129                 if (i == MAX_SESSION_ID) {
130                         SMB_ASSERT(rec == NULL);
131                         DEBUG(1,("session_claim: out of session IDs "
132                                  "(max is %d)\n", MAX_SESSION_ID));
133                         return False;
134                 }
135
136                 snprintf(sessionid.id_str, sizeof(sessionid.id_str),
137                          SESSION_UTMP_TEMPLATE, i);
138         } else
139         {
140                 snprintf(keystr, sizeof(keystr), "ID/%s/%u",
141                          procid_str_static(&pid), vuser->vuid);
142                 key = string_term_tdb_data(keystr);
143
144                 rec = ctx->fetch_locked(ctx, NULL, key);
145
146                 if (rec == NULL) {
147                         DEBUG(1, ("Could not lock \"%s\"\n", keystr));
148                         return False;
149                 }
150
151                 snprintf(sessionid.id_str, sizeof(sessionid.id_str), 
152                          SESSION_TEMPLATE, (long unsigned int)sys_getpid(), 
153                          vuser->vuid);
154         }
155
156         SMB_ASSERT(rec != NULL);
157
158         /* If 'hostname lookup' == yes, then do the DNS lookup.  This is
159            needed because utmp and PAM both expect DNS names 
160            
161            client_name() handles this case internally.
162         */
163
164         hostname = client_name();
165         if (strcmp(hostname, "UNKNOWN") == 0) {
166                 hostname = client_addr();
167         }
168
169         fstrcpy(sessionid.username, vuser->user.unix_name);
170         fstrcpy(sessionid.hostname, hostname);
171         sessionid.id_num = i;  /* Only valid for utmp sessions */
172         sessionid.pid = pid;
173         sessionid.uid = vuser->uid;
174         sessionid.gid = vuser->gid;
175         fstrcpy(sessionid.remote_machine, get_remote_machine_name());
176         fstrcpy(sessionid.ip_addr, client_addr());
177         sessionid.connect_start = time(NULL);
178
179         client_ip = client_inaddr(&sa);
180
181         if (!smb_pam_claim_session(sessionid.username, sessionid.id_str,
182                                    sessionid.hostname)) {
183                 DEBUG(1,("pam_session rejected the session for %s [%s]\n",
184                                 sessionid.username, sessionid.id_str));
185
186                 TALLOC_FREE(rec);
187                 return False;
188         }
189
190         data.dptr = (uint8 *)&sessionid;
191         data.dsize = sizeof(sessionid);
192
193         status = rec->store(rec, data, TDB_REPLACE);
194
195         TALLOC_FREE(rec);
196
197         if (!NT_STATUS_IS_OK(status)) {
198                 DEBUG(1,("session_claim: unable to create session id "
199                          "record: %s\n", nt_errstr(status)));
200                 return False;
201         }
202
203         if (lp_utmp()) {
204                 sys_utmp_claim(sessionid.username, sessionid.hostname, 
205                                client_ip,
206                                sessionid.id_str, sessionid.id_num);
207         }
208
209         TALLOC_FREE(rec);
210
211         vuser->session_keystr = talloc_strdup(vuser, keystr);
212         if (!vuser->session_keystr) {
213                 DEBUG(0, ("session_claim:  talloc_strdup() failed for "
214                           "session_keystr\n"));
215                 return False;
216         }
217         return True;
218 }
219
220 /********************************************************************
221  called when a session is destroyed
222 ********************************************************************/
223
224 void session_yield(user_struct *vuser)
225 {
226         TDB_DATA key;
227         struct sessionid sessionid;
228         struct in_addr *client_ip;
229         struct db_context *ctx;
230         struct db_record *rec;
231
232         if (!(ctx = session_db_ctx())) return;
233
234         if (!vuser->session_keystr) {
235                 return;
236         }
237
238         key = string_term_tdb_data(vuser->session_keystr);
239
240         if (!(rec = ctx->fetch_locked(ctx, NULL, key))) {
241                 return;
242         }
243
244         if (rec->value.dsize != sizeof(sessionid))
245                 return;
246
247         memcpy(&sessionid, rec->value.dptr, sizeof(sessionid));
248
249         client_ip = interpret_addr2(sessionid.ip_addr);
250
251         if (lp_utmp()) {
252                 sys_utmp_yield(sessionid.username, sessionid.hostname, 
253                                client_ip,
254                                sessionid.id_str, sessionid.id_num);
255         }
256
257         smb_pam_close_session(sessionid.username, sessionid.id_str,
258                               sessionid.hostname);
259
260         rec->delete_rec(rec);
261
262         TALLOC_FREE(rec);
263 }
264
265 /********************************************************************
266 ********************************************************************/
267
268 static BOOL session_traverse(int (*fn)(struct db_record *db,
269                                        void *private_data),
270                              void *private_data)
271 {
272         struct db_context *ctx;
273
274         if (!(ctx = session_db_ctx())) {
275                 DEBUG(3, ("No tdb opened\n"));
276                 return False;
277         }
278
279         ctx->traverse_read(ctx, fn, private_data);
280         return True;
281 }
282
283 /********************************************************************
284 ********************************************************************/
285
286 struct session_list {
287         TALLOC_CTX *mem_ctx;
288         int count;
289         struct sessionid *sessions;
290 };
291
292 static int gather_sessioninfo(struct db_record *rec, void *state)
293 {
294         struct session_list *sesslist = (struct session_list *) state;
295         const struct sessionid *current =
296                 (const struct sessionid *) rec->value.dptr;
297
298         sesslist->sessions = TALLOC_REALLOC_ARRAY(
299                 sesslist->mem_ctx, sesslist->sessions, struct sessionid,
300                 sesslist->count+1);
301
302         if (!sesslist->sessions) {
303                 sesslist->count = 0;
304                 return -1;
305         }
306
307         memcpy(&sesslist->sessions[sesslist->count], current,
308                sizeof(struct sessionid));
309
310         sesslist->count++;
311
312         DEBUG(7,("gather_sessioninfo session from %s@%s\n", 
313                  current->username, current->remote_machine));
314
315         return 0;
316 }
317
318 /********************************************************************
319 ********************************************************************/
320
321 int list_sessions(TALLOC_CTX *mem_ctx, struct sessionid **session_list)
322 {
323         struct session_list sesslist;
324
325         sesslist.mem_ctx = mem_ctx;
326         sesslist.count = 0;
327         sesslist.sessions = NULL;
328         
329         if (!session_traverse(gather_sessioninfo, (void *) &sesslist)) {
330                 DEBUG(3, ("Session traverse failed\n"));
331                 SAFE_FREE(sesslist.sessions);
332                 *session_list = NULL;
333                 return 0;
334         }
335
336         *session_list = sesslist.sessions;
337         return sesslist.count;
338 }