TODO destructor s3:smbXsrv_session: react on MSG_SMBXSRV_SESSION_CLOSE
[metze/samba/wip.git] / source3 / smbd / smbXsrv_session.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Stefan Metzmacher 2011-2012
5    Copyright (C) Michael Adam 2012
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 "system/filesys.h"
23 #include <tevent.h>
24 #include "smbd/smbd.h"
25 #include "smbd/globals.h"
26 #include "dbwrap/dbwrap.h"
27 #include "dbwrap/dbwrap_rbt.h"
28 #include "dbwrap/dbwrap_open.h"
29 #include "dbwrap/dbwrap_watch.h"
30 #include "session.h"
31 #include "auth.h"
32 #include "gensec.h"
33 #include "../lib/tsocket/tsocket.h"
34 #include "../libcli/security/security.h"
35 #include "messages.h"
36 #include "lib/util/util_tdb.h"
37 #include "librpc/gen_ndr/ndr_smbXsrv.h"
38 #include "serverid.h"
39 #include "lib/util/tevent_ntstatus.h"
40 #include "msg_channel.h"
41
42 struct smbXsrv_session_table {
43         struct {
44                 struct db_context *db_ctx;
45                 uint32_t lowest_id;
46                 uint32_t highest_id;
47                 uint32_t num_sessions;
48         } local;
49         struct {
50                 struct db_context *db_ctx;
51         } global;
52         struct msg_channel *close_channel;
53 };
54
55 static struct db_context *smbXsrv_session_global_db_ctx = NULL;
56
57 NTSTATUS smbXsrv_session_global_init(void)
58 {
59         const char *global_path = NULL;
60         struct db_context *db_ctx = NULL;
61
62         if (smbXsrv_session_global_db_ctx != NULL) {
63                 return NT_STATUS_OK;
64         }
65
66         /*
67          * This contains secret information like session keys!
68          */
69         global_path = lock_path("smbXsrv_session_global.tdb");
70
71         db_ctx = db_open(NULL, global_path,
72                          0, /* hash_size */
73                          TDB_DEFAULT |
74                          TDB_CLEAR_IF_FIRST |
75                          TDB_INCOMPATIBLE_HASH,
76                          O_RDWR | O_CREAT, 0600,
77                          DBWRAP_LOCK_ORDER_1);
78         if (db_ctx == NULL) {
79                 NTSTATUS status;
80
81                 status = map_nt_error_from_unix_common(errno);
82
83                 return status;
84         }
85
86         smbXsrv_session_global_db_ctx = db_ctx;
87
88         return NT_STATUS_OK;
89 }
90
91 /*
92  * NOTE:
93  * We need to store the keys in big endian so that dbwrap_rbt's memcmp
94  * has the same result as integer comparison between the uint32_t
95  * values.
96  *
97  * TODO: implement string based key
98  */
99
100 #define SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE sizeof(uint32_t)
101
102 static TDB_DATA smbXsrv_session_global_id_to_key(uint32_t id,
103                                                  uint8_t *key_buf)
104 {
105         TDB_DATA key;
106
107         RSIVAL(key_buf, 0, id);
108
109         key = make_tdb_data(key_buf, SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE);
110
111         return key;
112 }
113
114 static NTSTATUS smbXsrv_session_global_key_to_id(TDB_DATA key, uint32_t *id)
115 {
116         if (id == NULL) {
117                 return NT_STATUS_INVALID_PARAMETER;
118         }
119
120         if (key.dsize != SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE){
121                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
122         }
123
124         *id = RIVAL(key.dptr, 0);
125
126         return NT_STATUS_OK;
127 }
128
129 #define SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE sizeof(uint32_t)
130
131 static TDB_DATA smbXsrv_session_local_id_to_key(uint32_t id,
132                                                 uint8_t *key_buf)
133 {
134         TDB_DATA key;
135
136         RSIVAL(key_buf, 0, id);
137
138         key = make_tdb_data(key_buf, SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE);
139
140         return key;
141 }
142
143 static NTSTATUS smbXsrv_session_local_key_to_id(TDB_DATA key, uint32_t *id)
144 {
145         if (id == NULL) {
146                 return NT_STATUS_INVALID_PARAMETER;
147         }
148
149         if (key.dsize != SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE){
150                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
151         }
152
153         *id = RIVAL(key.dptr, 0);
154
155         return NT_STATUS_OK;
156 }
157
158 static void smbXsrv_session_close_loop(struct tevent_req *subreq);
159
160 static NTSTATUS smbXsrv_session_table_init(struct smbXsrv_connection *conn,
161                                            uint32_t lowest_id,
162                                            uint32_t highest_id)
163 {
164         struct smbXsrv_session_table *table;
165         NTSTATUS status;
166         struct tevent_req *subreq;
167         int ret;
168
169         table = talloc_zero(conn, struct smbXsrv_session_table);
170         if (table == NULL) {
171                 return NT_STATUS_NO_MEMORY;
172         }
173
174         table->local.db_ctx = db_open_rbt(conn);
175         if (table->local.db_ctx == NULL) {
176                 TALLOC_FREE(table);
177                 return NT_STATUS_NO_MEMORY;
178         }
179         table->local.lowest_id = lowest_id;
180         table->local.highest_id = highest_id;
181
182         status = smbXsrv_session_global_init();
183         if (!NT_STATUS_IS_OK(status)) {
184                 TALLOC_FREE(table);
185                 return status;
186         }
187
188         table->global.db_ctx = smbXsrv_session_global_db_ctx;
189
190         dbwrap_watch_db(table->global.db_ctx, conn->msg_ctx);
191
192         ret = msg_channel_init(table, conn->msg_ctx,
193                                MSG_SMBXSRV_SESSION_CLOSE,
194                                &table->close_channel);
195         if (ret != 0) {
196                 status = map_nt_error_from_unix_common(errno);
197                 TALLOC_FREE(table);
198                 return status;
199         }
200
201         subreq = msg_read_send(table, conn->ev_ctx, table->close_channel);
202         if (subreq == NULL) {
203                 TALLOC_FREE(table);
204                 return NT_STATUS_NO_MEMORY;
205         }
206         tevent_req_set_callback(subreq, smbXsrv_session_close_loop, conn);
207
208         conn->session_table = table;
209         return NT_STATUS_OK;
210 }
211
212 static void smbXsrv_session_close_loop(struct tevent_req *subreq)
213 {
214         struct smbXsrv_connection *conn =
215                 tevent_req_callback_data(subreq,
216                 struct smbXsrv_connection);
217         struct smbXsrv_session_table *table = conn->session_table;
218         int ret;
219         struct messaging_rec *rec = NULL;
220         struct smbXsrv_session_globalB global_blob;
221         enum ndr_err_code ndr_err;
222         struct smbXsrv_session_global0 *global = NULL;
223         struct smbXsrv_session *session = NULL;
224         NTSTATUS status;
225         struct timeval tv = timeval_current();
226         NTTIME now = timeval_to_nttime(&tv);
227         struct connection_struct *cur_conn, *next_conn;
228
229         ret = msg_read_recv(subreq, talloc_tos(), &rec);
230         TALLOC_FREE(subreq);
231         if (ret != 0) {
232                 goto next;
233         }
234
235         ndr_err = ndr_pull_struct_blob_all(&rec->buf, rec, &global_blob,
236                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_session_globalB);
237         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
238                 goto next;
239         }
240
241         DEBUG(0,("smbXsrv_session_close_loop: MSG_SMBXSRV_SESSION_CLOSE\n"));
242         NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
243
244         if (global_blob.version != SMBXSRV_VERSION_0) {
245                 goto next;
246         }
247
248         global = global_blob.info.info0;
249
250         status = smb2srv_session_lookup(conn, global->session_wire_id,
251                                         now, &session);
252         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_SESSION_DELETED)) {
253                 goto next;
254         }
255         if (!NT_STATUS_IS_OK(status) &&
256             !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) &&
257             !NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED)) {
258                 goto next;
259         }
260
261         /*
262          * TODO: cancel all outstanding requests on the session
263          */
264         file_close_user(conn->sconn, session->compat->vuid);
265
266         for (cur_conn=conn->sconn->connections; cur_conn; cur_conn=next_conn) {
267                 struct smbXsrv_tcon *tcon;
268
269                 next_conn = cur_conn->next;
270                 tcon = cur_conn->tcon;
271
272                 if (cur_conn->vuid != session->compat->vuid) {
273                         continue;
274                 }
275
276                 set_current_service(cur_conn, 0, True);
277                 close_cnum(cur_conn, cur_conn->vuid);
278
279                 TALLOC_FREE(tcon);
280         }
281
282         invalidate_vuid(conn->sconn, session->compat->vuid);
283         session->compat = NULL;
284
285         session->status = NT_STATUS_USER_SESSION_DELETED;
286         talloc_steal(rec, session);
287
288 next:
289         TALLOC_FREE(rec);
290
291         subreq = msg_read_send(table, conn->ev_ctx, table->close_channel);
292         if (subreq == NULL) {
293                 // TODO disconnect
294                 return;
295         }
296         tevent_req_set_callback(subreq, smbXsrv_session_close_loop, conn);
297 }
298
299 struct smb1srv_session_local_allocate_state {
300         const uint32_t lowest_id;
301         const uint32_t highest_id;
302         uint32_t last_id;
303         uint32_t useable_id;
304         NTSTATUS status;
305 };
306
307 static int smb1srv_session_local_allocate_traverse(struct db_record *rec,
308                                                    void *private_data)
309 {
310         struct smb1srv_session_local_allocate_state *state =
311                 (struct smb1srv_session_local_allocate_state *)private_data;
312         TDB_DATA key = dbwrap_record_get_key(rec);
313         uint32_t id = 0;
314         NTSTATUS status;
315
316         status = smbXsrv_session_local_key_to_id(key, &id);
317         if (!NT_STATUS_IS_OK(status)) {
318                 state->status = status;
319                 return -1;
320         }
321
322         if (id <= state->last_id) {
323                 state->status = NT_STATUS_INTERNAL_DB_CORRUPTION;
324                 return -1;
325         }
326         state->last_id = id;
327
328         if (id > state->useable_id) {
329                 state->status = NT_STATUS_OK;
330                 return -1;
331         }
332
333         state->useable_id +=1;
334         return 0;
335 }
336
337 static NTSTATUS smb1srv_session_local_allocate_id(struct db_context *db,
338                                                   uint32_t lowest_id,
339                                                   uint32_t highest_id,
340                                                   TALLOC_CTX *mem_ctx,
341                                                   struct db_record **_rec,
342                                                   uint32_t *_id)
343 {
344         struct smb1srv_session_local_allocate_state state = {
345                 .lowest_id = lowest_id,
346                 .highest_id = highest_id,
347                 .last_id = 0,
348                 .useable_id = lowest_id,
349                 .status = NT_STATUS_INTERNAL_ERROR,
350         };
351         uint32_t i;
352         uint32_t range;
353         NTSTATUS status;
354         int count = 0;
355
356         *_rec = NULL;
357         *_id = 0;
358
359         if (lowest_id > highest_id) {
360                 return NT_STATUS_INSUFFICIENT_RESOURCES;
361         }
362
363         range = (highest_id - lowest_id) + 1;
364
365         for (i = 0; i < range; i++) {
366                 uint32_t id;
367                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
368                 TDB_DATA key;
369                 TDB_DATA val;
370                 struct db_record *rec = NULL;
371
372                 id = generate_random() % range;
373                 id += lowest_id;
374
375                 if (id < lowest_id) {
376                         id = lowest_id;
377                 }
378                 if (id > highest_id) {
379                         id = highest_id;
380                 }
381
382                 key = smbXsrv_session_local_id_to_key(id, key_buf);
383
384                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
385                 if (rec == NULL) {
386                         return NT_STATUS_INSUFFICIENT_RESOURCES;
387                 }
388
389                 val = dbwrap_record_get_value(rec);
390                 if (val.dsize != 0) {
391                         TALLOC_FREE(rec);
392                         continue;
393                 }
394
395                 *_rec = rec;
396                 *_id = id;
397                 return NT_STATUS_OK;
398         }
399
400         status = dbwrap_traverse_read(db, smb1srv_session_local_allocate_traverse,
401                                       &state, &count);
402         if (!NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_DB_CORRUPTION)) {
403                 /*
404                  * Here we really expect NT_STATUS_INTERNAL_DB_CORRUPTION!
405                  *
406                  * If we get anything else it is an error, because it
407                  * means we did not manage to find a free slot in
408                  * the db.
409                  */
410                 return NT_STATUS_INSUFFICIENT_RESOURCES;
411         }
412
413         if (NT_STATUS_IS_OK(state.status)) {
414                 uint32_t id;
415                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
416                 TDB_DATA key;
417                 TDB_DATA val;
418                 struct db_record *rec = NULL;
419
420                 id = state.useable_id;
421
422                 key = smbXsrv_session_local_id_to_key(id, key_buf);
423
424                 rec = dbwrap_fetch_locked(db, mem_ctx, key);
425                 if (rec == NULL) {
426                         return NT_STATUS_INSUFFICIENT_RESOURCES;
427                 }
428
429                 val = dbwrap_record_get_value(rec);
430                 if (val.dsize != 0) {
431                         TALLOC_FREE(rec);
432                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
433                 }
434
435                 *_rec = rec;
436                 *_id = id;
437                 return NT_STATUS_OK;
438         }
439
440         return state.status;
441 }
442
443 struct smbXsrv_session_local_fetch_state {
444         struct smbXsrv_session *session;
445         NTSTATUS status;
446 };
447
448 static void smbXsrv_session_local_fetch_parser(TDB_DATA key, TDB_DATA data,
449                                                void *private_data)
450 {
451         struct smbXsrv_session_local_fetch_state *state =
452                 (struct smbXsrv_session_local_fetch_state *)private_data;
453         void *ptr;
454
455         if (data.dsize != sizeof(ptr)) {
456                 state->status = NT_STATUS_INTERNAL_DB_ERROR;
457                 return;
458         }
459
460         memcpy(&ptr, data.dptr, data.dsize);
461         state->session = talloc_get_type_abort(ptr, struct smbXsrv_session);
462         state->status = NT_STATUS_OK;
463 }
464
465 static NTSTATUS smbXsrv_session_local_lookup(struct smbXsrv_session_table *table,
466                                              uint32_t session_local_id,
467                                              NTTIME now,
468                                              struct smbXsrv_session **_session)
469 {
470         struct smbXsrv_session_local_fetch_state state = {
471                 .session = NULL,
472                 .status = NT_STATUS_INTERNAL_ERROR,
473         };
474         uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
475         TDB_DATA key;
476         NTSTATUS status;
477
478         *_session = NULL;
479
480         if (session_local_id == 0) {
481                 return NT_STATUS_USER_SESSION_DELETED;
482         }
483
484         if (table == NULL) {
485                 /* this might happen before the end of negprot */
486                 return NT_STATUS_USER_SESSION_DELETED;
487         }
488
489         if (table->local.db_ctx == NULL) {
490                 return NT_STATUS_INTERNAL_ERROR;
491         }
492
493         key = smbXsrv_session_local_id_to_key(session_local_id, key_buf);
494
495         status = dbwrap_parse_record(table->local.db_ctx, key,
496                                      smbXsrv_session_local_fetch_parser,
497                                      &state);
498         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
499                 return NT_STATUS_USER_SESSION_DELETED;
500         } else if (!NT_STATUS_IS_OK(status)) {
501                 return status;
502         }
503         if (!NT_STATUS_IS_OK(state.status)) {
504                 return state.status;
505         }
506
507         state.session->idle_time = now;
508
509         if (!NT_STATUS_IS_OK(state.session->status)) {
510                 *_session = state.session;
511                 return state.session->status;
512         }
513
514         if (now > state.session->global->expiration_time) {
515                 state.session->status = NT_STATUS_NETWORK_SESSION_EXPIRED;
516         }
517
518         *_session = state.session;
519         return state.session->status;
520 }
521
522 static int smbXsrv_session_global_destructor(struct smbXsrv_session_global0 *global)
523 {
524         return 0;
525 }
526
527 static void smbXsrv_session_global_verify_record(struct db_record *db_rec,
528                                         bool *is_free,
529                                         bool *was_free,
530                                         TALLOC_CTX *mem_ctx,
531                                         struct smbXsrv_session_global0 **_g);
532
533 static NTSTATUS smbXsrv_session_global_allocate(struct db_context *db,
534                                         TALLOC_CTX *mem_ctx,
535                                         struct smbXsrv_session_global0 **_global)
536 {
537         uint32_t i;
538         struct smbXsrv_session_global0 *global = NULL;
539         uint32_t last_free = 0;
540         const uint32_t min_tries = 3;
541
542         *_global = NULL;
543
544         global = talloc_zero(mem_ctx, struct smbXsrv_session_global0);
545         if (global == NULL) {
546                 return NT_STATUS_NO_MEMORY;
547         }
548         talloc_set_destructor(global, smbXsrv_session_global_destructor);
549
550         for (i = 0; i < UINT32_MAX; i++) {
551                 bool is_free = false;
552                 bool was_free = false;
553                 uint32_t id;
554                 uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
555                 TDB_DATA key;
556
557                 if (i >= min_tries && last_free != 0) {
558                         id = last_free;
559                 } else {
560                         id = generate_random();
561                 }
562                 if (id >= UINT16_MAX) {
563                         /*
564                          * For now we truncate to 16bit,
565                          * as that's what all callers
566                          * expect (uint16_t vuid).
567                          */
568                         id = id & UINT16_MAX;
569                 }
570                 if (id == 0) {
571                         id++;
572                 }
573                 if (id == UINT32_MAX) {
574                         id--;
575                 }
576
577                 key = smbXsrv_session_global_id_to_key(id, key_buf);
578
579                 global->db_rec = dbwrap_fetch_locked(db, mem_ctx, key);
580                 if (global->db_rec == NULL) {
581                         talloc_free(global);
582                         return NT_STATUS_INSUFFICIENT_RESOURCES;
583                 }
584
585                 smbXsrv_session_global_verify_record(global->db_rec,
586                                                      &is_free,
587                                                      &was_free,
588                                                      NULL, NULL);
589
590                 if (!is_free) {
591                         TALLOC_FREE(global->db_rec);
592                         continue;
593                 }
594
595                 if (!was_free && i < min_tries) {
596                         /*
597                          * The session_id is free now,
598                          * but was not free before.
599                          *
600                          * This happens if a smbd crashed
601                          * and did not cleanup the record.
602                          *
603                          * If this is one of our first tries,
604                          * then we try to find a real free one.
605                          */
606                         if (last_free == 0) {
607                                 last_free = id;
608                         }
609                         TALLOC_FREE(global->db_rec);
610                         continue;
611                 }
612                 global->session_global_id = id;
613
614                 *_global = global;
615                 return NT_STATUS_OK;
616         }
617
618         /* should not be reached */
619         talloc_free(global);
620         return NT_STATUS_INTERNAL_ERROR;
621 }
622
623 static void smbXsrv_session_global_verify_record(struct db_record *db_rec,
624                                         bool *is_free,
625                                         bool *was_free,
626                                         TALLOC_CTX *mem_ctx,
627                                         struct smbXsrv_session_global0 **_g)
628 {
629         TDB_DATA key;
630         TDB_DATA val;
631         DATA_BLOB blob;
632         struct smbXsrv_session_globalB global_blob;
633         enum ndr_err_code ndr_err;
634         struct smbXsrv_session_global0 *global = NULL;
635         bool exists;
636         TALLOC_CTX *frame = talloc_stackframe();
637
638         *is_free = false;
639
640         if (was_free) {
641                 *was_free = false;
642         }
643         if (_g) {
644                 *_g = NULL;
645         }
646
647         key = dbwrap_record_get_key(db_rec);
648
649         val = dbwrap_record_get_value(db_rec);
650         if (val.dsize == 0) {
651                 TALLOC_FREE(frame);
652                 *is_free = true;
653                 if (was_free) {
654                         *was_free = true;
655                 }
656                 return;
657         }
658
659         blob = data_blob_const(val.dptr, val.dsize);
660
661         ndr_err = ndr_pull_struct_blob(&blob, frame, &global_blob,
662                         (ndr_pull_flags_fn_t)ndr_pull_smbXsrv_session_globalB);
663         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
664                 DEBUG(1,("smbXsrv_session_global_verify_record: "
665                          "key '%s' use unsupported version %u\n",
666                          hex_encode_talloc(frame, key.dptr, key.dsize),
667                          global_blob.version));
668                 TALLOC_FREE(frame);
669                 return;
670         }
671
672         DEBUG(10,("smbXsrv_session_global_verify_record\n"));
673         if (DEBUGLVL(10)) {
674                 NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
675         }
676
677         if (global_blob.version != SMBXSRV_VERSION_0) {
678                 DEBUG(0,("smbXsrv_session_global_verify_record: "
679                          "key '%s' use unsupported version %u\n",
680                          hex_encode_talloc(frame, key.dptr, key.dsize),
681                          global_blob.version));
682                 NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
683                 TALLOC_FREE(frame);
684                 return;
685         }
686
687         global = global_blob.info.info0;
688
689         exists = serverid_exists(&global->channels[0].server_id);
690         if (!exists) {
691                 DEBUG(2,("smbXsrv_session_global_verify_record: "
692                          "key '%s' server_id %s does not exist.\n",
693                          hex_encode_talloc(frame, key.dptr, key.dsize),
694                          server_id_str(frame, &global->channels[0].server_id)));
695                 if (DEBUGLVL(2)) {
696                         NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
697                 }
698                 TALLOC_FREE(frame);
699                 dbwrap_record_delete(db_rec);
700                 *is_free = true;
701                 return;
702         }
703
704         if (_g) {
705                 *_g = talloc_move(mem_ctx, &global);
706         }
707         TALLOC_FREE(frame);
708 }
709
710 static NTSTATUS smbXsrv_session_global_store(struct smbXsrv_connection *sconn,
711                                              struct smbXsrv_session_global0 *global)
712 {
713         struct smbXsrv_session_globalB global_blob;
714         DATA_BLOB blob = data_blob_null;
715         TDB_DATA key;
716         TDB_DATA val;
717         NTSTATUS status;
718         enum ndr_err_code ndr_err;
719
720         /*
721          * TODO: if we use other versions than '0'
722          * we would add glue code here, that would be able to
723          * store the information in the old format.
724          */
725
726         if (global->db_rec == NULL) {
727                 return NT_STATUS_INTERNAL_ERROR;
728         }
729
730         key = dbwrap_record_get_key(global->db_rec);
731         val = dbwrap_record_get_value(global->db_rec);
732
733         ZERO_STRUCT(global_blob);
734         global_blob.version = smbXsrv_version_global_current();
735         if (val.dsize >= 8) {
736                 global_blob.seqnum = IVAL(val.dptr, 4);
737         }
738         global_blob.seqnum += 1;
739         global_blob.info.info0 = global;
740
741         ndr_err = ndr_push_struct_blob(&blob, global->db_rec, &global_blob,
742                         (ndr_push_flags_fn_t)ndr_push_smbXsrv_session_globalB);
743         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
744                 status = ndr_map_error2ntstatus(ndr_err);
745                 DEBUG(1,("smbXsrv_session_global_store: key '%s' ndr_push - %s\n",
746                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
747                          nt_errstr(status)));
748                 TALLOC_FREE(global->db_rec);
749                 return status;
750         }
751
752         val = make_tdb_data(blob.data, blob.length);
753         status = dbwrap_record_store(global->db_rec, val, TDB_REPLACE);
754         if (!NT_STATUS_IS_OK(status)) {
755                 DEBUG(1,("smbXsrv_session_global_store: key '%s' store - %s\n",
756                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize),
757                          nt_errstr(status)));
758                 TALLOC_FREE(global->db_rec);
759                 return status;
760         }
761
762         if (DEBUGLVL(10)) {
763                 DEBUG(10,("smbXsrv_session_global_store: key '%s' stored\n",
764                          hex_encode_talloc(global->db_rec, key.dptr, key.dsize)));
765                 NDR_PRINT_DEBUG(smbXsrv_session_globalB, &global_blob);
766         }
767
768         TALLOC_FREE(global->db_rec);
769
770         return NT_STATUS_OK;
771 }
772
773 struct smb2srv_session_close_previous_state {
774         struct tevent_context *ev;
775         struct smbXsrv_session *current_session;
776         struct dom_sid *current_sid;
777         struct db_record *db_rec;
778 };
779
780 static void smb2srv_session_close_previous_check(struct tevent_req *req);
781 static void smb2srv_session_close_previous_modified(struct tevent_req *subreq);
782
783 struct tevent_req *smb2srv_session_close_previous_send(TALLOC_CTX *mem_ctx,
784                                         struct tevent_context *ev,
785                                         struct smbXsrv_session *current_session,
786                                         uint64_t previous_session_id)
787 {
788         struct tevent_req *req;
789         struct smb2srv_session_close_previous_state *state;
790         uint32_t global_id = previous_session_id & UINT32_MAX;
791         uint64_t global_zeros = previous_session_id & 0xFFFFFFFF00000000LLU;
792         struct smbXsrv_connection *conn = current_session->connection;
793         struct smbXsrv_session_table *table = conn->session_table;
794         struct security_token *current_token = NULL;
795         uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
796         TDB_DATA key;
797
798         req = tevent_req_create(mem_ctx, &state,
799                                 struct smb2srv_session_close_previous_state);
800         if (req == NULL) {
801                 return NULL;
802         }
803         state->ev = ev;
804         state->current_session = current_session;
805
806         if (global_zeros != 0) {
807                 tevent_req_done(req);
808                 return tevent_req_post(req, ev);
809         }
810
811         if (current_session->global->auth_session_info == NULL) {
812                 tevent_req_done(req);
813                 return tevent_req_post(req, ev);
814         }
815         current_token = current_session->global->auth_session_info->security_token;
816
817         if (current_token->num_sids > PRIMARY_USER_SID_INDEX) {
818                 state->current_sid = &current_token->sids[PRIMARY_USER_SID_INDEX];
819         }
820
821         if (state->current_sid == NULL) {
822                 tevent_req_done(req);
823                 return tevent_req_post(req, ev);
824         }
825
826         if (!security_token_has_nt_authenticated_users(current_token)) {
827                 /* TODO */
828                 tevent_req_done(req);
829                 return tevent_req_post(req, ev);
830         }
831
832         key = smbXsrv_session_global_id_to_key(global_id, key_buf);
833
834         state->db_rec = dbwrap_fetch_locked(table->global.db_ctx,
835                                      state, key);
836         if (state->db_rec == NULL) {
837                 tevent_req_nterror(req, NT_STATUS_UNSUCCESSFUL);
838                 return tevent_req_post(req, ev);
839         }
840
841         smb2srv_session_close_previous_check(req);
842         if (!tevent_req_is_in_progress(req)) {
843                 return tevent_req_post(req, ev);
844         }
845
846         return req;
847 }
848
849 static void smb2srv_session_close_previous_check(struct tevent_req *req)
850 {
851         struct smb2srv_session_close_previous_state *state =
852                 tevent_req_data(req,
853                 struct smb2srv_session_close_previous_state);
854         struct smbXsrv_connection *conn = state->current_session->connection;
855         TDB_DATA val;
856         DATA_BLOB blob;
857         struct security_token *previous_token = NULL;
858         struct smbXsrv_session_global0 *global = NULL;
859         struct tevent_req *subreq = NULL;
860         NTSTATUS status;
861         bool is_free = false;
862
863         smbXsrv_session_global_verify_record(state->db_rec,
864                                              &is_free,
865                                              NULL,
866                                              state,
867                                              &global);
868
869         if (is_free) {
870                 TALLOC_FREE(state->db_rec);
871                 tevent_req_done(req);
872                 return;
873         }
874
875         if (global->auth_session_info == NULL) {
876                 TALLOC_FREE(state->db_rec);
877                 tevent_req_done(req);
878                 return;
879         }
880
881         previous_token = global->auth_session_info->security_token;
882
883         if (!security_token_is_sid(previous_token, state->current_sid)) {
884                 TALLOC_FREE(state->db_rec);
885                 tevent_req_done(req);
886                 return;
887         }
888
889         subreq = dbwrap_record_watch_send(state, state->ev,
890                                           state->db_rec, conn->msg_ctx);
891         if (tevent_req_nomem(subreq, req)) {
892                 TALLOC_FREE(state->db_rec);
893                 return;
894         }
895         tevent_req_set_callback(subreq,
896                                 smb2srv_session_close_previous_modified,
897                                 req);
898
899         val = dbwrap_record_get_value(state->db_rec);
900         blob = data_blob_const(val.dptr, val.dsize);
901
902         status = messaging_send(conn->msg_ctx,
903                                 global->channels[0].server_id,
904                                 MSG_SMBXSRV_SESSION_CLOSE, &blob);
905         TALLOC_FREE(state->db_rec);
906         if (tevent_req_nterror(req, status)) {
907                 return;
908         }
909
910         TALLOC_FREE(global);
911         return;
912 }
913
914 static void smb2srv_session_close_previous_modified(struct tevent_req *subreq)
915 {
916         struct tevent_req *req =
917                 tevent_req_callback_data(subreq,
918                 struct tevent_req);
919         struct smb2srv_session_close_previous_state *state =
920                 tevent_req_data(req,
921                 struct smb2srv_session_close_previous_state);
922         NTSTATUS status;
923
924         status = dbwrap_record_watch_recv(subreq, state, &state->db_rec);
925         TALLOC_FREE(subreq);
926         if (tevent_req_nterror(req, status)) {
927                 return;
928         }
929
930         smb2srv_session_close_previous_check(req);
931 }
932
933 NTSTATUS smb2srv_session_close_previous_recv(struct tevent_req *req)
934 {
935         NTSTATUS status;
936
937         if (tevent_req_is_nterror(req, &status)) {
938                 tevent_req_received(req);
939                 return status;
940         }
941
942         tevent_req_received(req);
943         return NT_STATUS_OK;
944 }
945
946 static int smbXsrv_session_destructor(struct smbXsrv_session *session)
947 {
948         struct smbXsrv_session_table *table;
949         struct db_record *local_rec = NULL;
950         struct db_record *global_rec = NULL;
951         NTSTATUS status;
952
953         if (session->table == NULL) {
954                 return 0;
955         }
956
957         table = session->table;
958         session->table = NULL;
959
960         session->connection = NULL;
961
962         local_rec = session->db_rec;
963         session->db_rec = NULL;
964         if (local_rec == NULL) {
965                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
966                 TDB_DATA key;
967
968                 key = smbXsrv_session_local_id_to_key(session->local_id,
969                                                       key_buf);
970
971                 local_rec = dbwrap_fetch_locked(table->local.db_ctx,
972                                                 session, key);
973         }
974
975         if (local_rec != NULL) {
976                 status = dbwrap_record_delete(local_rec);
977         }
978
979         global_rec = session->global->db_rec;
980         session->global->db_rec = NULL;
981         if (global_rec == NULL) {
982                 uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
983                 TDB_DATA key;
984
985                 key = smbXsrv_session_global_id_to_key(
986                                         session->global->session_global_id,
987                                         key_buf);
988
989                 global_rec = dbwrap_fetch_locked(table->global.db_ctx,
990                                                  session->global, key);
991         }
992
993         if (global_rec != NULL) {
994                 status = dbwrap_record_delete(global_rec);
995         }
996         TALLOC_FREE(session->global);
997
998         return 0;
999 }
1000
1001 NTSTATUS smbXsrv_session_create(struct smbXsrv_connection *conn,
1002                                 NTTIME now,
1003                                 struct smbXsrv_session **_session)
1004 {
1005         struct smbXsrv_session_table *table = conn->session_table;
1006         uint32_t max_sessions = table->local.highest_id - table->local.lowest_id;
1007         struct db_record *local_rec = NULL;
1008         struct smbXsrv_session *session = NULL;
1009         void *ptr = NULL;
1010         TDB_DATA val;
1011         struct smbXsrv_session_global0 *global = NULL;
1012         struct smbXsrv_channel_global0 *channels = NULL;
1013         NTSTATUS status;
1014
1015         if (table->local.num_sessions >= max_sessions) {
1016                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1017         }
1018
1019         session = talloc_zero(conn, struct smbXsrv_session);
1020         if (session == NULL) {
1021                 return NT_STATUS_NO_MEMORY;
1022         }
1023         session->table = table;
1024         session->idle_time = now;
1025         session->status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1026         session->connection = conn;
1027
1028         status = smbXsrv_session_global_allocate(table->global.db_ctx,
1029                                                  session,
1030                                                  &global);
1031         if (!NT_STATUS_IS_OK(status)) {
1032                 talloc_free(session);
1033                 return status;
1034         }
1035         session->global = global;
1036
1037         talloc_set_destructor(session, smbXsrv_session_destructor);
1038
1039         if (conn->protocol >= PROTOCOL_SMB2_02) {
1040                 uint16_t dialect = SMB2_DIALECT_REVISION_2FF;
1041                 uint64_t id = global->session_global_id;
1042                 uint8_t key_buf[SMBXSRV_SESSION_LOCAL_TDB_KEY_SIZE];
1043                 TDB_DATA key;
1044
1045                 status = smb2srv_tcon_table_init(session);
1046                 if (!NT_STATUS_IS_OK(status)) {
1047                         talloc_free(session);
1048                         return status;
1049                 }
1050
1051                 global->session_wire_id = id;
1052
1053                 switch (conn->protocol) {
1054                 case PROTOCOL_SMB2_02:
1055                         dialect = SMB2_DIALECT_REVISION_202;
1056                         break;
1057                 case PROTOCOL_SMB2_10:
1058                         dialect = SMB2_DIALECT_REVISION_210;
1059                         break;
1060                 case PROTOCOL_SMB2_22:
1061                         dialect = SMB2_DIALECT_REVISION_222;
1062                         break;
1063                 case PROTOCOL_SMB2_24:
1064                         dialect = SMB2_DIALECT_REVISION_224;
1065                         break;
1066                 case PROTOCOL_SMB3_00:
1067                         dialect = SMB3_DIALECT_REVISION_300;
1068                         break;
1069                 default:
1070                         talloc_free(session);
1071                         return NT_STATUS_INTERNAL_ERROR;
1072                 }
1073                 global->connection_dialect = dialect;
1074
1075                 session->local_id = global->session_global_id;
1076
1077                 key = smbXsrv_session_local_id_to_key(session->local_id, key_buf);
1078
1079                 local_rec = dbwrap_fetch_locked(table->local.db_ctx,
1080                                                 session, key);
1081                 if (local_rec == NULL) {
1082                         return NT_STATUS_NO_MEMORY;
1083                 }
1084
1085                 val = dbwrap_record_get_value(local_rec);
1086                 if (val.dsize != 0) {
1087                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1088                 }
1089         } else {
1090
1091                 status = smb1srv_session_local_allocate_id(table->local.db_ctx,
1092                                                         table->local.lowest_id,
1093                                                         table->local.highest_id,
1094                                                         session,
1095                                                         &local_rec,
1096                                                         &session->local_id);
1097                 if (!NT_STATUS_IS_OK(status)) {
1098                         return status;
1099                 }
1100
1101                 global->session_wire_id = session->local_id;
1102         }
1103
1104         ptr = session;
1105         val = make_tdb_data((uint8_t const *)&ptr, sizeof(ptr));
1106         status = dbwrap_record_store(local_rec, val, TDB_REPLACE);
1107         TALLOC_FREE(local_rec);
1108         if (!NT_STATUS_IS_OK(status)) {
1109                 talloc_free(session);
1110                 return status;
1111         }
1112
1113         global->creation_time = now;
1114         global->expiration_time = GENSEC_EXPIRE_TIME_INFINITY;
1115
1116         global->num_channels = 1;
1117         channels = talloc_zero_array(global,
1118                                      struct smbXsrv_channel_global0,
1119                                      global->num_channels);
1120         if (channels == NULL) {
1121                 talloc_free(session);
1122                 return NT_STATUS_NO_MEMORY;
1123         }
1124         global->channels = channels;
1125
1126         channels[0].server_id = messaging_server_id(conn->msg_ctx);
1127         channels[0].local_address = tsocket_address_string(conn->local_address,
1128                                                            channels);
1129         if (channels[0].local_address == NULL) {
1130                 talloc_free(session);
1131                 return NT_STATUS_NO_MEMORY;
1132         }
1133         channels[0].remote_address = tsocket_address_string(conn->remote_address,
1134                                                             channels);
1135         if (channels[0].remote_address == NULL) {
1136                 talloc_free(session);
1137                 return NT_STATUS_NO_MEMORY;
1138         }
1139         channels[0].remote_name = talloc_strdup(channels, conn->remote_hostname);
1140         if (channels[0].remote_name == NULL) {
1141                 talloc_free(session);
1142                 return NT_STATUS_NO_MEMORY;
1143         }
1144         channels[0].signing_key = data_blob_null;
1145
1146         status = smbXsrv_session_global_store(conn,
1147                                               global);
1148         if (!NT_STATUS_IS_OK(status)) {
1149                 DEBUG(0,("smbXsrv_session_create: "
1150                          "global_id 0x%08X store failed - %s\n",
1151                          session->global->session_global_id,
1152                          nt_errstr(status)));
1153                 talloc_free(session);
1154                 return status;
1155         }
1156
1157         if (DEBUGLVL(10)) {
1158                 struct smbXsrv_sessionB session_blob;
1159
1160                 ZERO_STRUCT(session_blob);
1161                 session_blob.version = SMBXSRV_VERSION_0;
1162                 session_blob.info.info0 = session;
1163
1164                 DEBUG(10,("smbXsrv_session_create: global_id (0x%08X) stored\n",
1165                          session->global->session_global_id));
1166                 NDR_PRINT_DEBUG(smbXsrv_sessionB, &session_blob);
1167         }
1168
1169         *_session = session;
1170         return NT_STATUS_OK;
1171 }
1172
1173 NTSTATUS smbXsrv_session_update(struct smbXsrv_session *session)
1174 {
1175         struct smbXsrv_session_table *table = session->table;
1176         NTSTATUS status;
1177         uint8_t key_buf[SMBXSRV_SESSION_GLOBAL_TDB_KEY_SIZE];
1178         TDB_DATA key;
1179
1180         if (session->global->db_rec != NULL) {
1181                 return NT_STATUS_INTERNAL_ERROR;
1182         }
1183
1184         key = smbXsrv_session_global_id_to_key(
1185                                         session->global->session_global_id,
1186                                         key_buf);
1187
1188         session->global->db_rec = dbwrap_fetch_locked(table->global.db_ctx,
1189                                                       session->global, key);
1190         if (session->global->db_rec == NULL) {
1191                 return NT_STATUS_INTERNAL_DB_ERROR;
1192         }
1193
1194         status = smbXsrv_session_global_store(session->connection,
1195                                               session->global);
1196         if (!NT_STATUS_IS_OK(status)) {
1197                 DEBUG(0,("smbXsrv_session_update: "
1198                          "global_id 0x%08X store failed - %s\n",
1199                          session->global->session_global_id,
1200                          nt_errstr(status)));
1201                 return status;
1202         }
1203
1204         if (DEBUGLVL(10)) {
1205                 struct smbXsrv_sessionB session_blob;
1206
1207                 ZERO_STRUCT(session_blob);
1208                 session_blob.version = SMBXSRV_VERSION_0;
1209                 session_blob.info.info0 = session;
1210
1211                 DEBUG(10,("smbXsrv_session_update: global_id 0x%08X stored\n",
1212                           session->global->session_global_id));
1213                 NDR_PRINT_DEBUG(smbXsrv_sessionB, &session_blob);
1214         }
1215
1216         return NT_STATUS_OK;
1217 }
1218
1219 NTSTATUS smb1srv_session_table_init(struct smbXsrv_connection *conn)
1220 {
1221         /*
1222          * Allow a range from 100..65534.
1223          */
1224         return smbXsrv_session_table_init(conn, 100, UINT16_MAX - 1);
1225 }
1226
1227 NTSTATUS smb1srv_session_lookup(struct smbXsrv_connection *conn,
1228                                 uint16_t vuid, NTTIME now,
1229                                 struct smbXsrv_session **session)
1230 {
1231         struct smbXsrv_session_table *table = conn->session_table;
1232         uint32_t local_id = vuid;
1233
1234         return smbXsrv_session_local_lookup(table, local_id, now, session);
1235 }
1236
1237 NTSTATUS smb2srv_session_table_init(struct smbXsrv_connection *conn)
1238 {
1239         /*
1240          * For now use the same range as SMB1.
1241          *
1242          * Allow a range from 100..65534.
1243          */
1244         return smbXsrv_session_table_init(conn, 100, UINT16_MAX - 1);
1245 }
1246
1247 NTSTATUS smb2srv_session_lookup(struct smbXsrv_connection *conn,
1248                                 uint64_t session_id, NTTIME now,
1249                                 struct smbXsrv_session **session)
1250 {
1251         struct smbXsrv_session_table *table = conn->session_table;
1252         uint32_t local_id = session_id & UINT32_MAX;
1253         uint64_t local_zeros = session_id & 0xFFFFFFFF00000000LLU;
1254
1255         if (local_zeros != 0) {
1256                 return NT_STATUS_USER_SESSION_DELETED;
1257         }
1258
1259         return smbXsrv_session_local_lookup(table, local_id, now, session);
1260 }