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 OptionGroup(optparse
.OptionGroup
):
175 """Samba OptionGroup base class.
177 Provides a generic set_option method to be used as Option callback,
178 so that one doesn't need to be created for every available Option.
180 Also overrides the add_option method, so it correctly initialises
181 the defaults on the OptionGroup.
184 def add_option(self
, *args
, **kwargs
):
185 """Override add_option so it applies defaults during constructor."""
186 opt
= super().add_option(*args
, **kwargs
)
187 default
= None if opt
.default
== optparse
.NO_DEFAULT
else opt
.default
188 self
.set_option(opt
, opt
.get_opt_string(), default
, self
.parser
)
191 def set_option(self
, option
, opt_str
, arg
, parser
):
192 """Callback to set the attribute based on the Option dest name."""
193 dest
= option
.dest
or option
._long
_opts
[0][2:].replace("-", "_")
194 setattr(self
, dest
, arg
)
197 class SambaOptions(OptionGroup
):
198 """General Samba-related command line options."""
200 def __init__(self
, parser
):
201 from samba
import fault_setup
204 # This removes passwords from the commandline via
205 # setproctitle() but makes no change to python sys.argv so we
206 # can continue to process as normal
208 # get_burnt_commandline returns None if no change is needed
209 new_proctitle
= get_burnt_commandline(sys
.argv
)
210 if new_proctitle
is not None:
213 setproctitle
.setproctitle(new_proctitle
)
215 except ModuleNotFoundError
:
216 msg
= ("WARNING: Using passwords on command line is insecure. "
217 "Installing the setproctitle python module will hide "
218 "these from shortly after program start.\n")
219 sys
.stderr
.write(msg
)
222 from samba
.param
import LoadParm
223 super().__init
__(parser
, "Samba Common Options")
224 self
.add_option("-s", "--configfile", action
="callback",
225 type=str, metavar
="FILE", help="Configuration file",
226 callback
=self
._load
_configfile
)
227 self
.add_option("-d", "--debuglevel", action
="callback",
228 type=str, metavar
="DEBUGLEVEL", help="debug level",
229 callback
=self
._set
_debuglevel
)
230 self
.add_option("--option", action
="callback",
231 type=str, metavar
="OPTION",
232 help="set smb.conf option from command line",
233 callback
=self
._set
_option
)
234 self
.add_option("--realm", action
="callback",
235 type=str, metavar
="REALM", help="set the realm name",
236 callback
=self
._set
_realm
)
237 self
._configfile
= None
238 self
._lp
= LoadParm()
241 def get_loadparm_path(self
):
242 """Return path to the smb.conf file specified on the command line."""
243 return self
._configfile
245 def _load_configfile(self
, option
, opt_str
, arg
, parser
):
246 self
._configfile
= arg
248 def _set_debuglevel(self
, option
, opt_str
, arg
, parser
):
250 self
._lp
.set('debug level', arg
)
252 raise optparse
.OptionValueError(
253 f
"invalid -d/--debug value: '{arg}'")
254 parser
.values
.debuglevel
= arg
256 def _set_realm(self
, option
, opt_str
, arg
, parser
):
258 self
._lp
.set('realm', arg
)
260 raise optparse
.OptionValueError(
261 f
"invalid --realm value: '{arg}'")
264 def _set_option(self
, option
, opt_str
, arg
, parser
):
265 if arg
.find('=') == -1:
266 raise optparse
.OptionValueError(
267 "--option option takes a 'a=b' argument")
268 a
= arg
.split('=', 1)
270 self
._lp
.set(a
[0], a
[1])
271 except Exception as e
:
272 raise optparse
.OptionValueError(
273 "invalid --option option value %r: %s" % (arg
, e
))
275 def get_loadparm(self
):
276 """Return loadparm object with data specified on the command line."""
277 if self
._configfile
is not None:
278 self
._lp
.load(self
._configfile
)
279 elif os
.getenv("SMB_CONF_PATH") is not None:
280 self
._lp
.load(os
.getenv("SMB_CONF_PATH"))
282 self
._lp
.load_default()
286 class Samba3Options(SambaOptions
):
287 """General Samba-related command line options with an s3 param."""
289 def __init__(self
, parser
):
290 super().__init
__(parser
)
291 from samba
.samba3
import param
as s3param
292 self
._lp
= s3param
.get_context()
295 class HostOptions(OptionGroup
):
296 """Command line options for connecting to target host or database."""
298 def __init__(self
, parser
):
299 super().__init
__(parser
, "Host Options")
301 self
.add_option("-H", "--URL",
302 help="LDB URL for database or target server",
303 type=str, metavar
="URL", action
="callback",
304 callback
=self
.set_option
, dest
="H")
307 class VersionOptions(OptionGroup
):
308 """Command line option for printing Samba version."""
309 def __init__(self
, parser
):
310 super().__init
__(parser
, "Version Options")
311 self
.add_option("-V", "--version", action
="callback",
312 callback
=self
._display
_version
,
313 help="Display version number")
315 def _display_version(self
, option
, opt_str
, arg
, parser
):
321 def parse_kerberos_arg_legacy(arg
, opt_str
):
322 if arg
.lower() in ["yes", 'true', '1']:
323 return MUST_USE_KERBEROS
324 elif arg
.lower() in ["no", 'false', '0']:
325 return DONT_USE_KERBEROS
326 elif arg
.lower() in ["auto"]:
327 return AUTO_USE_KERBEROS
329 raise optparse
.OptionValueError("invalid %s option value: %s" %
333 def parse_kerberos_arg(arg
, opt_str
):
334 if arg
.lower() == 'required':
335 return MUST_USE_KERBEROS
336 elif arg
.lower() == 'desired':
337 return AUTO_USE_KERBEROS
338 elif arg
.lower() == 'off':
339 return DONT_USE_KERBEROS
341 raise optparse
.OptionValueError("invalid %s option value: %s" %
345 class CredentialsOptions(OptionGroup
):
346 """Command line options for specifying credentials."""
348 def __init__(self
, parser
, special_name
=None):
349 self
.special_name
= special_name
350 if special_name
is not None:
351 self
.section
= "Credentials Options (%s)" % special_name
353 self
.section
= "Credentials Options"
355 self
.ask_for_password
= True
356 self
.ipaddress
= None
357 self
.machine_pass
= False
358 super().__init
__(parser
, self
.section
)
359 self
._add
_option
("--simple-bind-dn", metavar
="DN", action
="callback",
360 callback
=self
._set
_simple
_bind
_dn
, type=str,
361 help="DN to use for a simple bind")
362 self
._add
_option
("--password", metavar
="PASSWORD", action
="callback",
363 help="Password", type=str, callback
=self
._set
_password
)
364 self
._add
_option
("-U", "--username", metavar
="USERNAME",
365 action
="callback", type=str,
366 help="Username", callback
=self
._parse
_username
)
367 self
._add
_option
("-W", "--workgroup", metavar
="WORKGROUP",
368 action
="callback", type=str,
369 help="Workgroup", callback
=self
._parse
_workgroup
)
370 self
._add
_option
("-N", "--no-pass", action
="callback",
371 help="Don't ask for a password",
372 callback
=self
._set
_no
_password
)
373 self
._add
_option
("", "--ipaddress", metavar
="IPADDRESS",
374 action
="callback", type=str,
375 help="IP address of server",
376 callback
=self
._set
_ipaddress
)
377 self
._add
_option
("-P", "--machine-pass",
379 help="Use stored machine account password",
380 callback
=self
._set
_machine
_pass
)
381 self
._add
_option
("--use-kerberos", metavar
="desired|required|off",
382 action
="callback", type=str,
383 help="Use Kerberos authentication", callback
=self
._set
_kerberos
)
384 self
._add
_option
("--use-krb5-ccache", metavar
="KRB5CCNAME",
385 action
="callback", type=str,
386 help="Kerberos Credentials cache",
387 callback
=self
._set
_krb
5_ccache
)
388 self
._add
_option
("-A", "--authentication-file", metavar
="AUTHFILE",
389 action
="callback", type=str,
390 help="Authentication file",
391 callback
=self
._set
_auth
_file
)
394 self
._add
_option
("-k", "--kerberos", metavar
="KERBEROS",
395 action
="callback", type=str,
396 help="DEPRECATED: Migrate to --use-kerberos", callback
=self
._set
_kerberos
_legacy
)
397 self
.creds
= Credentials()
399 def _add_option(self
, *args1
, **kwargs
):
400 if self
.special_name
is None:
401 return self
.add_option(*args1
, **kwargs
)
405 if not a
.startswith("--"):
407 args2
+= (a
.replace("--", "--%s-" % self
.special_name
),)
408 self
.add_option(*args2
, **kwargs
)
410 def _parse_username(self
, option
, opt_str
, arg
, parser
):
411 self
.creds
.parse_string(arg
)
412 self
.machine_pass
= False
414 def _parse_workgroup(self
, option
, opt_str
, arg
, parser
):
415 self
.creds
.set_domain(arg
)
417 def _set_password(self
, option
, opt_str
, arg
, parser
):
418 self
.creds
.set_password(arg
)
419 self
.ask_for_password
= False
420 self
.machine_pass
= False
422 def _set_no_password(self
, option
, opt_str
, arg
, parser
):
423 self
.ask_for_password
= False
425 def _set_machine_pass(self
, option
, opt_str
, arg
, parser
):
426 self
.machine_pass
= True
428 def _set_ipaddress(self
, option
, opt_str
, arg
, parser
):
431 def _set_kerberos_legacy(self
, option
, opt_str
, arg
, parser
):
432 print('WARNING: The option -k|--kerberos is deprecated!')
433 self
.creds
.set_kerberos_state(parse_kerberos_arg_legacy(arg
, opt_str
))
435 def _set_kerberos(self
, option
, opt_str
, arg
, parser
):
436 self
.creds
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
438 def _set_simple_bind_dn(self
, option
, opt_str
, arg
, parser
):
439 self
.creds
.set_bind_dn(arg
)
441 def _set_krb5_ccache(self
, option
, opt_str
, arg
, parser
):
442 self
.creds
.set_kerberos_state(MUST_USE_KERBEROS
)
443 self
.creds
.set_named_ccache(arg
)
445 def _set_auth_file(self
, option
, opt_str
, arg
, parser
):
446 if os
.path
.exists(arg
):
447 self
.creds
.parse_file(arg
)
448 self
.ask_for_password
= False
449 self
.machine_pass
= False
451 def get_credentials(self
, lp
, fallback_machine
=False):
452 """Obtain the credentials set on the command-line.
454 :param lp: Loadparm object to use.
455 :return: Credentials object
458 if self
.machine_pass
:
459 self
.creds
.set_machine_account(lp
)
460 elif self
.ask_for_password
:
461 self
.creds
.set_cmdline_callbacks()
463 # possibly fallback to using the machine account, if we have
464 # access to the secrets db
465 if fallback_machine
and not self
.creds
.authentication_requested():
467 self
.creds
.set_machine_account(lp
)
474 class CredentialsOptionsDouble(CredentialsOptions
):
475 """Command line options for specifying credentials of two servers."""
477 def __init__(self
, parser
):
478 super().__init
__(parser
)
480 self
.add_option("--simple-bind-dn2", metavar
="DN2", action
="callback",
481 callback
=self
._set
_simple
_bind
_dn
2, type=str,
482 help="DN to use for a simple bind")
483 self
.add_option("--password2", metavar
="PASSWORD2", action
="callback",
484 help="Password", type=str,
485 callback
=self
._set
_password
2)
486 self
.add_option("--username2", metavar
="USERNAME2",
487 action
="callback", type=str,
488 help="Username for second server",
489 callback
=self
._parse
_username
2)
490 self
.add_option("--workgroup2", metavar
="WORKGROUP2",
491 action
="callback", type=str,
492 help="Workgroup for second server",
493 callback
=self
._parse
_workgroup
2)
494 self
.add_option("--no-pass2", action
="store_true",
495 help="Don't ask for a password for the second server")
496 self
.add_option("--use-kerberos2", metavar
="desired|required|off",
497 action
="callback", type=str,
498 help="Use Kerberos authentication", callback
=self
._set
_kerberos
2)
501 self
.add_option("--kerberos2", metavar
="KERBEROS2",
502 action
="callback", type=str,
503 help="Use Kerberos", callback
=self
._set
_kerberos
2_legacy
)
504 self
.creds2
= Credentials()
506 def _parse_username2(self
, option
, opt_str
, arg
, parser
):
507 self
.creds2
.parse_string(arg
)
509 def _parse_workgroup2(self
, option
, opt_str
, arg
, parser
):
510 self
.creds2
.set_domain(arg
)
512 def _set_password2(self
, option
, opt_str
, arg
, parser
):
513 self
.creds2
.set_password(arg
)
514 self
.no_pass2
= False
516 def _set_kerberos2_legacy(self
, option
, opt_str
, arg
, parser
):
517 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
519 def _set_kerberos2(self
, option
, opt_str
, arg
, parser
):
520 self
.creds2
.set_kerberos_state(parse_kerberos_arg(arg
, opt_str
))
522 def _set_simple_bind_dn2(self
, option
, opt_str
, arg
, parser
):
523 self
.creds2
.set_bind_dn(arg
)
525 def get_credentials2(self
, lp
, guess
=True):
526 """Obtain the credentials set on the command-line.
528 :param lp: Loadparm object to use.
529 :param guess: Try guess Credentials from environment
530 :return: Credentials object
533 self
.creds2
.guess(lp
)
534 elif not self
.creds2
.get_username():
535 self
.creds2
.set_anonymous()
538 self
.creds2
.set_cmdline_callbacks()