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