fe5838225d9f690529ac6b61a6ad3c09df39c096
[metze/samba/wip.git] / source3 / smbd / service.c
1 /* 
2    Unix SMB/CIFS implementation.
3    service (connection) opening and closing
4    Copyright (C) Andrew Tridgell 1992-1998
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "system/filesys.h"
22 #include "system/passwd.h" /* uid_wrapper */
23 #include "../lib/tsocket/tsocket.h"
24 #include "smbd/smbd.h"
25 #include "smbd/globals.h"
26 #include "../librpc/gen_ndr/netlogon.h"
27 #include "../libcli/security/security.h"
28 #include "printing/pcap.h"
29 #include "passdb/lookup_sid.h"
30 #include "auth.h"
31 #include "lib/param/loadparm.h"
32 #include "messages.h"
33
34 static bool canonicalize_connect_path(connection_struct *conn)
35 {
36         bool ret;
37         char *resolved_name = SMB_VFS_REALPATH(conn,conn->connectpath);
38         if (!resolved_name) {
39                 return false;
40         }
41         ret = set_conn_connectpath(conn,resolved_name);
42         SAFE_FREE(resolved_name);
43         return ret;
44 }
45
46 /****************************************************************************
47  Ensure when setting connectpath it is a canonicalized (no ./ // or ../)
48  absolute path stating in / and not ending in /.
49  Observent people will notice a similarity between this and check_path_syntax :-).
50 ****************************************************************************/
51
52 bool set_conn_connectpath(connection_struct *conn, const char *connectpath)
53 {
54         char *destname;
55         char *d;
56         const char *s = connectpath;
57         bool start_of_name_component = true;
58
59         if (connectpath == NULL || connectpath[0] == '\0') {
60                 return false;
61         }
62
63         /* Allocate for strlen + '\0' + possible leading '/' */
64         destname = (char *)SMB_MALLOC(strlen(connectpath) + 2);
65         if (!destname) {
66                 return false;
67         }
68         d = destname;
69
70         *d++ = '/'; /* Always start with root. */
71
72         while (*s) {
73                 if (*s == '/') {
74                         /* Eat multiple '/' */
75                         while (*s == '/') {
76                                 s++;
77                         }
78                         if ((d > destname + 1) && (*s != '\0')) {
79                                 *d++ = '/';
80                         }
81                         start_of_name_component = True;
82                         continue;
83                 }
84
85                 if (start_of_name_component) {
86                         if ((s[0] == '.') && (s[1] == '.') && (s[2] == '/' || s[2] == '\0')) {
87                                 /* Uh oh - "/../" or "/..\0" ! */
88
89                                 /* Go past the ../ or .. */
90                                 if (s[2] == '/') {
91                                         s += 3;
92                                 } else {
93                                         s += 2; /* Go past the .. */
94                                 }
95
96                                 /* If  we just added a '/' - delete it */
97                                 if ((d > destname) && (*(d-1) == '/')) {
98                                         *(d-1) = '\0';
99                                         d--;
100                                 }
101
102                                 /* Are we at the start ? Can't go back further if so. */
103                                 if (d <= destname) {
104                                         *d++ = '/'; /* Can't delete root */
105                                         continue;
106                                 }
107                                 /* Go back one level... */
108                                 /* Decrement d first as d points to the *next* char to write into. */
109                                 for (d--; d > destname; d--) {
110                                         if (*d == '/') {
111                                                 break;
112                                         }
113                                 }
114                                 /* We're still at the start of a name component, just the previous one. */
115                                 continue;
116                         } else if ((s[0] == '.') && ((s[1] == '\0') || s[1] == '/')) {
117                                 /* Component of pathname can't be "." only - skip the '.' . */
118                                 if (s[1] == '/') {
119                                         s += 2;
120                                 } else {
121                                         s++;
122                                 }
123                                 continue;
124                         }
125                 }
126
127                 if (!(*s & 0x80)) {
128                         *d++ = *s++;
129                 } else {
130                         size_t siz;
131                         /* Get the size of the next MB character. */
132                         next_codepoint(s,&siz);
133                         switch(siz) {
134                                 case 5:
135                                         *d++ = *s++;
136                                         /*fall through*/
137                                 case 4:
138                                         *d++ = *s++;
139                                         /*fall through*/
140                                 case 3:
141                                         *d++ = *s++;
142                                         /*fall through*/
143                                 case 2:
144                                         *d++ = *s++;
145                                         /*fall through*/
146                                 case 1:
147                                         *d++ = *s++;
148                                         break;
149                                 default:
150                                         break;
151                         }
152                 }
153                 start_of_name_component = false;
154         }
155         *d = '\0';
156
157         /* And must not end in '/' */
158         if (d > destname + 1 && (*(d-1) == '/')) {
159                 *(d-1) = '\0';
160         }
161
162         DEBUG(10,("set_conn_connectpath: service %s, connectpath = %s\n",
163                 lp_servicename(SNUM(conn)), destname ));
164
165         string_set(&conn->connectpath, destname);
166         SAFE_FREE(destname);
167         return true;
168 }
169
170 /****************************************************************************
171  Load parameters specific to a connection/service.
172 ****************************************************************************/
173
174 bool set_current_service(connection_struct *conn, uint16 flags, bool do_chdir)
175 {
176         int snum;
177
178         if (!conn)  {
179                 last_conn = NULL;
180                 return(False);
181         }
182
183         conn->lastused_count++;
184
185         snum = SNUM(conn);
186
187         if (do_chdir &&
188             vfs_ChDir(conn,conn->connectpath) != 0 &&
189             vfs_ChDir(conn,conn->origpath) != 0) {
190                 DEBUG(((errno!=EACCES)?0:3),("chdir (%s) failed, reason: %s\n",
191                          conn->connectpath, strerror(errno)));
192                 return(False);
193         }
194
195         if ((conn == last_conn) && (last_flags == flags)) {
196                 return(True);
197         }
198
199         last_conn = conn;
200         last_flags = flags;
201
202         /* Obey the client case sensitivity requests - only for clients that support it. */
203         switch (lp_casesensitive(snum)) {
204                 case Auto:
205                         {
206                                 /* We need this uglyness due to DOS/Win9x clients that lie about case insensitivity. */
207                                 enum remote_arch_types ra_type = get_remote_arch();
208                                 if ((ra_type != RA_SAMBA) && (ra_type != RA_CIFSFS)) {
209                                         /* Client can't support per-packet case sensitive pathnames. */
210                                         conn->case_sensitive = False;
211                                 } else {
212                                         conn->case_sensitive = !(flags & FLAG_CASELESS_PATHNAMES);
213                                 }
214                         }
215                         break;
216                 case True:
217                         conn->case_sensitive = True;
218                         break;
219                 default:
220                         conn->case_sensitive = False;
221                         break;
222         }
223         return(True);
224 }
225
226 /****************************************************************************
227  do some basic sainity checks on the share.  
228  This function modifies dev, ecode.
229 ****************************************************************************/
230
231 static NTSTATUS share_sanity_checks(const struct tsocket_address *remote_address,
232                                     const char *rhost,
233                                     int snum,
234                                     fstring dev)
235 {
236         char *raddr;
237
238         raddr = tsocket_address_inet_addr_string(remote_address,
239                                                  talloc_tos());
240         if (raddr == NULL) {
241                 return NT_STATUS_NO_MEMORY;
242         }
243
244         if (!lp_snum_ok(snum) ||
245             !allow_access(lp_hostsdeny(snum), lp_hostsallow(snum),
246                           rhost, raddr)) {
247                 return NT_STATUS_ACCESS_DENIED;
248         }
249
250         if (dev[0] == '?' || !dev[0]) {
251                 if (lp_print_ok(snum)) {
252                         fstrcpy(dev,"LPT1:");
253                 } else if (strequal(lp_fstype(snum), "IPC")) {
254                         fstrcpy(dev, "IPC");
255                 } else {
256                         fstrcpy(dev,"A:");
257                 }
258         }
259
260         strupper_m(dev);
261
262         if (lp_print_ok(snum)) {
263                 if (!strequal(dev, "LPT1:")) {
264                         return NT_STATUS_BAD_DEVICE_TYPE;
265                 }
266         } else if (strequal(lp_fstype(snum), "IPC")) {
267                 if (!strequal(dev, "IPC")) {
268                         return NT_STATUS_BAD_DEVICE_TYPE;
269                 }
270         } else if (!strequal(dev, "A:")) {
271                 return NT_STATUS_BAD_DEVICE_TYPE;
272         }
273
274         /* Behave as a printer if we are supposed to */
275         if (lp_print_ok(snum) && (strcmp(dev, "A:") == 0)) {
276                 fstrcpy(dev, "LPT1:");
277         }
278
279         return NT_STATUS_OK;
280 }
281
282 /*
283  * Go through lookup_name etc to find the force'd group.  
284  *
285  * Create a new token from src_token, replacing the primary group sid with the
286  * one found.
287  */
288
289 static NTSTATUS find_forced_group(bool force_user,
290                                   int snum, const char *username,
291                                   struct dom_sid *pgroup_sid,
292                                   gid_t *pgid)
293 {
294         NTSTATUS result = NT_STATUS_NO_SUCH_GROUP;
295         TALLOC_CTX *frame = talloc_stackframe();
296         struct dom_sid group_sid;
297         enum lsa_SidType type;
298         char *groupname;
299         bool user_must_be_member = False;
300         gid_t gid;
301
302         groupname = talloc_strdup(talloc_tos(), lp_force_group(snum));
303         if (groupname == NULL) {
304                 DEBUG(1, ("talloc_strdup failed\n"));
305                 result = NT_STATUS_NO_MEMORY;
306                 goto done;
307         }
308
309         if (groupname[0] == '+') {
310                 user_must_be_member = True;
311                 groupname += 1;
312         }
313
314         groupname = talloc_string_sub(talloc_tos(), groupname,
315                                       "%S", lp_servicename(snum));
316         if (groupname == NULL) {
317                 DEBUG(1, ("talloc_string_sub failed\n"));
318                 result = NT_STATUS_NO_MEMORY;
319                 goto done;
320         }
321
322         if (!lookup_name_smbconf(talloc_tos(), groupname,
323                          LOOKUP_NAME_ALL|LOOKUP_NAME_GROUP,
324                          NULL, NULL, &group_sid, &type)) {
325                 DEBUG(10, ("lookup_name_smbconf(%s) failed\n",
326                            groupname));
327                 goto done;
328         }
329
330         if ((type != SID_NAME_DOM_GRP) && (type != SID_NAME_ALIAS) &&
331             (type != SID_NAME_WKN_GRP)) {
332                 DEBUG(10, ("%s is a %s, not a group\n", groupname,
333                            sid_type_lookup(type)));
334                 goto done;
335         }
336
337         if (!sid_to_gid(&group_sid, &gid)) {
338                 DEBUG(10, ("sid_to_gid(%s) for %s failed\n",
339                            sid_string_dbg(&group_sid), groupname));
340                 goto done;
341         }
342
343         /*
344          * If the user has been forced and the forced group starts with a '+',
345          * then we only set the group to be the forced group if the forced
346          * user is a member of that group.  Otherwise, the meaning of the '+'
347          * would be ignored.
348          */
349
350         if (force_user && user_must_be_member) {
351                 if (user_in_group_sid(username, &group_sid)) {
352                         sid_copy(pgroup_sid, &group_sid);
353                         *pgid = gid;
354                         DEBUG(3,("Forced group %s for member %s\n",
355                                  groupname, username));
356                 } else {
357                         DEBUG(0,("find_forced_group: forced user %s is not a member "
358                                 "of forced group %s. Disallowing access.\n",
359                                 username, groupname ));
360                         result = NT_STATUS_MEMBER_NOT_IN_GROUP;
361                         goto done;
362                 }
363         } else {
364                 sid_copy(pgroup_sid, &group_sid);
365                 *pgid = gid;
366                 DEBUG(3,("Forced group %s\n", groupname));
367         }
368
369         result = NT_STATUS_OK;
370  done:
371         TALLOC_FREE(frame);
372         return result;
373 }
374
375 /****************************************************************************
376   Create an auth_session_info structure for a connection_struct
377 ****************************************************************************/
378
379 static NTSTATUS create_connection_session_info(struct smbd_server_connection *sconn,
380                                               TALLOC_CTX *mem_ctx, int snum,
381                                               struct auth_session_info *session_info,
382                                               struct auth_session_info **presult)
383 {
384         struct auth_session_info *result;
385
386         if (lp_guest_only(snum)) {
387                 return make_session_info_guest(mem_ctx, presult);
388         }
389
390         /*
391          * This is the normal security != share case where we have a
392          * valid vuid from the session setup.                 */
393
394         if (security_session_user_level(session_info, NULL) < SECURITY_USER) {
395                 if (!lp_guest_ok(snum)) {
396                         DEBUG(2, ("guest user (from session setup) "
397                                   "not permitted to access this share "
398                                   "(%s)\n", lp_servicename(snum)));
399                         return NT_STATUS_ACCESS_DENIED;
400                 }
401         } else {
402                 if (!user_ok_token(session_info->unix_info->unix_name,
403                                    session_info->info->domain_name,
404                                    session_info->security_token, snum)) {
405                         DEBUG(2, ("user '%s' (from session setup) not "
406                                   "permitted to access this share "
407                                   "(%s)\n",
408                                   session_info->unix_info->unix_name,
409                                   lp_servicename(snum)));
410                         return NT_STATUS_ACCESS_DENIED;
411                 }
412         }
413
414         result = copy_session_info(mem_ctx, session_info);
415         if (result == NULL) {
416                 return NT_STATUS_NO_MEMORY;
417         }
418
419         *presult = result;
420         return NT_STATUS_OK;
421 }
422
423 /****************************************************************************
424   set relavent user and group settings corresponding to force user/group
425   configuration for the given snum.
426 ****************************************************************************/
427
428 NTSTATUS set_conn_force_user_group(connection_struct *conn, int snum)
429 {
430         NTSTATUS status;
431
432         if (*lp_force_user(snum)) {
433
434                 /*
435                  * Replace conn->session_info with a completely faked up one
436                  * from the username we are forced into :-)
437                  */
438
439                 char *fuser;
440                 char *sanitized_username;
441                 struct auth_session_info *forced_serverinfo;
442                 bool guest;
443
444                 fuser = talloc_string_sub(conn, lp_force_user(snum), "%S",
445                                           lp_const_servicename(snum));
446                 if (fuser == NULL) {
447                         return NT_STATUS_NO_MEMORY;
448                 }
449
450                 guest = security_session_user_level(conn->session_info, NULL) < SECURITY_USER;
451
452                 status = make_session_info_from_username(
453                         conn, fuser,
454                         guest,
455                         &forced_serverinfo);
456                 if (!NT_STATUS_IS_OK(status)) {
457                         return status;
458                 }
459
460                 /* We don't want to replace the original sanitized_username
461                    as it is the original user given in the connect attempt.
462                    This is used in '%U' substitutions. */
463                 sanitized_username = discard_const_p(char,
464                         forced_serverinfo->unix_info->sanitized_username);
465                 TALLOC_FREE(sanitized_username);
466                 forced_serverinfo->unix_info->sanitized_username =
467                         talloc_move(forced_serverinfo->unix_info,
468                                 &conn->session_info->unix_info->sanitized_username);
469
470                 TALLOC_FREE(conn->session_info);
471                 conn->session_info = forced_serverinfo;
472
473                 conn->force_user = true;
474                 DEBUG(3,("Forced user %s\n", fuser));
475         }
476
477         /*
478          * If force group is true, then override
479          * any groupid stored for the connecting user.
480          */
481
482         if (*lp_force_group(snum)) {
483
484                 status = find_forced_group(
485                         conn->force_user, snum, conn->session_info->unix_info->unix_name,
486                         &conn->session_info->security_token->sids[1],
487                         &conn->session_info->unix_token->gid);
488
489                 if (!NT_STATUS_IS_OK(status)) {
490                         return status;
491                 }
492
493                 /*
494                  * We need to cache this gid, to use within
495                  * change_to_user() separately from the conn->session_info
496                  * struct. We only use conn->session_info directly if
497                  * "force_user" was set.
498                  */
499                 conn->force_group_gid = conn->session_info->unix_token->gid;
500         }
501
502         return NT_STATUS_OK;
503 }
504
505 /****************************************************************************
506   Setup the share access mask for a connection.
507 ****************************************************************************/
508
509 static void create_share_access_mask(connection_struct *conn, int snum)
510 {
511         const struct security_token *token = conn->session_info->security_token;
512
513         share_access_check(token,
514                         lp_servicename(snum),
515                         MAXIMUM_ALLOWED_ACCESS,
516                         &conn->share_access);
517
518         if (security_token_has_privilege(token, SEC_PRIV_SECURITY)) {
519                 conn->share_access |= SEC_FLAG_SYSTEM_SECURITY;
520         }
521         if (security_token_has_privilege(token, SEC_PRIV_RESTORE)) {
522                 conn->share_access |= (SEC_RIGHTS_PRIV_RESTORE);
523         }
524         if (security_token_has_privilege(token, SEC_PRIV_BACKUP)) {
525                 conn->share_access |= (SEC_RIGHTS_PRIV_BACKUP);
526         }
527         if (security_token_has_privilege(token, SEC_PRIV_TAKE_OWNERSHIP)) {
528                 conn->share_access |= (SEC_STD_WRITE_OWNER);
529         }
530 }
531
532 /****************************************************************************
533   Make a connection, given the snum to connect to, and the vuser of the
534   connecting user if appropriate.
535 ****************************************************************************/
536
537 static NTSTATUS make_connection_snum(struct smbd_server_connection *sconn,
538                                         connection_struct *conn,
539                                         int snum, struct user_struct *vuser,
540                                         const char *pdev)
541 {
542         struct smb_filename *smb_fname_cpath = NULL;
543         fstring dev;
544         int ret;
545         bool on_err_call_dis_hook = false;
546         bool claimed_connection = false;
547         uid_t effuid;
548         gid_t effgid;
549         NTSTATUS status;
550
551         fstrcpy(dev, pdev);
552
553         status = share_sanity_checks(sconn->remote_address,
554                                        sconn->remote_hostname,
555                                        snum,
556                                        dev);
557         if (NT_STATUS_IS_ERR(status)) {
558                 goto err_root_exit;
559         }
560
561         conn->params->service = snum;
562
563         status = create_connection_session_info(sconn,
564                 conn, snum, vuser->session_info,
565                 &conn->session_info);
566
567         if (!NT_STATUS_IS_OK(status)) {
568                 DEBUG(1, ("create_connection_session_info failed: %s\n",
569                           nt_errstr(status)));
570                 goto err_root_exit;
571         }
572
573         if (lp_guest_only(snum)) {
574                 conn->force_user = true;
575         }
576
577         conn->num_files_open = 0;
578         conn->lastused = conn->lastused_count = time(NULL);
579         conn->printer = (strncmp(dev,"LPT",3) == 0);
580         conn->ipc = ( (strncmp(dev,"IPC",3) == 0) ||
581                       ( lp_enable_asu_support() && strequal(dev,"ADMIN$")) );
582
583         /* Case options for the share. */
584         if (lp_casesensitive(snum) == Auto) {
585                 /* We will be setting this per packet. Set to be case
586                  * insensitive for now. */
587                 conn->case_sensitive = False;
588         } else {
589                 conn->case_sensitive = (bool)lp_casesensitive(snum);
590         }
591
592         conn->case_preserve = lp_preservecase(snum);
593         conn->short_case_preserve = lp_shortpreservecase(snum);
594
595         conn->encrypt_level = lp_smb_encrypt(snum);
596
597         conn->veto_list = NULL;
598         conn->hide_list = NULL;
599         conn->veto_oplock_list = NULL;
600         conn->aio_write_behind_list = NULL;
601
602         conn->read_only = lp_readonly(SNUM(conn));
603
604         status = set_conn_force_user_group(conn, snum);
605         if (!NT_STATUS_IS_OK(status)) {
606                 goto err_root_exit;
607         }
608
609         conn->vuid = vuser->vuid;
610
611         {
612                 char *s = talloc_sub_advanced(talloc_tos(),
613                                         lp_servicename(SNUM(conn)),
614                                         conn->session_info->unix_info->unix_name,
615                                         conn->connectpath,
616                                         conn->session_info->unix_token->gid,
617                                         conn->session_info->unix_info->sanitized_username,
618                                         conn->session_info->info->domain_name,
619                                         lp_pathname(snum));
620                 if (!s) {
621                         status = NT_STATUS_NO_MEMORY;
622                         goto err_root_exit;
623                 }
624
625                 if (!set_conn_connectpath(conn,s)) {
626                         TALLOC_FREE(s);
627                         status = NT_STATUS_NO_MEMORY;
628                         goto err_root_exit;
629                 }
630                 DEBUG(3,("Connect path is '%s' for service [%s]\n",s,
631                          lp_servicename(snum)));
632                 TALLOC_FREE(s);
633         }
634
635         /*
636          * New code to check if there's a share security descripter
637          * added from NT server manager. This is done after the
638          * smb.conf checks are done as we need a uid and token. JRA.
639          *
640          */
641
642         create_share_access_mask(conn, snum);
643
644         if ((conn->share_access & FILE_WRITE_DATA) == 0) {
645                 if ((conn->share_access & FILE_READ_DATA) == 0) {
646                         /* No access, read or write. */
647                         DEBUG(0,("make_connection: connection to %s "
648                                  "denied due to security "
649                                  "descriptor.\n",
650                                  lp_servicename(snum)));
651                         status = NT_STATUS_ACCESS_DENIED;
652                         goto err_root_exit;
653                 } else {
654                         conn->read_only = True;
655                 }
656         }
657         /* Initialise VFS function pointers */
658
659         if (!smbd_vfs_init(conn)) {
660                 DEBUG(0, ("vfs_init failed for service %s\n",
661                           lp_servicename(snum)));
662                 status = NT_STATUS_BAD_NETWORK_NAME;
663                 goto err_root_exit;
664         }
665
666 /* ROOT Activities: */
667         /* explicitly check widelinks here so that we can correctly warn
668          * in the logs. */
669         widelinks_warning(snum);
670
671         /*
672          * Enforce the max connections parameter.
673          */
674
675         if ((lp_max_connections(snum) > 0)
676             && (count_current_connections(lp_servicename(SNUM(conn)), True) >=
677                 lp_max_connections(snum))) {
678
679                 DEBUG(1, ("Max connections (%d) exceeded for %s\n",
680                           lp_max_connections(snum), lp_servicename(snum)));
681                 status = NT_STATUS_INSUFFICIENT_RESOURCES;
682                 goto err_root_exit;
683         }
684
685         /*
686          * Get us an entry in the connections db
687          */
688         if (!claim_connection(conn, lp_servicename(snum))) {
689                 DEBUG(1, ("Could not store connections entry\n"));
690                 status = NT_STATUS_INTERNAL_DB_ERROR;
691                 goto err_root_exit;
692         }
693         claimed_connection = true;
694
695         /* Invoke VFS make connection hook - this must be the first
696            filesystem operation that we do. */
697
698         if (SMB_VFS_CONNECT(conn, lp_servicename(snum),
699                             conn->session_info->unix_info->unix_name) < 0) {
700                 DEBUG(0,("make_connection: VFS make connection failed!\n"));
701                 status = NT_STATUS_UNSUCCESSFUL;
702                 goto err_root_exit;
703         }
704
705         /* Any error exit after here needs to call the disconnect hook. */
706         on_err_call_dis_hook = true;
707
708         if ((!conn->printer) && (!conn->ipc) &&
709             lp_change_notify(conn->params)) {
710                 if (sconn->notify_ctx == NULL) {
711                         sconn->notify_ctx = notify_init(
712                                 sconn, sconn->msg_ctx, sconn->ev_ctx);
713                 }
714                 if (sconn->sys_notify_ctx == NULL) {
715                         sconn->sys_notify_ctx = sys_notify_context_create(
716                                 sconn, sconn->ev_ctx);
717                 }
718         }
719
720         if (lp_kernel_oplocks(snum)) {
721                 init_kernel_oplocks(conn->sconn);
722         }
723
724         /*
725          * Fix compatibility issue pointed out by Volker.
726          * We pass the conn->connectpath to the preexec
727          * scripts as a parameter, so attempt to canonicalize
728          * it here before calling the preexec scripts.
729          * We ignore errors here, as it is possible that
730          * the conn->connectpath doesn't exist yet and
731          * the preexec scripts will create them.
732          */
733
734         (void)canonicalize_connect_path(conn);
735
736         /* Preexecs are done here as they might make the dir we are to ChDir
737          * to below */
738         /* execute any "root preexec = " line */
739         if (*lp_rootpreexec(snum)) {
740                 char *cmd = talloc_sub_advanced(talloc_tos(),
741                                         lp_servicename(SNUM(conn)),
742                                         conn->session_info->unix_info->unix_name,
743                                         conn->connectpath,
744                                         conn->session_info->unix_token->gid,
745                                         conn->session_info->unix_info->sanitized_username,
746                                         conn->session_info->info->domain_name,
747                                         lp_rootpreexec(snum));
748                 DEBUG(5,("cmd=%s\n",cmd));
749                 ret = smbrun(cmd,NULL);
750                 TALLOC_FREE(cmd);
751                 if (ret != 0 && lp_rootpreexec_close(snum)) {
752                         DEBUG(1,("root preexec gave %d - failing "
753                                  "connection\n", ret));
754                         status = NT_STATUS_ACCESS_DENIED;
755                         goto err_root_exit;
756                 }
757         }
758
759 /* USER Activites: */
760         if (!change_to_user(conn, conn->vuid)) {
761                 /* No point continuing if they fail the basic checks */
762                 DEBUG(0,("Can't become connected user!\n"));
763                 status = NT_STATUS_LOGON_FAILURE;
764                 goto err_root_exit;
765         }
766
767         effuid = geteuid();
768         effgid = getegid();
769
770         /* Remember that a different vuid can connect later without these
771          * checks... */
772
773         /* Preexecs are done here as they might make the dir we are to ChDir
774          * to below */
775
776         /* execute any "preexec = " line */
777         if (*lp_preexec(snum)) {
778                 char *cmd = talloc_sub_advanced(talloc_tos(),
779                                         lp_servicename(SNUM(conn)),
780                                         conn->session_info->unix_info->unix_name,
781                                         conn->connectpath,
782                                         conn->session_info->unix_token->gid,
783                                         conn->session_info->unix_info->sanitized_username,
784                                         conn->session_info->info->domain_name,
785                                         lp_preexec(snum));
786                 ret = smbrun(cmd,NULL);
787                 TALLOC_FREE(cmd);
788                 if (ret != 0 && lp_preexec_close(snum)) {
789                         DEBUG(1,("preexec gave %d - failing connection\n",
790                                  ret));
791                         status = NT_STATUS_ACCESS_DENIED;
792                         goto err_root_exit;
793                 }
794         }
795
796 #ifdef WITH_FAKE_KASERVER
797         if (lp_afs_share(snum)) {
798                 afs_login(conn);
799         }
800 #endif
801
802         /*
803          * we've finished with the user stuff - go back to root
804          * so the SMB_VFS_STAT call will only fail on path errors,
805          * not permission problems.
806          */
807         change_to_root_user();
808 /* ROOT Activites: */
809
810         /*
811          * If widelinks are disallowed we need to canonicalise the connect
812          * path here to ensure we don't have any symlinks in the
813          * connectpath. We will be checking all paths on this connection are
814          * below this directory. We must do this after the VFS init as we
815          * depend on the realpath() pointer in the vfs table. JRA.
816          */
817         if (!lp_widelinks(snum)) {
818                 if (!canonicalize_connect_path(conn)) {
819                         DEBUG(0, ("canonicalize_connect_path failed "
820                         "for service %s, path %s\n",
821                                 lp_servicename(snum),
822                                 conn->connectpath));
823                         status = NT_STATUS_BAD_NETWORK_NAME;
824                         goto err_root_exit;
825                 }
826         }
827
828         /* Add veto/hide lists */
829         if (!IS_IPC(conn) && !IS_PRINT(conn)) {
830                 set_namearray( &conn->veto_list, lp_veto_files(snum));
831                 set_namearray( &conn->hide_list, lp_hide_files(snum));
832                 set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(snum));
833                 set_namearray( &conn->aio_write_behind_list,
834                                 lp_aio_write_behind(snum));
835         }
836         status = create_synthetic_smb_fname(talloc_tos(), conn->connectpath,
837                                             NULL, NULL, &smb_fname_cpath);
838         if (!NT_STATUS_IS_OK(status)) {
839                 goto err_root_exit;
840         }
841
842         /* win2000 does not check the permissions on the directory
843            during the tree connect, instead relying on permission
844            check during individual operations. To match this behaviour
845            I have disabled this chdir check (tridge) */
846         /* the alternative is just to check the directory exists */
847
848         if ((ret = SMB_VFS_STAT(conn, smb_fname_cpath)) != 0 ||
849             !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) {
850                 if (ret == 0 && !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) {
851                         DEBUG(0,("'%s' is not a directory, when connecting to "
852                                  "[%s]\n", conn->connectpath,
853                                  lp_servicename(snum)));
854                 } else {
855                         DEBUG(0,("'%s' does not exist or permission denied "
856                                  "when connecting to [%s] Error was %s\n",
857                                  conn->connectpath, lp_servicename(snum),
858                                  strerror(errno) ));
859                 }
860                 status = NT_STATUS_BAD_NETWORK_NAME;
861                 goto err_root_exit;
862         }
863         conn->base_share_dev = smb_fname_cpath->st.st_ex_dev;
864
865         string_set(&conn->origpath,conn->connectpath);
866
867         /* Figure out the characteristics of the underlying filesystem. This
868          * assumes that all the filesystem mounted withing a share path have
869          * the same characteristics, which is likely but not guaranteed.
870          */
871
872         conn->fs_capabilities = SMB_VFS_FS_CAPABILITIES(conn, &conn->ts_res);
873
874         /*
875          * Print out the 'connected as' stuff here as we need
876          * to know the effective uid and gid we will be using
877          * (at least initially).
878          */
879
880         if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
881                 dbgtext( "%s (%s) ", get_remote_machine_name(),
882                          tsocket_address_string(conn->sconn->remote_address,
883                                                 talloc_tos()) );
884                 dbgtext( "%s", srv_is_signing_active(sconn) ? "signed " : "");
885                 dbgtext( "connect to service %s ", lp_servicename(snum) );
886                 dbgtext( "initially as user %s ",
887                          conn->session_info->unix_info->unix_name );
888                 dbgtext( "(uid=%d, gid=%d) ", (int)effuid, (int)effgid );
889                 dbgtext( "(pid %d)\n", (int)getpid() );
890         }
891
892         return status;
893
894   err_root_exit:
895
896         TALLOC_FREE(smb_fname_cpath);
897         /* We must exit this function as root. */
898         if (geteuid() != 0) {
899                 change_to_root_user();
900         }
901         if (on_err_call_dis_hook) {
902                 /* Call VFS disconnect hook */
903                 SMB_VFS_DISCONNECT(conn);
904         }
905         if (claimed_connection) {
906                 yield_connection(conn, lp_servicename(snum));
907         }
908         return status;
909 }
910
911 /****************************************************************************
912  Make a connection to a service from SMB1. Internal interface.
913 ****************************************************************************/
914
915 static connection_struct *make_connection_smb1(struct smbd_server_connection *sconn,
916                                         int snum, struct user_struct *vuser,
917                                         const char *pdev,
918                                         NTSTATUS *pstatus)
919 {
920         connection_struct *conn = conn_new(sconn);
921         if (!conn) {
922                 DEBUG(0,("make_connection_smb1: Couldn't find free connection.\n"));
923                 *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
924                 return NULL;
925         }
926         *pstatus = make_connection_snum(sconn,
927                                         conn,
928                                         snum,
929                                         vuser,
930                                         pdev);
931         if (!NT_STATUS_IS_OK(*pstatus)) {
932                 conn_free(conn);
933                 return NULL;
934         }
935         return conn;
936 }
937
938 /****************************************************************************
939  Make a connection to a service from SMB2. External SMB2 interface.
940  We must set cnum before claiming connection.
941 ****************************************************************************/
942
943 connection_struct *make_connection_smb2(struct smbd_server_connection *sconn,
944                                         struct smbXsrv_tcon *tcon,
945                                         int snum,
946                                         struct user_struct *vuser,
947                                         const char *pdev,
948                                         NTSTATUS *pstatus)
949 {
950         connection_struct *conn = conn_new(sconn);
951         if (!conn) {
952                 DEBUG(0,("make_connection_smb2: Couldn't find free connection.\n"));
953                 *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
954                 return NULL;
955         }
956
957         conn->cnum = tcon->global->tcon_wire_id;
958         conn->tcon = tcon;
959
960         *pstatus = make_connection_snum(sconn,
961                                         conn,
962                                         snum,
963                                         vuser,
964                                         pdev);
965         if (!NT_STATUS_IS_OK(*pstatus)) {
966                 conn_free(conn);
967                 return NULL;
968         }
969         return conn;
970 }
971
972 /****************************************************************************
973  Make a connection to a service. External SMB1 interface.
974  *
975  * @param service 
976 ****************************************************************************/
977
978 connection_struct *make_connection(struct smbd_server_connection *sconn,
979                                    const char *service_in,
980                                    const char *pdev, uint64_t vuid,
981                                    NTSTATUS *status)
982 {
983         uid_t euid;
984         struct user_struct *vuser = NULL;
985         char *service = NULL;
986         fstring dev;
987         int snum = -1;
988
989         fstrcpy(dev, pdev);
990
991         /* This must ONLY BE CALLED AS ROOT. As it exits this function as
992          * root. */
993         if (!non_root_mode() && (euid = geteuid()) != 0) {
994                 DEBUG(0,("make_connection: PANIC ERROR. Called as nonroot "
995                          "(%u)\n", (unsigned int)euid ));
996                 smb_panic("make_connection: PANIC ERROR. Called as nonroot\n");
997         }
998
999         if (conn_num_open(sconn) > 2047) {
1000                 *status = NT_STATUS_INSUFF_SERVER_RESOURCES;
1001                 return NULL;
1002         }
1003
1004         vuser = get_valid_user_struct(sconn, vuid);
1005         if (!vuser) {
1006                 DEBUG(1,("make_connection: refusing to connect with "
1007                          "no session setup\n"));
1008                 *status = NT_STATUS_ACCESS_DENIED;
1009                 return NULL;
1010         }
1011
1012         /* Logic to try and connect to the correct [homes] share, preferably
1013            without too many getpwnam() lookups.  This is particulary nasty for
1014            winbind usernames, where the share name isn't the same as unix
1015            username.
1016
1017            The snum of the homes share is stored on the vuser at session setup
1018            time.
1019         */
1020
1021         if (strequal(service_in,HOMES_NAME)) {
1022                 if (vuser->homes_snum == -1) {
1023                         DEBUG(2, ("[homes] share not available for "
1024                                   "this user because it was not found "
1025                                   "or created at session setup "
1026                                   "time\n"));
1027                         *status = NT_STATUS_BAD_NETWORK_NAME;
1028                         return NULL;
1029                 }
1030                 DEBUG(5, ("making a connection to [homes] service "
1031                           "created at session setup time\n"));
1032                 return make_connection_smb1(sconn,
1033                                             vuser->homes_snum,
1034                                             vuser,
1035                                             dev, status);
1036         } else if ((vuser->homes_snum != -1)
1037                    && strequal(service_in,
1038                                lp_servicename(vuser->homes_snum))) {
1039                 DEBUG(5, ("making a connection to 'homes' service [%s] "
1040                           "created at session setup time\n", service_in));
1041                 return make_connection_smb1(sconn,
1042                                             vuser->homes_snum,
1043                                             vuser,
1044                                             dev, status);
1045         }
1046
1047         service = talloc_strdup(talloc_tos(), service_in);
1048         if (!service) {
1049                 *status = NT_STATUS_NO_MEMORY;
1050                 return NULL;
1051         }
1052
1053         strlower_m(service);
1054
1055         snum = find_service(talloc_tos(), service, &service);
1056         if (!service) {
1057                 *status = NT_STATUS_NO_MEMORY;
1058                 return NULL;
1059         }
1060
1061         if (snum < 0) {
1062                 if (strequal(service,"IPC$") ||
1063                     (lp_enable_asu_support() && strequal(service,"ADMIN$"))) {
1064                         DEBUG(3,("refusing IPC connection to %s\n", service));
1065                         *status = NT_STATUS_ACCESS_DENIED;
1066                         return NULL;
1067                 }
1068
1069                 DEBUG(3,("%s (%s) couldn't find service %s\n",
1070                         get_remote_machine_name(),
1071                         tsocket_address_string(
1072                                 sconn->remote_address, talloc_tos()),
1073                         service));
1074                 *status = NT_STATUS_BAD_NETWORK_NAME;
1075                 return NULL;
1076         }
1077
1078         /* Handle non-Dfs clients attempting connections to msdfs proxy */
1079         if (lp_host_msdfs() && (*lp_msdfs_proxy(snum) != '\0'))  {
1080                 DEBUG(3, ("refusing connection to dfs proxy share '%s' "
1081                           "(pointing to %s)\n", 
1082                         service, lp_msdfs_proxy(snum)));
1083                 *status = NT_STATUS_BAD_NETWORK_NAME;
1084                 return NULL;
1085         }
1086
1087         DEBUG(5, ("making a connection to 'normal' service %s\n", service));
1088
1089         return make_connection_smb1(sconn, snum, vuser,
1090                                     dev, status);
1091 }
1092
1093 /****************************************************************************
1094  Close a cnum.
1095 ****************************************************************************/
1096
1097 void close_cnum(connection_struct *conn, uint64_t vuid)
1098 {
1099         file_close_conn(conn);
1100
1101         if (!IS_IPC(conn)) {
1102                 dptr_closecnum(conn);
1103         }
1104
1105         change_to_root_user();
1106
1107         DEBUG(IS_IPC(conn)?3:1, ("%s (%s) closed connection to service %s\n",
1108                                  get_remote_machine_name(),
1109                                  tsocket_address_string(conn->sconn->remote_address,
1110                                                         talloc_tos()),
1111                                  lp_servicename(SNUM(conn))));
1112
1113         /* Call VFS disconnect hook */    
1114         SMB_VFS_DISCONNECT(conn);
1115
1116         yield_connection(conn, lp_servicename(SNUM(conn)));
1117
1118         /* make sure we leave the directory available for unmount */
1119         vfs_ChDir(conn, "/");
1120
1121         /* execute any "postexec = " line */
1122         if (*lp_postexec(SNUM(conn)) && 
1123             change_to_user(conn, vuid))  {
1124                 char *cmd = talloc_sub_advanced(talloc_tos(),
1125                                         lp_servicename(SNUM(conn)),
1126                                         conn->session_info->unix_info->unix_name,
1127                                         conn->connectpath,
1128                                         conn->session_info->unix_token->gid,
1129                                         conn->session_info->unix_info->sanitized_username,
1130                                         conn->session_info->info->domain_name,
1131                                         lp_postexec(SNUM(conn)));
1132                 smbrun(cmd,NULL);
1133                 TALLOC_FREE(cmd);
1134                 change_to_root_user();
1135         }
1136
1137         change_to_root_user();
1138         /* execute any "root postexec = " line */
1139         if (*lp_rootpostexec(SNUM(conn)))  {
1140                 char *cmd = talloc_sub_advanced(talloc_tos(),
1141                                         lp_servicename(SNUM(conn)),
1142                                         conn->session_info->unix_info->unix_name,
1143                                         conn->connectpath,
1144                                         conn->session_info->unix_token->gid,
1145                                         conn->session_info->unix_info->sanitized_username,
1146                                         conn->session_info->info->domain_name,
1147                                         lp_rootpostexec(SNUM(conn)));
1148                 smbrun(cmd,NULL);
1149                 TALLOC_FREE(cmd);
1150         }
1151
1152         conn_free(conn);
1153 }