[GLUE] Rsync SAMBA_3_2_0 SVN r25598 in order to create the v3-2-test branch.
[samba.git] / source / lib / substitute.c
1 /* 
2    Unix SMB/CIFS implementation.
3    string substitution functions
4    Copyright (C) Andrew Tridgell 1992-2000
5    Copyright (C) Gerald Carter   2006
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
22 #include "includes.h"
23
24 extern struct current_user current_user;
25
26 fstring local_machine="";
27 fstring remote_arch="UNKNOWN";
28 userdom_struct current_user_info;
29 fstring remote_proto="UNKNOWN";
30
31 static fstring remote_machine;
32 static fstring smb_user_name;
33
34 /** 
35  * Set the 'local' machine name
36  * @param local_name the name we are being called
37  * @param if this is the 'final' name for us, not be be changed again
38  */
39
40 void set_local_machine_name(const char* local_name, BOOL perm)
41 {
42         static BOOL already_perm = False;
43         fstring tmp_local_machine;
44
45         fstrcpy(tmp_local_machine,local_name);
46         trim_char(tmp_local_machine,' ',' ');
47
48         /*
49          * Windows NT/2k uses "*SMBSERVER" and XP uses "*SMBSERV"
50          * arrggg!!! 
51          */
52
53         if ( strequal(tmp_local_machine, "*SMBSERVER") || strequal(tmp_local_machine, "*SMBSERV") )  {
54                 fstrcpy( local_machine, client_socket_addr() );
55                 return;
56         }
57
58         if (already_perm)
59                 return;
60
61         already_perm = perm;
62
63         alpha_strcpy(local_machine,tmp_local_machine,SAFE_NETBIOS_CHARS,sizeof(local_machine)-1);
64         strlower_m(local_machine);
65 }
66
67 /** 
68  * Set the 'remote' machine name
69  * @param remote_name the name our client wants to be called by
70  * @param if this is the 'final' name for them, not be be changed again
71  */
72
73 void set_remote_machine_name(const char* remote_name, BOOL perm)
74 {
75         static BOOL already_perm = False;
76         fstring tmp_remote_machine;
77
78         if (already_perm)
79                 return;
80
81         already_perm = perm;
82
83         fstrcpy(tmp_remote_machine,remote_name);
84         trim_char(tmp_remote_machine,' ',' ');
85         alpha_strcpy(remote_machine,tmp_remote_machine,SAFE_NETBIOS_CHARS,sizeof(remote_machine)-1);
86         strlower_m(remote_machine);
87 }
88
89 const char* get_remote_machine_name(void) 
90 {
91         return remote_machine;
92 }
93
94 const char* get_local_machine_name(void) 
95 {
96         if (!*local_machine) {
97                 return global_myname();
98         }
99
100         return local_machine;
101 }
102
103 /*******************************************************************
104  Setup the string used by %U substitution.
105 ********************************************************************/
106
107 void sub_set_smb_name(const char *name)
108 {
109         fstring tmp;
110         int len;
111         BOOL is_machine_account = False;
112
113         /* don't let anonymous logins override the name */
114         if (! *name)
115                 return;
116
117
118         fstrcpy( tmp, name );
119         trim_char( tmp, ' ', ' ' );
120         strlower_m( tmp );
121
122         len = strlen( tmp );
123
124         if ( len == 0 )
125                 return;
126
127         /* long story but here goes....we have to allow usernames
128            ending in '$' as they are valid machine account names.
129            So check for a machine account and re-add the '$'
130            at the end after the call to alpha_strcpy().   --jerry  */
131            
132         if ( tmp[len-1] == '$' )
133                 is_machine_account = True;
134         
135         alpha_strcpy( smb_user_name, tmp, SAFE_NETBIOS_CHARS, sizeof(smb_user_name)-1 );
136
137         if ( is_machine_account ) {
138                 len = strlen( smb_user_name );
139                 smb_user_name[len-1] = '$';
140         }
141 }
142
143 /*******************************************************************
144  Setup the strings used by substitutions. Called per packet. Ensure
145  %U name is set correctly also.
146 ********************************************************************/
147
148 void set_current_user_info(const userdom_struct *pcui)
149 {
150         current_user_info = *pcui;
151         /* The following is safe as current_user_info.smb_name
152          * has already been sanitised in register_existing_vuid. */
153         fstrcpy(smb_user_name, current_user_info.smb_name);
154 }
155
156 /*******************************************************************
157  return the current active user name
158 *******************************************************************/
159
160 const char* get_current_username( void )
161 {
162         if ( current_user_info.smb_name[0] == '\0' )
163                 return smb_user_name;
164
165         return current_user_info.smb_name; 
166 }
167
168 /*******************************************************************
169  Given a pointer to a %$(NAME) in p and the whole string in str
170  expand it as an environment variable.
171  Return a new allocated and expanded string.
172  Based on code by Branko Cibej <branko.cibej@hermes.si>
173  When this is called p points at the '%' character.
174  May substitute multiple occurrencies of the same env var.
175 ********************************************************************/
176
177 static char * realloc_expand_env_var(char *str, char *p)
178 {
179         char *envname;
180         char *envval;
181         char *q, *r;
182         int copylen;
183
184         if (p[0] != '%' || p[1] != '$' || p[2] != '(') {
185                 return str;
186         }
187
188         /*
189          * Look for the terminating ')'.
190          */
191
192         if ((q = strchr_m(p,')')) == NULL) {
193                 DEBUG(0,("expand_env_var: Unterminated environment variable [%s]\n", p));
194                 return str;
195         }
196
197         /*
198          * Extract the name from within the %$(NAME) string.
199          */
200
201         r = p + 3;
202         copylen = q - r;
203         
204         /* reserve space for use later add %$() chars */
205         if ( (envname = (char *)SMB_MALLOC(copylen + 1 + 4)) == NULL ) {
206                 return NULL;
207         }
208         
209         strncpy(envname,r,copylen);
210         envname[copylen] = '\0';
211
212         if ((envval = getenv(envname)) == NULL) {
213                 DEBUG(0,("expand_env_var: Environment variable [%s] not set\n", envname));
214                 SAFE_FREE(envname);
215                 return str;
216         }
217
218         /*
219          * Copy the full %$(NAME) into envname so it
220          * can be replaced.
221          */
222
223         copylen = q + 1 - p;
224         strncpy(envname,p,copylen);
225         envname[copylen] = '\0';
226         r = realloc_string_sub(str, envname, envval);
227         SAFE_FREE(envname);
228                 
229         return r;
230 }
231
232 /*******************************************************************
233 *******************************************************************/
234
235 static char *longvar_domainsid( void )
236 {
237         DOM_SID sid;
238         char *sid_string;
239         
240         if ( !secrets_fetch_domain_sid( lp_workgroup(), &sid ) ) {
241                 return NULL;
242         }
243         
244         sid_string = SMB_STRDUP( sid_string_static( &sid ) );
245         
246         if ( !sid_string ) {
247                 DEBUG(0,("longvar_domainsid: failed to dup SID string!\n"));
248         }
249         
250         return sid_string;
251 }
252
253 /*******************************************************************
254 *******************************************************************/
255
256 struct api_longvar {
257         const char *name;
258         char* (*fn)( void );
259 };
260
261 static struct api_longvar longvar_table[] = {
262         { "DomainSID",          longvar_domainsid },
263         { NULL,                 NULL }
264 };
265
266 static char *get_longvar_val( const char *varname )
267 {
268         int i;
269         
270         DEBUG(7,("get_longvar_val: expanding variable [%s]\n", varname));
271         
272         for ( i=0; longvar_table[i].name; i++ ) {
273                 if ( strequal( longvar_table[i].name, varname ) ) {
274                         return longvar_table[i].fn();
275                 }
276         }
277         
278         return NULL;
279 }
280
281 /*******************************************************************
282  Expand the long smb.conf variable names given a pointer to a %(NAME).
283  Return the number of characters by which the pointer should be advanced.
284  When this is called p points at the '%' character.
285 ********************************************************************/
286
287 static char *realloc_expand_longvar(char *str, char *p)
288 {
289         fstring varname;
290         char *value;
291         char *q, *r;
292         int copylen;
293
294         if ( p[0] != '%' || p[1] != '(' ) {
295                 return str;
296         }
297
298         /* Look for the terminating ')'.*/
299
300         if ((q = strchr_m(p,')')) == NULL) {
301                 DEBUG(0,("realloc_expand_longvar: Unterminated environment variable [%s]\n", p));
302                 return str;
303         }
304
305         /* Extract the name from within the %(NAME) string.*/
306
307         r = p+2;
308         copylen = MIN( (q-r), (sizeof(varname)-1) );
309         strncpy(varname, r, copylen);
310         varname[copylen] = '\0';
311
312         if ((value = get_longvar_val(varname)) == NULL) {
313                 DEBUG(0,("realloc_expand_longvar: Variable [%s] not set.  Skipping\n", varname));
314                 return str;
315         }
316
317         /* Copy the full %(NAME) into envname so it can be replaced.*/
318
319         copylen = MIN( (q+1-p),(sizeof(varname)-1) );
320         strncpy( varname, p, copylen );
321         varname[copylen] = '\0';
322         r = realloc_string_sub(str, varname, value);
323         SAFE_FREE( value );
324         
325         /* skip over the %(varname) */
326         
327         return r;
328 }
329
330 /*******************************************************************
331  Patch from jkf@soton.ac.uk
332  Added this to implement %p (NIS auto-map version of %H)
333 *******************************************************************/
334
335 static char *automount_path(const char *user_name)
336 {
337         pstring server_path;
338
339         /* use the passwd entry as the default */
340         /* this will be the default if WITH_AUTOMOUNT is not used or fails */
341
342         pstrcpy(server_path, get_user_home_dir(user_name));
343
344 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
345
346         if (lp_nis_home_map()) {
347                 const char *home_path_start;
348                 const char *automount_value = automount_lookup(user_name);
349
350                 if(strlen(automount_value) > 0) {
351                         home_path_start = strchr_m(automount_value,':');
352                         if (home_path_start != NULL) {
353                                 DEBUG(5, ("NIS lookup succeeded.  Home path is: %s\n",
354                                                 home_path_start?(home_path_start+1):""));
355                                 pstrcpy(server_path, home_path_start+1);
356                         }
357                 } else {
358                         /* NIS key lookup failed: default to user home directory from password file */
359                         DEBUG(5, ("NIS lookup failed. Using Home path from passwd file. Home path is: %s\n", server_path ));
360                 }
361         }
362 #endif
363
364         DEBUG(4,("Home server path: %s\n", server_path));
365
366         return talloc_strdup(talloc_tos(), server_path);
367 }
368
369 /*******************************************************************
370  Patch from jkf@soton.ac.uk
371  This is Luke's original function with the NIS lookup code
372  moved out to a separate function.
373 *******************************************************************/
374
375 static const char *automount_server(const char *user_name)
376 {
377         pstring server_name;
378         const char *local_machine_name = get_local_machine_name(); 
379
380         /* use the local machine name as the default */
381         /* this will be the default if WITH_AUTOMOUNT is not used or fails */
382         if (local_machine_name && *local_machine_name)
383                 pstrcpy(server_name, local_machine_name);
384         else
385                 pstrcpy(server_name, global_myname());
386         
387 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
388
389         if (lp_nis_home_map()) {
390                 int home_server_len;
391                 char *automount_value = automount_lookup(user_name);
392                 home_server_len = strcspn(automount_value,":");
393                 DEBUG(5, ("NIS lookup succeeded.  Home server length: %d\n",home_server_len));
394                 if (home_server_len > sizeof(pstring))
395                         home_server_len = sizeof(pstring);
396                 strncpy(server_name, automount_value, home_server_len);
397                 server_name[home_server_len] = '\0';
398         }
399 #endif
400
401         DEBUG(4,("Home server: %s\n", server_name));
402
403         return talloc_strdup(talloc_tos(), server_name);
404 }
405
406 /****************************************************************************
407  Do some standard substitutions in a string.
408  len is the length in bytes of the space allowed in string str. If zero means
409  don't allow expansions.
410 ****************************************************************************/
411
412 void standard_sub_basic(const char *smb_name, const char *domain_name,
413                         char *str, size_t len)
414 {
415         char *s;
416         
417         if ( (s = alloc_sub_basic( smb_name, domain_name, str )) != NULL ) {
418                 strncpy( str, s, len );
419         }
420         
421         SAFE_FREE( s );
422         
423 }
424
425 /****************************************************************************
426  Do some standard substitutions in a string.
427  This function will return an allocated string that have to be freed.
428 ****************************************************************************/
429
430 char *talloc_sub_basic(TALLOC_CTX *mem_ctx, const char *smb_name,
431                        const char *domain_name, const char *str)
432 {
433         char *a, *t;
434         
435         if ( (a = alloc_sub_basic(smb_name, domain_name, str)) == NULL ) {
436                 return NULL;
437         }
438         t = talloc_strdup(mem_ctx, a);
439         SAFE_FREE(a);
440         return t;
441 }
442
443 /****************************************************************************
444 ****************************************************************************/
445
446 char *alloc_sub_basic(const char *smb_name, const char *domain_name,
447                       const char *str)
448 {
449         char *b, *p, *s, *r, *a_string;
450         fstring pidstr, vnnstr;
451         struct passwd *pass;
452         const char *local_machine_name = get_local_machine_name();
453
454         /* workaround to prevent a crash while looking at bug #687 */
455         
456         if (!str) {
457                 DEBUG(0,("alloc_sub_basic: NULL source string!  This should not happen\n"));
458                 return NULL;
459         }
460         
461         a_string = SMB_STRDUP(str);
462         if (a_string == NULL) {
463                 DEBUG(0, ("alloc_sub_basic: Out of memory!\n"));
464                 return NULL;
465         }
466         
467         for (b = s = a_string; (p = strchr_m(s, '%')); s = a_string + (p - b)) {
468
469                 r = NULL;
470                 b = a_string;
471                 
472                 switch (*(p+1)) {
473                 case 'U' : 
474                         r = strdup_lower(smb_name);
475                         if (r == NULL) {
476                                 goto error;
477                         }
478                         a_string = realloc_string_sub(a_string, "%U", r);
479                         break;
480                 case 'G' :
481                         r = SMB_STRDUP(smb_name);
482                         if (r == NULL) {
483                                 goto error;
484                         }
485                         if ((pass = Get_Pwnam(r))!=NULL) {
486                                 a_string = realloc_string_sub(a_string, "%G", gidtoname(pass->pw_gid));
487                         } 
488                         break;
489                 case 'D' :
490                         r = strdup_upper(domain_name);
491                         if (r == NULL) {
492                                 goto error;
493                         }
494                         a_string = realloc_string_sub(a_string, "%D", r);
495                         break;
496                 case 'I' :
497                         a_string = realloc_string_sub(a_string, "%I", client_addr());
498                         break;
499                 case 'i': 
500                         a_string = realloc_string_sub( a_string, "%i", client_socket_addr() );
501                         break;
502                 case 'L' : 
503                         if ( StrnCaseCmp(p, "%LOGONSERVER%", strlen("%LOGONSERVER%")) == 0 ) {
504                                 break;
505                         }
506                         if (local_machine_name && *local_machine_name) {
507                                 a_string = realloc_string_sub(a_string, "%L", local_machine_name); 
508                         } else {
509                                 a_string = realloc_string_sub(a_string, "%L", global_myname()); 
510                         }
511                         break;
512                 case 'N':
513                         a_string = realloc_string_sub(a_string, "%N", automount_server(smb_name));
514                         break;
515                 case 'M' :
516                         a_string = realloc_string_sub(a_string, "%M", client_name());
517                         break;
518                 case 'R' :
519                         a_string = realloc_string_sub(a_string, "%R", remote_proto);
520                         break;
521                 case 'T' :
522                         a_string = realloc_string_sub(a_string, "%T", current_timestring(False));
523                         break;
524                 case 'a' :
525                         a_string = realloc_string_sub(a_string, "%a", remote_arch);
526                         break;
527                 case 'd' :
528                         slprintf(pidstr,sizeof(pidstr)-1, "%d",(int)sys_getpid());
529                         a_string = realloc_string_sub(a_string, "%d", pidstr);
530                         break;
531                 case 'h' :
532                         a_string = realloc_string_sub(a_string, "%h", myhostname());
533                         break;
534                 case 'm' :
535                         a_string = realloc_string_sub(a_string, "%m", remote_machine);
536                         break;
537                 case 'v' :
538                         a_string = realloc_string_sub(a_string, "%v", SAMBA_VERSION_STRING);
539                         break;
540                 case 'w' :
541                         a_string = realloc_string_sub(a_string, "%w", lp_winbind_separator());
542                         break;
543                 case '$' :
544                         a_string = realloc_expand_env_var(a_string, p); /* Expand environment variables */
545                         break;
546                 case '(':
547                         a_string = realloc_expand_longvar( a_string, p );
548                         break;
549                 case 'V' :
550                         slprintf(vnnstr,sizeof(vnnstr)-1, "%u", get_my_vnn());
551                         a_string = realloc_string_sub(a_string, "%V", vnnstr);
552                         break;
553                 default: 
554                         break;
555                 }
556
557                 p++;
558                 SAFE_FREE(r);
559                 
560                 if ( !a_string ) {
561                         return NULL;
562                 }
563         }
564
565         return a_string;
566
567 error:
568         SAFE_FREE(a_string);
569         return NULL;
570 }
571
572 /****************************************************************************
573  Do some specific substitutions in a string.
574  This function will return an allocated string that have to be freed.
575 ****************************************************************************/
576
577 char *talloc_sub_specified(TALLOC_CTX *mem_ctx,
578                         const char *input_string,
579                         const char *username,
580                         const char *domain,
581                         uid_t uid,
582                         gid_t gid)
583 {
584         char *a_string;
585         char *ret_string = NULL;
586         char *b, *p, *s;
587         TALLOC_CTX *tmp_ctx;
588
589         if (!(tmp_ctx = talloc_new(mem_ctx))) {
590                 DEBUG(0, ("talloc_new failed\n"));
591                 return NULL;
592         }
593
594         a_string = talloc_strdup(tmp_ctx, input_string);
595         if (a_string == NULL) {
596                 DEBUG(0, ("talloc_sub_specified: Out of memory!\n"));
597                 goto done;
598         }
599         
600         for (b = s = a_string; (p = strchr_m(s, '%')); s = a_string + (p - b)) {
601                 
602                 b = a_string;
603                 
604                 switch (*(p+1)) {
605                 case 'U' : 
606                         a_string = talloc_string_sub(
607                                 tmp_ctx, a_string, "%U", username);
608                         break;
609                 case 'u' : 
610                         a_string = talloc_string_sub(
611                                 tmp_ctx, a_string, "%u", username);
612                         break;
613                 case 'G' :
614                         if (gid != -1) {
615                                 a_string = talloc_string_sub(
616                                         tmp_ctx, a_string, "%G",
617                                         gidtoname(gid));
618                         } else {
619                                 a_string = talloc_string_sub(
620                                         tmp_ctx, a_string,
621                                         "%G", "NO_GROUP");
622                         }
623                         break;
624                 case 'g' :
625                         if (gid != -1) {
626                                 a_string = talloc_string_sub(
627                                         tmp_ctx, a_string, "%g",
628                                         gidtoname(gid));
629                         } else {
630                                 a_string = talloc_string_sub(
631                                         tmp_ctx, a_string, "%g", "NO_GROUP");
632                         }
633                         break;
634                 case 'D' :
635                         a_string = talloc_string_sub(tmp_ctx, a_string,
636                                                      "%D", domain);
637                         break;
638                 case 'N' : 
639                         a_string = talloc_string_sub(
640                                 tmp_ctx, a_string, "%N",
641                                 automount_server(username)); 
642                         break;
643                 default: 
644                         break;
645                 }
646
647                 p++;
648                 if (a_string == NULL) {
649                         goto done;
650                 }
651         }
652
653         /* Watch out, using "mem_ctx" here, so all intermediate stuff goes
654          * away with the TALLOC_FREE(tmp_ctx) further down. */
655
656         ret_string = talloc_sub_basic(mem_ctx, username, domain, a_string);
657
658  done:
659         TALLOC_FREE(tmp_ctx);
660         return ret_string;
661 }
662
663 /****************************************************************************
664 ****************************************************************************/
665
666 static char *alloc_sub_advanced(const char *servicename, const char *user, 
667                          const char *connectpath, gid_t gid, 
668                          const char *smb_name, const char *domain_name,
669                          const char *str)
670 {
671         char *a_string, *ret_string;
672         char *b, *p, *s, *h;
673
674         a_string = SMB_STRDUP(str);
675         if (a_string == NULL) {
676                 DEBUG(0, ("alloc_sub_advanced: Out of memory!\n"));
677                 return NULL;
678         }
679         
680         for (b = s = a_string; (p = strchr_m(s, '%')); s = a_string + (p - b)) {
681                 
682                 b = a_string;
683                 
684                 switch (*(p+1)) {
685                 case 'N' :
686                         a_string = realloc_string_sub(a_string, "%N", automount_server(user));
687                         break;
688                 case 'H':
689                         if ((h = get_user_home_dir(user)))
690                                 a_string = realloc_string_sub(a_string, "%H", h);
691                         break;
692                 case 'P': 
693                         a_string = realloc_string_sub(a_string, "%P", connectpath); 
694                         break;
695                 case 'S': 
696                         a_string = realloc_string_sub(a_string, "%S", servicename);
697                         break;
698                 case 'g': 
699                         a_string = realloc_string_sub(a_string, "%g", gidtoname(gid)); 
700                         break;
701                 case 'u': 
702                         a_string = realloc_string_sub(a_string, "%u", user); 
703                         break;
704                         
705                         /* Patch from jkf@soton.ac.uk Left the %N (NIS
706                          * server name) in standard_sub_basic as it is
707                          * a feature for logon servers, hence uses the
708                          * username.  The %p (NIS server path) code is
709                          * here as it is used instead of the default
710                          * "path =" string in [homes] and so needs the
711                          * service name, not the username.  */
712                 case 'p': 
713                         a_string = realloc_string_sub(a_string, "%p",
714                                                       automount_path(servicename)); 
715                         break;
716                         
717                 default: 
718                         break;
719                 }
720
721                 p++;
722                 if (a_string == NULL) {
723                         return NULL;
724                 }
725         }
726
727         ret_string = alloc_sub_basic(smb_name, domain_name, a_string);
728         SAFE_FREE(a_string);
729         return ret_string;
730 }
731
732 /*
733  * This obviously is inefficient and needs to be merged into
734  * alloc_sub_advanced...
735  */
736
737 char *talloc_sub_advanced(TALLOC_CTX *mem_ctx,
738                           const char *servicename, const char *user, 
739                           const char *connectpath, gid_t gid, 
740                           const char *smb_name, const char *domain_name,
741                           const char *str)
742 {
743         char *a, *t;
744
745         if (!(a = alloc_sub_advanced(servicename, user, connectpath, gid,
746                                      smb_name, domain_name, str))) {
747                 return NULL;
748         }
749         t = talloc_strdup(mem_ctx, a);
750         SAFE_FREE(a);
751         return t;
752 }
753
754
755 void standard_sub_advanced(const char *servicename, const char *user, 
756                            const char *connectpath, gid_t gid, 
757                            const char *smb_name, const char *domain_name,
758                            char *str, size_t len)
759 {
760         char *s;
761         
762         s = alloc_sub_advanced(servicename, user, connectpath,
763                                gid, smb_name, domain_name, str);
764
765         if ( s ) {
766                 strncpy( str, s, len );
767                 SAFE_FREE( s );
768         }
769 }
770
771 /****************************************************************************
772  *  Do some standard substitutions in a string.
773  *  ****************************************************************************/
774
775 void standard_sub_conn(connection_struct *conn, char *str, size_t len)
776 {
777         char *s;
778
779         s = alloc_sub_advanced(lp_servicename(SNUM(conn)), conn->user, conn->connectpath,
780                                conn->gid, smb_user_name, "", str);
781
782         if ( s ) {
783                 strncpy( str, s, len );
784                 SAFE_FREE( s );
785         }
786 }
787