1 # Samba-specific bits for optparse
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 """Support for parsing Samba-related command-line options."""
20 __docformat__
= "restructuredText"
25 from abc
import ABCMeta
, abstractmethod
28 from samba
.credentials
import (
34 from samba
._glue
import get_burnt_commandline
37 def check_bytes(option
, opt
, value
):
38 """Custom option type to allow the input of sizes using byte, kb, mb ...
40 units, e.g. 2Gb, 4KiB ...
41 e.g. Option("--size", type="bytes", metavar="SIZE")
44 multipliers
= {"B": 1,
47 "GB": 1024 * 1024 * 1024}
49 # strip out any spaces
50 v
= value
.replace(" ", "")
52 # extract the numeric prefix
54 while v
and v
[0:1].isdigit() or v
[0:1] == '.':
61 msg
= ("{0} option requires a numeric value, "
62 "with an optional unit suffix").format(opt
)
63 raise optparse
.OptionValueError(msg
)
65 # strip out the 'i' and convert to upper case so
66 # kib Kib kb KB are all equivalent
67 suffix
= v
.upper().replace("I", "")
69 return m
* multipliers
[suffix
]
71 msg
= ("{0} invalid suffix '{1}', "
72 "should be B, Kb, Mb or Gb").format(opt
, v
)
73 raise optparse
.OptionValueError(msg
)
76 class OptionMissingError(optparse
.OptionValueError
):
77 """One or more Options with required=True is missing."""
79 def __init__(self
, options
):
80 """Raised when required Options are missing from the command line.
82 :param options: list of 1 or more option
84 self
.options
= options
87 if len(self
.options
) == 1:
88 missing
= self
.options
[0]
89 return f
"Argument {missing} is required."
91 options
= sorted([str(option
) for option
in self
.options
])
92 missing
= ", ".join(options
)
93 return f
"The arguments {missing} are required."
96 class ValidationError(Exception):
97 """ValidationError is the exception raised by validators.
99 Should be raised from the __call__ method of the Validator subclass.
104 class Validator(metaclass
=ABCMeta
):
105 """Base class for Validators used by SambaOption.
107 Subclass this to make custom validators and implement __call__.
111 def __call__(self
, field
, value
):
115 class Option(optparse
.Option
):
116 ATTRS
= optparse
.Option
.ATTRS
+ ["required", "validators"]
117 TYPES
= optparse
.Option
.TYPES
+ ("bytes",)
118 TYPE_CHECKER
= copy(optparse
.Option
.TYPE_CHECKER
)
119 TYPE_CHECKER
["bytes"] = check_bytes
121 def run_validators(self
, opt
, value
):
122 """Runs the list of validators on the current option."""
123 validators
= getattr(self
, "validators") or []
124 for validator
in validators
:
125 validator(opt
, value
)
127 def convert_value(self
, opt
, value
):
128 """Override convert_value to run validators just after.
130 This can also be done in process() but there we would have to
131 replace the entire method.
133 value
= super().convert_value(opt
, value
)
134 self
.run_validators(opt
, value
)
138 class OptionParser(optparse
.OptionParser
):
139 """Samba OptionParser, adding support for required=True on Options."""
146 conflict_handler
="error",
149 add_help_option
=True,
153 Ensure that option_class defaults to the Samba one.
155 super().__init
__(usage
, option_list
, option_class
, version
,
156 conflict_handler
, description
, formatter
,
157 add_help_option
, prog
, epilog
)
159 def check_values(self
, values
, args
):
160 """Loop through required options if value is missing raise exception."""
162 for option
in self
._get
_all
_options
():
164 value
= getattr(values
, option
.dest
)
166 missing
.append(option
)
169 raise OptionMissingError(missing
)
171 return super().check_values(values
, args
)
174 class SambaOptions(optparse
.OptionGroup
):
175 """General Samba-related command line options."""
177 def __init__(self
, parser
):
178 from samba
import fault_setup
181 # This removes passwords from the commandline via
182 # setproctitle() but makes no change to python sys.argv so we
183 # can continue to process as normal
185 # get_burnt_commandline returns None if no change is needed
186 new_proctitle
= get_burnt_commandline(sys
.argv
)
187 if new_proctitle
is not None:
190 setproctitle
.setproctitle(new_proctitle
)
192 except ModuleNotFoundError
:
193 msg
= ("WARNING: Using passwords on command line is insecure. "
194 "Installing the setproctitle python module will hide "
195 "these from shortly after program start.\n")
196 sys
.stderr
.write(msg
)
199 from samba
.param
import LoadParm
200 super().__init
__(parser
, "Samba Common Options")
201 self
.add_option("-s", "--configfile", action
="callback",
202 type=str, metavar
="FILE", help="Configuration file",
203 callback
=self
._load
_configfile
)
204 self
.add_option("-d", "--debuglevel", action
="callback",
205 type=str, metavar
="DEBUGLEVEL", help="debug level",
206 callback
=self
._set
_debuglevel
)
207 self
.add_option("--option", action
="callback",
208 type=str, metavar
="OPTION",
209 help="set smb.conf option from command line",
210 callback
=self
._set
_option
)
211 self
.add_option("--realm", action
="callback",
212 type=str, metavar
="REALM", help="set the realm name",
213 callback
=self
._set
_realm
)
214 self
._configfile
= None
215 self
._lp
= LoadParm()
218 def get_loadparm_path(self
):
219 """Return path to the smb.conf file specified on the command line."""
220 return self
._configfile
222 def _load_configfile(self
, option
, opt_str
, arg
, parser
):
223 self
._configfile
= arg
225 def _set_debuglevel(self
, option
, opt_str
, arg
, parser
):
227 self
._lp
.set('debug level', arg
)
229 raise optparse
.OptionValueError(
230 f
"invalid -d/--debug value: '{arg}'")
231 parser
.values
.debuglevel
= arg
233 def _set_realm(self
, option
, opt_str
, arg
, parser
):
235 self
._lp
.set('realm', arg
)
237 raise optparse
.OptionValueError(
238 f
"invalid --realm value: '{arg}'")
241 def _set_option(self
, option
, opt_str
, arg
, parser
):
242 if arg
.find('=') == -1:
243 raise optparse
.OptionValueError(
244 "--option option takes a 'a=b' argument")
245 a
= arg
.split('=', 1)
247 self
._lp
.set(a
[0], a
[1])
248 except Exception as e
:
249 raise optparse
.OptionValueError(
250 "invalid --option option value %r: %s" % (arg
, e
))
252 def get_loadparm(self
):
253 """Return loadparm object with data specified on the command line."""
254 if self
._configfile
is not None:
255 self
._lp
.load(self
._configfile
)
256 elif os
.getenv("SMB_CONF_PATH") is not None:
257 self
._lp
.load(os
.getenv("SMB_CONF_PATH"))
259 self
._lp
.load_default()
263 class Samba3Options(SambaOptions
):
264 """General Samba-related command line options with an s3 param."""
266 def __init__(self
, parser
):
267 super().__init
__(parser
)
268 from samba
.samba3
import param
as s3param
269 self
._lp
= s3param
.get_context()
272 class HostOptions(optparse
.OptionGroup
):
273 """Command line options for connecting to target host or database."""
275 def __init__(self
, parser
):
276 super().__init
__(parser
, "Host Options")
279 self
.add_option("-H", "--URL",
280 help="LDB URL for database or target server",
281 type=str, metavar
="URL", action
="callback",
282 callback
=self
._set
_H
, dest
="H")
284 def _set_H(self
, option
, opt_str
, arg
, parser
):
285 parser
.values
.H
= self
.H
= arg
288 class VersionOptions(optparse
.OptionGroup
):
289 """Command line option for printing Samba version."""
290 def __init__(self
, parser
):
291 super().__init
__(parser
, "Version Options")
292 self
.add_option("-V", "--version", action
="callback",
293 callback
=self
._display
_version
,
294 help="Display version number")
296 def _display_version(self
, option
, opt_str
, arg
, parser
):
302 def parse_kerberos_arg_legacy(arg
, opt_str
):
303 if arg
.lower() in ["yes", 'true', '1']:
304 return MUST_USE_KERBEROS
305 elif arg
.lower() in ["no", 'false', '0']:
306 return DONT_USE_KERBEROS
307 elif arg
.lower() in ["auto"]:
308 return AUTO_USE_KERBEROS
310 raise optparse
.OptionValueError("invalid %s option value: %s" %
314 def parse_kerberos_arg(arg
, opt_str
):
315 if arg
.lower() == 'required':
316 return MUST_USE_KERBEROS
317 elif arg
.lower() == 'desired':
318 return AUTO_USE_KERBEROS
319 elif arg
.lower() == 'off':
320 return DONT_USE_KERBEROS
322 raise optparse
.OptionValueError("invalid %s option value: %s" %
326 class CredentialsOptions(optparse
.OptionGroup
):
327 """Command line options for specifying credentials."""
329 def __init__(self
, parser
, special_name
=None):
330 self
.special_name
= special_name
331 if special_name
is not None:
332 self
.section
= "Credentials Options (%s)" % special_name
334 self
.section
= "Credentials Options"
336 self
.ask_for_password
= True
337 self
.ipaddress
= None
338 self
.machine_pass
= False
339 super().__init
__(parser
, self
.section
)
340 self
._add
_option
("--simple-bind-dn", metavar
="DN", action
="callback",
341 callback
=self
._set
_simple
_bind
_dn
, type=str,
342 help="DN to use for a simple bind")
343 self
._add
_option
("--password", metavar
="PASSWORD", action
="callback",
344 help="Password", type=str, callback
=self
._set
_password
)
345 self
._add
_option
("-U", "--username", metavar
="USERNAME",
346 action
="callback", type=str,
347 help="Username", callback
=self
._parse
_username
)
348 self
._add
_option
("-W", "--workgroup", metavar
="WORKGROUP",
349 action
="callback", type=str,
350 help="Workgroup", callback
=self
._parse
_workgroup
)
351 self
._add
_option
("-N", "--no-pass", action
="callback",
352 help="Don't ask for a password",
353 callback
=self
._set
_no
_password
)
354 self
._add
_option
("", "--ipaddress", metavar
="IPADDRESS",
355 action
="callback", type=str,
356 help="IP address of server",
357 callback
=self
._set
_ipaddress
)
358 self
._add
_option
("-P", "--machine-pass",
360 help="Use stored machine account password",
361 callback
=self
._set
_machine
_pass
)
362 self
._add
_option
("--use-kerberos", metavar
="desired|required|off",
363 action
="callback", type=str,
364 help="Use Kerberos authentication", callback
=self
._set
_kerberos
)
365 self
._add
_option
("--use-krb5-ccache", metavar
="KRB5CCNAME",
366 action
="callback", type=str,
367 help="Kerberos Credentials cache",
368 callback
=self
._set
_krb
5_ccache
)
369 self
._add
_option
("-A", "--authentication-file", metavar
="AUTHFILE",
370 action
="callback", type=str,
371 help="Authentication file",
372 callback
=self
._set
_auth
_file
)
375 self
._add
_option
("-k", "--kerberos", metavar
="KERBEROS",
376 action
="callback", type=str,
377 help="DEPRECATED: Migrate to --use-kerberos", callback
=self
._set
_kerberos
_legacy
)
378 self
.creds
= Credentials()
380 def _add_option(self
, *args1
, **kwargs
):
381 if self
.special_name
is None:
382 return self
.add_option(*args1
, **kwargs
)
386 if not a
.startswith("--"):
388 args2
+= (a
.replace("--", "--%s-" % self
.special_name
),)
389 self
.add_option(*args2
, **kwargs
)
391 def _parse_username(self
, option
, opt_str
, arg
, parser
):
392 self
.creds
.parse_string(arg
)
393 self
.machine_pass
= False
395 def _parse_workgroup(self
, option
, opt_str
, arg
, parser
):
396 self
.creds
.set_domain(arg
)
398 def _set_password(self
, option
, opt_str
, arg
, parser
):
399 self
.creds
.set_password(arg
)
400 self
.ask_for_password
= False
401 self
.machine_pass
= False
403 def _set_no_password(self
, option
, opt_str
, arg
, parser
):
404 self
.ask_for_password
= False
406 def _set_machine_pass(self
, option
, opt_str
, arg
, parser
):
407 self
.machine_pass
= True
409 def _set_ipaddress(self
, option
, opt_str
, arg
, parser
):
412 def _set_kerberos_legacy(self
, option
, opt_str
, arg
, parser
):
413 print('WARNING: The option -k|--kerberos is deprecated!')
414 self
.creds
.set_kerberos_state(parse_kerberos_arg_legacy(arg
, opt_str
))
416 def _set_kerberos(self
, option
, opt_str
, arg
, parser
):
417 self
.creds
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
419 def _set_simple_bind_dn(self
, option
, opt_str
, arg
, parser
):
420 self
.creds
.set_bind_dn(arg
)
422 def _set_krb5_ccache(self
, option
, opt_str
, arg
, parser
):
423 self
.creds
.set_kerberos_state(MUST_USE_KERBEROS
)
424 self
.creds
.set_named_ccache(arg
)
426 def _set_auth_file(self
, option
, opt_str
, arg
, parser
):
427 if os
.path
.exists(arg
):
428 self
.creds
.parse_file(arg
)
429 self
.ask_for_password
= False
430 self
.machine_pass
= False
432 def get_credentials(self
, lp
, fallback_machine
=False):
433 """Obtain the credentials set on the command-line.
435 :param lp: Loadparm object to use.
436 :return: Credentials object
439 if self
.machine_pass
:
440 self
.creds
.set_machine_account(lp
)
441 elif self
.ask_for_password
:
442 self
.creds
.set_cmdline_callbacks()
444 # possibly fallback to using the machine account, if we have
445 # access to the secrets db
446 if fallback_machine
and not self
.creds
.authentication_requested():
448 self
.creds
.set_machine_account(lp
)
455 class CredentialsOptionsDouble(CredentialsOptions
):
456 """Command line options for specifying credentials of two servers."""
458 def __init__(self
, parser
):
459 super().__init
__(parser
)
461 self
.add_option("--simple-bind-dn2", metavar
="DN2", action
="callback",
462 callback
=self
._set
_simple
_bind
_dn
2, type=str,
463 help="DN to use for a simple bind")
464 self
.add_option("--password2", metavar
="PASSWORD2", action
="callback",
465 help="Password", type=str,
466 callback
=self
._set
_password
2)
467 self
.add_option("--username2", metavar
="USERNAME2",
468 action
="callback", type=str,
469 help="Username for second server",
470 callback
=self
._parse
_username
2)
471 self
.add_option("--workgroup2", metavar
="WORKGROUP2",
472 action
="callback", type=str,
473 help="Workgroup for second server",
474 callback
=self
._parse
_workgroup
2)
475 self
.add_option("--no-pass2", action
="store_true",
476 help="Don't ask for a password for the second server")
477 self
.add_option("--use-kerberos2", metavar
="desired|required|off",
478 action
="callback", type=str,
479 help="Use Kerberos authentication", callback
=self
._set
_kerberos
2)
482 self
.add_option("--kerberos2", metavar
="KERBEROS2",
483 action
="callback", type=str,
484 help="Use Kerberos", callback
=self
._set
_kerberos
2_legacy
)
485 self
.creds2
= Credentials()
487 def _parse_username2(self
, option
, opt_str
, arg
, parser
):
488 self
.creds2
.parse_string(arg
)
490 def _parse_workgroup2(self
, option
, opt_str
, arg
, parser
):
491 self
.creds2
.set_domain(arg
)
493 def _set_password2(self
, option
, opt_str
, arg
, parser
):
494 self
.creds2
.set_password(arg
)
495 self
.no_pass2
= False
497 def _set_kerberos2_legacy(self
, option
, opt_str
, arg
, parser
):
498 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
500 def _set_kerberos2(self
, option
, opt_str
, arg
, parser
):
501 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
503 def _set_simple_bind_dn2(self
, option
, opt_str
, arg
, parser
):
504 self
.creds2
.set_bind_dn(arg
)
506 def get_credentials2(self
, lp
, guess
=True):
507 """Obtain the credentials set on the command-line.
509 :param lp: Loadparm object to use.
510 :param guess: Try guess Credentials from environment
511 :return: Credentials object
514 self
.creds2
.guess(lp
)
515 elif not self
.creds2
.get_username():
516 self
.creds2
.set_anonymous()
519 self
.creds2
.set_cmdline_callbacks()