Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
PYthon 3: use bytearrays instead of strings (str)
Should work with Python 2 (>= 2.6) and Python 3.
  • Loading branch information
joergsteffens committed Apr 25, 2016
1 parent a92ba26 commit 3c3b7a5
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 36 deletions.
13 changes: 9 additions & 4 deletions bareos/bsock/bsock.py
Expand Up @@ -35,9 +35,9 @@ def __call(self, command, count):
Call a bareos-director user agent command.
If connection is lost, try to reconnect.
'''
result = ''
result = b''
try:
self.send(str(command))
self.send(bytearray(command, 'utf-8'))
result = self.recv_msg()
except (SocketEmptyHeader, ConnectionLostError) as e:
self.logger.error("connection problem (%s): %s" % (type(e).__name__, str(e)))
Expand All @@ -58,7 +58,12 @@ def interactive(self):
self._set_state_director_prompt()
command = ""
while command != "exit" and command != "quit":
command = raw_input(">>")
# Python2: raw_input, Python3: input
try:
myinput = raw_input
except NameError:
myinput = input
command = myinput(">>")
resultmsg = self.call(command)
sys.stdout.write(resultmsg)
sys.stdout.write(resultmsg.decode('utf-8'))
return True
11 changes: 8 additions & 3 deletions bareos/bsock/bsockjson.py
Expand Up @@ -26,7 +26,7 @@ def call(self, command):
json = self.call_fullresult(command)
if json == None:
return
if json.has_key('result'):
if 'result' in json:
result = json['result']
else:
# TODO: or raise an exception?
Expand All @@ -38,8 +38,9 @@ def call_fullresult(self, command):
resultstring = super(BSockJson, self).call(command)
data = None
if resultstring:
print(resultstring.decode('utf-8'))
try:
data = json.loads(resultstring)
data = json.loads(resultstring.decode('utf-8'))
except ValueError as e:
# in case result is not valid json,
# create a JSON-RPC wrapper
Expand All @@ -60,7 +61,11 @@ def interactive(self):
self._set_state_director_prompt()
command = ""
while command != "exit" and command != "quit":
command = raw_input(">>")
try:
myinput = raw_input
except NameError:
myinput = input
command = myinput(">>")
if command:
pprint(self.call(command))
return True
Expand Down
40 changes: 23 additions & 17 deletions bareos/bsock/lowlevel.py
Expand Up @@ -115,7 +115,7 @@ def send(self, msg=None):
try:
# convert to network flow
self.socket.sendall(struct.pack("!i", msg_len) + msg)
self.logger.debug("%s" %(msg.encode('string-escape')))
self.logger.debug("%s" %(msg))
except socket.error as e:
self._handleSocketError(e)

Expand All @@ -136,7 +136,7 @@ def recv(self):
def recv_msg(self):
'''will receive data from director '''
self.__check_socket_connection()
msg = ""
msg = b""
try:
timeouts = 0
while True:
Expand Down Expand Up @@ -166,7 +166,7 @@ def recv_msg(self):

def recv_submsg(self, length):
# get the message
msg = ""
msg = b""
while length > 0:
self.logger.debug(" submsg len: " + str(length))
# TODO
Expand All @@ -175,6 +175,10 @@ def recv_submsg(self, length):
length -= len(submsg)
#self.logger.debug(submsg)
msg += submsg
if (type(msg) is str):
msg = bytearray(msg, 'utf-8')
if (type(msg) is bytes):
msg = bytearray(msg)
return msg


Expand Down Expand Up @@ -213,21 +217,23 @@ def _cram_md5_challenge(self, clientname, password, tls_local_need=0, compatible
# to confirm the director so can do this on bconsole`way
rand = random.randint(1000000000, 9999999999)
#chal = "<%u.%u@%s>" %(rand, int(time.time()), self.dirname)
chal = "<%u.%u@%s>" %(rand, int(time.time()), clientname)
msg = 'auth cram-md5 %s ssl=%d\n' %(chal, tls_local_need)
chal = '<%u.%u@%s>' %(rand, int(time.time()), clientname)
msg = bytearray('auth cram-md5 %s ssl=%d\n' %(chal, tls_local_need), 'utf-8')
# send the confirmation
self.send(msg)
# get the response
msg = self.recv().strip(chr(0))
self.logger.debug("received: " + msg)
msg = self.recv()
if msg[-1] == 0:
del msg[-1]
self.logger.debug("received: " + str(msg))

# hash with password
hmac_md5 = hmac.new(password)
hmac_md5.update(chal)
hmac_md5 = hmac.new(bytearray(password, 'utf-8'))
hmac_md5.update(bytearray(chal, 'utf-8'))
bbase64compatible = BareosBase64().string_to_base64(bytearray(hmac_md5.digest()), True)
bbase64notcompatible = BareosBase64().string_to_base64(bytearray(hmac_md5.digest()), False)
self.logger.debug("string_to_base64, compatible: " + bbase64compatible)
self.logger.debug("string_to_base64, not compatible: " + bbase64notcompatible)
self.logger.debug("string_to_base64, compatible: " + str(bbase64compatible))
self.logger.debug("string_to_base64, not compatible: " + str(bbase64notcompatible))

is_correct = ((msg == bbase64compatible) or (msg == bbase64notcompatible))
# check against compatible base64 and Bareos specific base64
Expand Down Expand Up @@ -256,14 +262,14 @@ def _cram_md5_respond(self, password, tls_remote_need=0, compatible=True):
self.logger.error("RuntimeError exception in recv")
return (0, True, False)
# check the receive message
self.logger.debug("(recv): " + msg.encode('string-escape'))
msg_list = msg.split(" ")
self.logger.debug("(recv): " + str(msg))
msg_list = msg.split(b" ")
chal = msg_list[2]
# get th timestamp and the tle info from director response
ssl = int(msg_list[3][4])
compatible = True
# hmac chal and the password
hmac_md5 = hmac.new(password)
hmac_md5 = hmac.new(bytearray(password, 'utf-8'))
hmac_md5.update(chal)

# base64 encoding
Expand All @@ -275,7 +281,7 @@ def _cram_md5_respond(self, password, tls_remote_need=0, compatible=True):
if ProtocolMessages.is_auth_ok(received):
result = True
else:
self.logger.error("failed: " + received)
self.logger.error("failed: " + str(received))
return (ssl, compatible, result)


Expand All @@ -286,9 +292,9 @@ def __set_status(self, status):


def _set_state_director_prompt(self):
self.send(".")
self.send(b".")
msg = self.recv_msg()
self.logger.debug("received message: " + msg)
self.logger.debug("received message: " + str(msg))
# TODO: check prompt
return True

Expand Down
8 changes: 4 additions & 4 deletions bareos/bsock/protocolmessages.py
Expand Up @@ -11,21 +11,21 @@ class ProtocolMessages():
@staticmethod
def hello(name, type=ConnectionType.DIRECTOR):
if type == ConnectionType.FILEDAEMON:
return "Hello Director %s calling\n" % (name)
return bytearray("Hello Director %s calling\n" % (name), 'utf-8')
else:
return "Hello %s calling\n" % (name)
return bytearray("Hello %s calling\n" % (name), 'utf-8')

#@staticmethod
#def ok():
#return "1000 OK:"

@staticmethod
def auth_ok():
return "1000 OK auth\n"
return b"1000 OK auth\n"

@staticmethod
def auth_failed():
return "1999 Authorization failed.\n"
return b"1999 Authorization failed.\n"

@staticmethod
def is_auth_ok(msg):
Expand Down
8 changes: 4 additions & 4 deletions bareos/util/bareosbase64.py
Expand Up @@ -19,7 +19,7 @@ def __init__(self):
'''
Initialize the Base 64 conversion routines
'''
self.base64_map = dict(zip(self.base64_digits, xrange(0, 64)))
self.base64_map = dict(list(zip(self.base64_digits, list(range(0, 64)))))

@staticmethod
def twos_comp(val, bits):
Expand All @@ -40,12 +40,12 @@ def base64_to_int(self, base64):
neg = True
first = 1

for i in xrange(first, len(base64)):
for i in range(first, len(base64)):
value = value << 6
try:
value += self.base64_map[base64[i]]
except KeyError:
print "KeyError:", i
print("KeyError:", i)

return -value if neg else value

Expand Down Expand Up @@ -96,4 +96,4 @@ def string_to_base64(self, string, compatible=False):
buf += self.base64_digits[(reg & mask) << (6 - rem)]
else:
buf += self.base64_digits[reg & mask]
return buf
return bytearray(buf, 'utf-8')
4 changes: 2 additions & 2 deletions bareos/util/password.py
Expand Up @@ -11,7 +11,7 @@ def __init__(self, password=None):
self.set_plaintext(password)

def set_plaintext(self, password):
self.password_plaintext = password
self.password_plaintext = bytearray(password, 'utf-8')
self.set_md5(self.__plaintext2md5(password))

def set_md5(self, password):
Expand All @@ -29,5 +29,5 @@ def __plaintext2md5(password):
md5 the password and return the hex style
'''
md5 = hashlib.md5()
md5.update(password)
md5.update(bytearray(password, 'utf-8'))
return md5.hexdigest()
3 changes: 2 additions & 1 deletion bin/bconsole-json.py
@@ -1,5 +1,6 @@
#!/usr/bin/python

from __future__ import print_function
import argparse
import bareos.bsock
import logging
Expand Down Expand Up @@ -38,7 +39,7 @@ def getArguments():
parameter['password']=password
director = bareos.bsock.BSockJson(**parameter)
except RuntimeError as e:
print str(e)
print(str(e))
sys.exit(1)
logger.debug( "authentication successful" )
director.interactive()
3 changes: 2 additions & 1 deletion bin/bconsole.py
@@ -1,5 +1,6 @@
#!/usr/bin/python

from __future__ import print_function
import argparse
#import bareos
import bareos.bsock
Expand Down Expand Up @@ -39,7 +40,7 @@ def getArguments():
parameter['password']=password
director = bareos.bsock.BSock(**parameter)
except RuntimeError as e:
print str(e)
print(str(e))
sys.exit(1)
logger.debug( "authentication successful" )
director.interactive()

0 comments on commit 3c3b7a5

Please sign in to comment.