r2640: valgrind does a great job on some types of memory leaks, but is slow
[amitay/samba.git] / source4 / lib / cmdline / popt_common.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Common popt routines
4
5    Copyright (C) Tim Potter 2001,2002
6    Copyright (C) Jelmer Vernooij 2002,2003
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 /* Handle command line options:
26  *              -d,--debuglevel 
27  *              -s,--configfile 
28  *              -O,--socket-options 
29  *              -V,--version
30  *              -l,--log-base
31  *              -n,--netbios-name
32  *              -W,--workgroup
33  *              -i,--scope
34  */
35
36
37 enum {OPT_OPTION=1,OPT_LEAK_CHECK=2};
38
39 static struct cmdline_auth_info cmdline_auth_info;
40
41 static void popt_common_callback(poptContext con, 
42                            enum poptCallbackReason reason,
43                            const struct poptOption *opt,
44                            const char *arg, const void *data)
45 {
46         const char *pname;
47         
48         /* Find out basename of current program */
49         pname = strrchr_m(poptGetInvocationName(con),'/');
50
51         if (!pname)
52                 pname = poptGetInvocationName(con);
53         else 
54                 pname++;
55
56         if (reason == POPT_CALLBACK_REASON_PRE) {
57                 char *logfile = talloc_asprintf(NULL, "%s/log.%s", dyn_LOGFILEBASE, pname);
58                 lp_set_cmdline("log file", logfile);
59                 talloc_free(logfile);
60                 return;
61         }
62
63         switch(opt->val) {
64         case 'd':
65                 lp_set_cmdline("log level", arg);
66                 break;
67
68         case 'V':
69                 printf( "Version %s\n", SAMBA_VERSION_STRING );
70                 exit(0);
71                 break;
72
73         case 'O':
74                 if (arg) {
75                         lp_set_cmdline("socket options", arg);
76                 }
77                 break;
78
79         case 's':
80                 if (arg) {
81                         pstrcpy(dyn_CONFIGFILE, arg);
82                 }
83                 break;
84
85         case 'l':
86                 if (arg) {
87                         char *logfile = talloc_asprintf(NULL, "%s/log.%s", arg, pname);
88                         lp_set_cmdline("log file", logfile);
89                         talloc_free(logfile);
90                 }
91                 break;
92                 
93         case 'W':
94                 lp_set_cmdline("workgroup", arg);
95                 break;
96                 
97         case 'n':
98                 lp_set_cmdline("netbios name", arg);
99                 break;
100                 
101         case 'i':
102                 lp_set_cmdline("netbios scope", arg);
103                 break;
104
105         case 'm':
106                 lp_set_cmdline("max protocol", arg);
107                 break;
108
109         case 'R':
110                 lp_set_cmdline("name resolve order", arg);
111                 break;
112
113         case OPT_OPTION:
114                 if (!lp_set_option(arg)) {
115                         fprintf(stderr, "Error setting option '%s'\n", arg);
116                         exit(1);
117                 }
118                 break;
119
120         case OPT_LEAK_CHECK:
121                 talloc_enable_leak_check();
122                 break;
123         }
124 }
125
126 struct poptOption popt_common_connection[] = {
127         { NULL, 0, POPT_ARG_CALLBACK, popt_common_callback },
128         { "name-resolve", 'R', POPT_ARG_STRING, NULL, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
129         { "socket-options", 'O', POPT_ARG_STRING, NULL, 'O', "socket options to use", "SOCKETOPTIONS" },
130         { "netbiosname", 'n', POPT_ARG_STRING, NULL, 'n', "Primary netbios name", "NETBIOSNAME" },
131         { "workgroup", 'W', POPT_ARG_STRING, NULL, 'W', "Set the workgroup name", "WORKGROUP" },
132         { "scope", 'i', POPT_ARG_STRING, NULL, 'i', "Use this Netbios scope", "SCOPE" },
133         { "maxprotocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set max protocol level", "MAXPROTOCOL" },
134         POPT_TABLEEND
135 };
136
137 struct poptOption popt_common_samba[] = {
138         { NULL, 0, POPT_ARG_CALLBACK|POPT_CBFLAG_PRE, popt_common_callback },
139         { "debuglevel",   'd', POPT_ARG_STRING, NULL, 'd', "Set debug level", "DEBUGLEVEL" },
140         { "configfile",   's', POPT_ARG_STRING, NULL, 's', "Use alternative configuration file", "CONFIGFILE" },
141         { "option",         0, POPT_ARG_STRING, NULL, OPT_OPTION, "Set smb.conf option from command line", "name=value" },
142         { "log-basename", 'l', POPT_ARG_STRING, NULL, 'l', "Basename for log/debug files", "LOGFILEBASE" },
143         { "leak-check",     0, POPT_ARG_NONE, NULL, OPT_LEAK_CHECK, "enable talloc leak checking", NULL },
144         POPT_TABLEEND
145 };
146
147 struct poptOption popt_common_version[] = {
148         { NULL, 0, POPT_ARG_CALLBACK, popt_common_callback },
149         { "version", 'V', POPT_ARG_NONE, NULL, 'V', "Print version" },
150         POPT_TABLEEND
151 };
152
153
154
155 /****************************************************************************
156  * get a password from a a file or file descriptor
157  * exit on failure
158  * ****************************************************************************/
159 static void get_password_file(struct cmdline_auth_info *a)
160 {
161         int fd = -1;
162         char *p;
163         BOOL close_it = False;
164         pstring spec;
165         char pass[128];
166
167         if ((p = getenv("PASSWD_FD")) != NULL) {
168                 pstrcpy(spec, "descriptor ");
169                 pstrcat(spec, p);
170                 sscanf(p, "%d", &fd);
171                 close_it = False;
172         } else if ((p = getenv("PASSWD_FILE")) != NULL) {
173                 fd = sys_open(p, O_RDONLY, 0);
174                 pstrcpy(spec, p);
175                 if (fd < 0) {
176                         fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
177                                         spec, strerror(errno));
178                         exit(1);
179                 }
180                 close_it = True;
181         }
182
183         for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
184                 p && p - pass < sizeof(pass);) {
185                 switch (read(fd, p, 1)) {
186                 case 1:
187                         if (*p != '\n' && *p != '\0') {
188                                 *++p = '\0'; /* advance p, and null-terminate pass */
189                                 break;
190                         }
191                 case 0:
192                         if (p - pass) {
193                                 *p = '\0'; /* null-terminate it, just in case... */
194                                 p = NULL; /* then force the loop condition to become false */
195                                 break;
196                         } else {
197                                 fprintf(stderr, "Error reading password from file %s: %s\n",
198                                                 spec, "empty password\n");
199                                 exit(1);
200                         }
201
202                 default:
203                         fprintf(stderr, "Error reading password from file %s: %s\n",
204                                         spec, strerror(errno));
205                         exit(1);
206                 }
207         }
208         pstrcpy(a->password, pass);
209         if (close_it)
210                 close(fd);
211 }
212
213 static void get_credentials_file(const char *file, struct cmdline_auth_info *info) 
214 {
215         XFILE *auth;
216         fstring buf;
217         uint16_t len = 0;
218         char *ptr, *val, *param;
219
220         if ((auth=x_fopen(file, O_RDONLY, 0)) == NULL)
221         {
222                 /* fail if we can't open the credentials file */
223                 d_printf("ERROR: Unable to open credentials file!\n");
224                 exit(-1);
225         }
226
227         while (!x_feof(auth))
228         {
229                 /* get a line from the file */
230                 if (!x_fgets(buf, sizeof(buf), auth))
231                         continue;
232                 len = strlen(buf);
233
234                 if ((len) && (buf[len-1]=='\n'))
235                 {
236                         buf[len-1] = '\0';
237                         len--;
238                 }
239                 if (len == 0)
240                         continue;
241
242                 /* break up the line into parameter & value.
243                  * will need to eat a little whitespace possibly */
244                 param = buf;
245                 if (!(ptr = strchr_m (buf, '=')))
246                         continue;
247
248                 val = ptr+1;
249                 *ptr = '\0';
250
251                 /* eat leading white space */
252                 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
253                         val++;
254
255                 if (strwicmp("password", param) == 0)
256                 {
257                         pstrcpy(info->password, val);
258                         info->got_pass = True;
259                 }
260                 else if (strwicmp("username", param) == 0)
261                         pstrcpy(info->username, val);
262                 else if (strwicmp("domain", param) == 0)
263                         pstrcpy(info->domain,val);
264                 memset(buf, 0, sizeof(buf));
265         }
266         x_fclose(auth);
267 }
268
269 /* Handle command line options:
270  *              -U,--user
271  *              -A,--authentication-file
272  *              -k,--use-kerberos
273  *              -N,--no-pass
274  *              -S,--signing
275  *              -P --machine-pass
276  */
277
278
279 static void popt_common_credentials_callback(poptContext con, 
280                                                 enum poptCallbackReason reason,
281                                                 const struct poptOption *opt,
282                                                 const char *arg, const void *data)
283 {
284         char *p;
285
286         if (reason == POPT_CALLBACK_REASON_PRE) {
287                 cmdline_auth_info.use_kerberos = False;
288                 cmdline_auth_info.got_pass = False;
289                 pstrcpy(cmdline_auth_info.username, "GUEST");   
290
291                 if (getenv("LOGNAME"))pstrcpy(cmdline_auth_info.username,getenv("LOGNAME"));
292
293                 if (getenv("USER")) {
294                         pstring tmp;
295
296                         pstrcpy(cmdline_auth_info.username,getenv("USER"));
297
298                         pstrcpy(tmp,cmdline_auth_info.username);
299                         if ((p = strchr_m(tmp,'\\'))) {
300                                 *p = 0;
301                                 pstrcpy(cmdline_auth_info.domain,tmp);
302                                 pstrcpy(cmdline_auth_info.username,p+1);
303                         }
304
305                         if ((p = strchr_m(cmdline_auth_info.username,'%'))) {
306                                 *p = 0;
307                                 pstrcpy(cmdline_auth_info.password,p+1);
308                                 cmdline_auth_info.got_pass = True;
309                                 memset(strchr_m(getenv("USER"),'%')+1,'X',strlen(cmdline_auth_info.password));
310                         }
311                 }
312
313                 if (getenv("DOMAIN")) {
314                         pstrcpy(cmdline_auth_info.domain,getenv("DOMAIN"));
315                 }
316
317                 if (getenv("PASSWD")) {
318                         pstrcpy(cmdline_auth_info.password,getenv("PASSWD"));
319                         cmdline_auth_info.got_pass = True;
320                 }
321
322                 if (getenv("PASSWD_FD") || getenv("PASSWD_FILE")) {
323                         get_password_file(&cmdline_auth_info);
324                         cmdline_auth_info.got_pass = True;
325                 }
326
327                 return;
328         }
329
330         switch(opt->val) {
331         case 'U':
332                 {
333                         char *lp;
334                         pstring tmp;
335
336                         pstrcpy(cmdline_auth_info.username,arg);
337
338                         pstrcpy(tmp,cmdline_auth_info.username);
339                         if ((p = strchr_m(tmp,'\\'))) {
340                                 *p = 0;
341                                 pstrcpy(cmdline_auth_info.domain,tmp);
342                                 pstrcpy(cmdline_auth_info.username,p+1);
343                         }
344
345                         if ((lp=strchr_m(cmdline_auth_info.username,'%'))) {
346                                 *lp = 0;
347                                 pstrcpy(cmdline_auth_info.password,lp+1);
348                                 cmdline_auth_info.got_pass = True;
349                                 memset(strchr_m(arg,'%')+1,'X',strlen(cmdline_auth_info.password));
350                         }
351                 }
352                 break;
353
354         case 'A':
355                 get_credentials_file(arg, &cmdline_auth_info);
356                 break;
357
358         case 'k':
359 #ifndef HAVE_KRB5
360                 d_printf("No kerberos support compiled in\n");
361                 exit(1);
362 #else
363                 cmdline_auth_info.use_kerberos = True;
364                 cmdline_auth_info.got_pass = True;
365 #endif
366                 break;
367
368         case 'S':
369                 lp_set_cmdline("client signing", arg);
370                 break;
371
372         case 'P':
373                 {
374                         char *opt_password = NULL;
375                         /* it is very useful to be able to make ads queries as the
376                            machine account for testing purposes and for domain leave */
377                         
378                         if (!secrets_init()) {
379                                 d_printf("ERROR: Unable to open secrets database\n");
380                                 exit(1);
381                         }
382                         
383                         opt_password = secrets_fetch_machine_password(lp_workgroup());
384                         
385                         if (!opt_password) {
386                                 d_printf("ERROR: Unable to fetch machine password\n");
387                                 exit(1);
388                         }
389                         pstr_sprintf(cmdline_auth_info.username, "%s$", 
390                                      lp_netbios_name());
391                         pstrcpy(cmdline_auth_info.password,opt_password);
392                         SAFE_FREE(opt_password);
393
394                         pstrcpy(cmdline_auth_info.password, lp_workgroup());
395
396                         /* machine accounts only work with kerberos */
397                         cmdline_auth_info.use_kerberos = True;
398                         cmdline_auth_info.got_pass = True;
399                 }
400                 break;
401         }
402 }
403
404
405
406 struct poptOption popt_common_credentials[] = {
407         { NULL, 0, POPT_ARG_CALLBACK|POPT_CBFLAG_PRE, popt_common_credentials_callback },
408         { "user", 'U', POPT_ARG_STRING, NULL, 'U', "Set the network username", "USERNAME" },
409         { "no-pass", 'N', POPT_ARG_NONE, &cmdline_auth_info.got_pass, 0, "Don't ask for a password" },
410         { "kerberos", 'k', POPT_ARG_NONE, &cmdline_auth_info.use_kerberos, 'k', "Use kerberos (active directory) authentication" },
411         { "authentication-file", 'A', POPT_ARG_STRING, NULL, 'A', "Get the credentials from a file", "FILE" },
412         { "signing", 'S', POPT_ARG_STRING, NULL, 'S', "Set the client signing state", "on|off|required" },
413         { "machine-pass", 'P', POPT_ARG_NONE, NULL, 'P', "Use stored machine account password" },
414         POPT_TABLEEND
415 };
416
417 void cmdline_set_username(const char *name)
418 {
419         pstrcpy(cmdline_auth_info.username, name);
420 }
421
422 const char *cmdline_get_username(void)
423 {
424         return cmdline_auth_info.username;
425 }
426
427 void cmdline_set_userdomain(const char *domain)
428 {
429         pstrcpy(cmdline_auth_info.domain, domain);
430 }
431
432 const char *cmdline_get_userdomain(void)
433 {
434         if (cmdline_auth_info.domain[0]) {
435                 return cmdline_auth_info.domain;
436         }
437
438         /* I think this should be lp_netbios_name() 
439          * instead of lp_workgroup(), because if you're logged in 
440          * as domain user the getenv("USER") contains the domain
441          * and this code path isn't used
442          * --metze
443          */
444         return lp_netbios_name();
445 }
446
447 const char *cmdline_get_userpassword(void)
448 {
449         pstring prompt;
450
451         if (cmdline_auth_info.got_pass) {
452                 return cmdline_auth_info.password;
453         }
454
455         pstr_sprintf(prompt, "Password for [%s\\%s]:", 
456                         cmdline_get_userdomain(),
457                         cmdline_get_username());
458
459         return getpass(prompt);
460 }
461
462 void cmdline_set_userpassword(const char *pass)
463 {
464         cmdline_auth_info.got_pass = True;
465         pstrcpy(cmdline_auth_info.password, pass);
466 }
467
468 void cmdline_set_use_kerberos(BOOL use_kerberos)
469 {
470         cmdline_auth_info.use_kerberos = use_kerberos;
471 }
472
473 BOOL cmdline_get_use_kerberos(void)
474 {
475         return cmdline_auth_info.use_kerberos;
476 }