def handle(self):
        global STARTED_SERVICE_NAME
        while 1:
            try:
                command = self.request.recv(1024)  
            except:
                break
            
            if command == COMM_ACCESS_SERVICE:
                try:
                    data = json.loads(self.request.recv(1024))
                except:
                    break
                aes_cipher = AESCipher(get_key(STARTED_SERVICE_NAME).decode('hex'))
                print 'encrypted data: %s' % str(data)
                try:
                    from_server = json.loads(aes_cipher.decrypt_data(data['from_service'].decode('hex')))
                    print 'data from server: %s' % str(from_server)
                except:
                    print ERR_INVALID_SERVER_DATA
                    self.request.sendall(json.dumps({'err': ERR_INVALID_SERVER_DATA}))
                    break

                des3_cipher = DES3Cipher(from_server['key'].decode('hex'))

                try:
                    from_user = json.loads(des3_cipher.decrypt_data(data['from_user'].decode('hex')))
                    print 'data from user: %s' % str(from_user)
                except:
                    print ERR_INVALID_SESSION_KEY
                    self.request.sendall(json.dumps({'err': ERR_INVALID_SESSION_KEY}))
                    break


                try:
                    if from_user['user']['username'] != from_server['user']['username']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break

                    if from_user['user']['password'] != from_server['user']['password']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed identidy check'

                    if from_user['lifetime'] != from_server['lifetime']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed lifetime check'

                    if int(time.time()) > from_server['lifetime']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed key lifetime check'

                    if from_user['timestamp'] > from_server['lifetime']:
                        print ERR_INVALID_DATA
                        self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                        break
                    print 'passed timestamp validation'
                except:
                    print ERR_INVALID_DATA
                    self.request.sendall(json.dumps({'err': ERR_INVALID_DATA}))
                    break

                response = {}
                response['lifetime'] = from_server['lifetime'] - 1
                response['timestamp'] = from_user['timestamp']

                response = des3_cipher.encrypt_data(json.dumps(response)).encode('hex')
                self.request.sendall(json.dumps({'for_user': response}))

            elif command == COMM_EXIT:
                break

        self.request.close()
def access_service(sock):

    user_data = {}
    user_data['user'] = {}
    user_data['user']['username'] = raw_input('Username: '******'err' in services:
        return services

    services = services['services']

    service_to_access = get_service_to_access(services)
    
    user_data['nonce'] = rand.random()
    user_data['service'] = service = services[service_to_access]
    user_data['user']['password'] = getpass.getpass()
    user_data['right'] = raw_input('Access right(r/w/rw): ')
    while user_data['right'] not in ACCESS_RIGHT_OPT:
        user_data['right'] = raw_input('Access right(r/w/rw): ')

    sock.sendall(COMM_ACCESS_SERVICE)
    sock.sendall(json.dumps(user_data))
    response = json.loads(sock.recv(1024))

    if 'err' in response:
        return response

    user_key = get_key(user_data['user']['username']).decode('hex')
    print 'kut: %s' % user_key
    aes_cipher = AESCipher(user_key)
    
    print 'response from server: %s' % str(response)
    user_response = json.loads(aes_cipher.decrypt_data(response['for_user'].decode('hex')))
    print 'decrypted response from server, for user: %s' % str(user_response)
    print 'k: %s' % user_response['key'].decode('hex')

    if user_response['nonce'] != user_data['nonce']:
        return {'err': ERR_INVALID_SESSION}

    if user_response['service'] != user_data['service']:
        return {'err': ERR_INVALID_SESSION}        

    des3_cipher = DES3Cipher(user_response['key'].decode('hex'))

    service_socket = connect_to_socket(HOST, service['port'])

    if 'err' in service_socket:
        return service_socket

    service_socket = service_socket['sock']

    timestamp = int(time.time())
    service_response = {}
    service_response['from_user'] = {}
    service_response['from_user']['user'] = user_data['user']
    service_response['from_user']['timestamp'] = timestamp
    service_response['from_user']['lifetime'] = user_response['lifetime']
    service_response['from_user'] = des3_cipher.encrypt_data(json.dumps(service_response['from_user'])).encode('hex')
    service_response['from_service'] = response['for_service']

    print 'send service respons: %s' % str(service_response)

    service_socket.sendall(COMM_ACCESS_SERVICE)
    service_socket.sendall(json.dumps(service_response))

    response = json.loads(service_socket.recv(1024))

    if 'err' in response:
        service_socket.close()
        return response

    print 'response from service: %s' % str(response)
    response = json.loads(des3_cipher.decrypt_data(response['for_user'].decode('hex')))
    print 'decrypted response from service: %s' % str(response)

    if response['timestamp'] != timestamp:
        return {'err': ERR_INVALID_SESSION}

    if response['lifetime'] != user_response['lifetime'] - 1:
        return {'err': ERR_FORBIDDEN}

    service_socket.sendall(COMM_EXIT)

    service_socket.close()

    return ERR_SUCCESS