示例#1
0
	def lineReceived(self, line):
		display_message('Received the following line from the client [%s]: %s' % (self.host, line))
		
		data = self._cleanAndSplitInput(line)
		if len(data) == 0 or data == '':
			return 
		
		command = data[0].lower()
		if not command in COMMANDS:
                        self.transport.write('%s\n' % (command))
			self.transport.write('Invalid command\n')
			return
		    
		if command == 'list':
                        pass

		elif command == 'auth':
                        self.isLogin = self.getAuth()
                        if self.isLogin:
                                self.transport.write('file\n')
                                
                        return

		elif command == 'put':
			try:
				filename = data[1]
				file_hash = data[2]
			except IndexError:
				self.transport.write('Missing filename or file MD5 hash\n')
				return

			self.file_data = (filename, file_hash)
			
			# Switch to the raw mode (for receiving binary data)
			display_message('Receiving file: %s' % (filename))
			self.setRawMode()
		elif command == 'help':
			self.transport.write('Available commands:\n\n')
			
			for key, value in COMMANDS.iteritems():
				self.transport.write('%s - %s\n' % (value[0], value[1]))
							
		elif command == 'quit':
			self.transport.loseConnection()
示例#2
0
文件: server.py 项目: tahyuu/paimai
	def lineReceived(self, line):

		display_message('Received the following line from the client [%s]: %s' % (self.transport.getPeer().host, line))

		

		data = self._cleanAndSplitInput(line)

		if len(data) == 0 or data == '':

			return 

		

		command = data[0].lower()

		if not command in COMMANDS:

			self.transport.write('Invalid command\n')

			self.transport.write('ENDMSG\n')

			return

		if command == 'list':

			self._send_list_of_files()

		elif command == 'get':

			try:

				filename = data[1]

			except IndexError:

				self.transport.write('Missing filename\n')

				self.transport.write('ENDMSG\n')

				return

			

			if not self.factory.files:

				self.factory.files = self._get_file_list()

				

			if not filename in self.factory.files:

				self.transport.write('File with filename %s does not exist\n' % (filename))

				self.transport.write('ENDMSG\n')

				return

			

			display_message('Sending file: %s (%d KB)' % (filename, self.factory.files[filename][1] / 1024))

			

			self.transport.write('HASH %s %s\n' % (filename, self.factory.files[filename][2]))

			self.setRawMode()

			

			for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, filename)):

				self.transport.write(bytes)

			

			self.transport.write('\r\n')	

			self.setLineMode()

		elif command == 'put':

			try:

				filename = data[1]

				file_hash = data[2]

			except IndexError:

				self.transport.write('Missing filename or file MD5 hash\n')

				self.transport.write('ENDMSG\n')

				return



			self.file_data = (filename, file_hash)

			

			# Switch to the raw mode (for receiving binary data)

			print 'Receiving file: %s' % (filename)

			self.setRawMode()

		elif command == 'help':

			self.transport.write('Available commands:\n\n')

			

			for key, value in COMMANDS.iteritems():

				self.transport.write('%s - %s\n' % (value[0], value[1]))

			

			self.transport.write('ENDMSG\n')				

		elif command == 'quit':

			self.transport.loseConnection()
示例#3
0
	def lineReceived(self, line):
		display_message('Received the following line from the client [%s]: %s' % (self.transport.getPeer().host, line))
		logMessage = 'Received the following line from the client [%s]: %s' % (self.transport.getPeer().host, line)
		self.log(logMessage)

		data = self._cleanAndSplitInput(line)
		if len(data) == 0 or data == '':
			return 
		
		command = data[0].lower()
		if not command in COMMANDS:
			self.transport.write('Invalid command\n')
			self.transport.write('ENDMSG\n')
			return
		if command == 'list':
			self._send_list_of_files()
		elif command == 'get':
			try:
				filename = data[1]
			except IndexError:
				self.transport.write('Missing filename\n')
				self.transport.write('ENDMSG\n')
				return
			
			if not self.factory.files:
				self.factory.files = self._get_file_list()
				
			if not filename in self.factory.files:
				self.transport.write('File with filename %s does not exist\n' % (filename))
				self.transport.write('ENDMSG\n')
				return
			
			display_message('Sending file: %s (%d KB)' % (filename, self.factory.files[filename][1] / 1024))
			
			self.transport.write('HASH %s %s\n' % (filename, self.factory.files[filename][2]))
			self.setRawMode()
			
			for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, filename)):
				self.transport.write(bytes)
			
			self.transport.write('\r\n')	
			self.setLineMode()
		elif command == 'put':
			try:
				filename = data[1]
				file_hash = data[2]
			except IndexError:
				self.transport.write('Missing filename or file MD5 hash\n')
				self.transport.write('ENDMSG\n')
				return

			self.file_data = (filename, file_hash)
			
			# Switch to the raw mode (for receiving binary data)
			print 'Receiving file: %s' % (filename)
			self.setRawMode()
		elif command == 'help':
			self.transport.write('Available commands:\n\n')
			
			for key, value in COMMANDS.iteritems():
				self.transport.write('%s - %s\n' % (value[0], value[1]))
			
			self.transport.write('ENDMSG\n')		

		elif command == 'register':
			username = data[1]
			password = data[2]
			answer = login_demo.register_user(username, password)
			print answer
			self.transport.write('%s\n' % answer)	
			self.transport.write('ENDMSG\n')
			
		elif command == 'login':
			username = data[1]
			password = data[2]
			answer = login_demo.login(username, password)
			print answer
			self.transport.write('%s\n' % answer)	
			self.transport.write('ENDMSG\n')				
		
		elif command == 'quit':
			self.transport.loseConnection()
示例#4
0
                    print e
            elif os.path.isfile(filename):
                print("deleting file")
                try:
                    os.remove(filename)
                except OSError, e:
                    print("error deleting file")
                    print e
            else:
                print "%s does not exist" % filename

            ####################################################################
        elif command == 'help':
            self.transport.write('Available commands:\n\n')

            for key, value in COMMANDS.iteritems():
                self.transport.write('%s - %s\n' % (value[0], value[1]))

            self.transport.write('ENDMSG\n')

        elif command == 'registry':
            global admin
            if user not in admin:
                self.transport.write('%s does not have administrative rights.\n' % user)
                self.transport.write('ENDMSG\n')
            else:

                # TODO; check if user is in admin list first
                registry = login_demo.retrieve_login_info()
                self.transport.write('username\t\tpassword\t\trole\n')
                for key, value in registry.iteritems():
示例#5
0
    def lineReceived(self, line):
	global clients
        display_message('Received the following line from the client [%s]: %s' % (self.transport.getPeer().host, line))

        data = self._cleanAndSplitInput(line)
        if len(data) == 0 or data == '':
            return
	
	user = data.pop()

        command = data[0].lower()
        if not command in COMMANDS:
            self.transport.write('Invalid command\n')
            self.transport.write('ENDMSG\n')
            return

	if command != 'login' and command != 'quit' and user not in clients:
		self.transport.write('You must be logged in\n')
		self.transport.write('ENDMSG\n')
		return


	print data

        if command == 'list':
            self._send_list_of_files()

        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self.transport.write('Missing filename\n')
                self.transport.write('ENDMSG\n')
                return

            if not self.factory.files:
                self.factory.files = self._get_file_list()

            if not filename in self.factory.files:
                self.transport.write('File with filename %s does not exist\n' % (filename))
                self.transport.write('ENDMSG\n')
                return

            display_message('Sending file: %s (%d KB)' % (filename, self.factory.files[filename][1] / 1024))

            self.transport.write('HASH %s %s\n' % (filename, self.factory.files[filename][2]))
            self.setRawMode()

            for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, filename)):
                self.transport.write(bytes)

            self.transport.write('\r\n')
            self.setLineMode()
        elif command == 'put':

            try:
                filename = data[1]
                file_hash = data[2]
                #replace the '|' back with ' '
                filename = filename.replace('|',' ')
                file_hash = file_hash.replace('|',' ')

            except IndexError:
                self.transport.write('Missing filename or file MD5 hash\n')
                self.transport.write('ENDMSG\n')
                return

            self.file_data = (filename, file_hash)

            # Switch to the raw mode (for receiving binary data)
            print 'Receiving file: %s' % (filename)
            self.setRawMode()
        elif command == 'help':
            self.transport.write('Available commands:\n\n')

            for key, value in COMMANDS.iteritems():
                self.transport.write('%s - %s\n' % (value[0], value[1]))

            self.transport.write('ENDMSG\n')

	elif command == 'registry':
	    global admin
	    if user not in admin:
		self.transport.write('%s does not have administrative rights.\n' % user)
                self.transport.write('ENDMSG\n')
	    else:
		
	    # TODO; check if user is in admin list first
		registry = login_demo.retrieve_login_info()
		self.transport.write('username\t\tpassword\t\trole\n')
		for key, value in registry.iteritems():
			self.transport.write('%s\t\t\t%s\t\t\t%s\n' % (key, value[0],  value[1]))
		
		self.transport.write('ENDMSG\n')			

        elif command == 'register':
	    global admin
	    if user not in admin:
		self.transport.write('%s does not have administrative rights.\n' % user)
                self.transport.write('ENDMSG\n')
	    # TODO; check if user is in admin list first
            username = data[1]
            password = data[2]
	    role = data [3]
            answer = login_demo.register_user(username, password, role)
            print answer

	    created = "user %s has been created" % username
	    if answer == created:
		user_path = DIRECTORY + "/%s/OneDir" % username
		if not os.path.exists(user_path):
		    try:	
			os.makedirs(user_path)
		    except OSError, e: 
			print e
	    else:
		print "%s already exists" % path
		return False

		
            self.transport.write('%s\n' % answer)
            self.transport.write('ENDMSG\n')
示例#6
0
    def lineReceived(self, line):
        display_message(
            self.prv_logger,
            'Received the following line from the client [%s]: %s' %
            (self.transport.getPeer().host, line))

        data = self._cleanAndSplitInput(line)
        if len(data) == 0 or data == '':
            return

        command = data[0].lower()
        if not command in COMMANDS:
            self.transport.write('Invalid command:%s\n' % command)
            self.transport.write('ENDMSG\n')
            return
        if command == 'list':
            self._send_list_of_files()
        elif command == 'get':
            try:
                src_filename = data[1]
                dst_filename = data[2]
            except IndexError:
                self.transport.write('Missing filename\n')
                self.transport.write('ENDMSG\n')
                return
            abs_file_path = os.path.join(self.factory.files_path, src_filename)
            if not os.path.isfile(abs_file_path):
                self.transport.write('File with filename %s does not exist\n' %
                                     (src_filename))
                self.transport.write('ENDMSG\n')
                return
            file_size = os.path.getsize(abs_file_path)
            md5_hash = get_file_md5_hash(abs_file_path)

            display_message(
                self.prv_logger, 'Sending file to (%s:%s): %s (%d KB)' %
                (str(self.transport.getPeer().host),
                 str(self.transport.getPeer().port), src_filename,
                 file_size / 1024))

            self.transport.write('HASH %s %s\n' % (dst_filename, md5_hash))
            self.setRawMode()

            for bytes in read_bytes_from_file(abs_file_path):
                self.transport.write(bytes)

            self.transport.write('\r\r\r\r\n')
            self.setLineMode()
        elif command == 'put' or command == 'upload':
            try:
                filename = data[1]
                file_hash = data[2]
            except IndexError:
                self.transport.write('Missing filename or file MD5 hash\n')
                self.transport.write('ENDMSG\n')
                return
            if command == 'upload':
                try:
                    id = data[3]
                    result = data[4]
                except IndexError:
                    self.transport.write('Missing id or result when upload\n')
                    self.transport.write('ENDMSG\n')
                    return
                timeStamp = time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime())
                if not update_special_cmd(self.mysql_hdlr, id, {
                        'status': 'finished',
                        'end_time': timeStamp,
                        'result': result
                }):
                    self.prv_logger.error(
                        "update mysql failed; status: running->finished")
                self.file_data["%s:%s" %
                               (str(self.transport.getPeer().host),
                                str(self.transport.getPeer().port))] = {
                                    'filename': filename,
                                    'file_hash': file_hash,
                                    'id': id
                                }
            else:
                self.file_data["%s:%s" %
                               (str(self.transport.getPeer().host),
                                str(self.transport.getPeer().port))] = {
                                    'filename': filename,
                                    'file_hash': file_hash
                                }

            # Switch to the raw mode (for receiving binary data)
            print 'Receiving file: %s' % (filename)
            self.setRawMode()
        elif command == 'case_finished':
            id = data[1]
            result = data[2]
            timeStamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.prv_logger.trace("update mysql, case id:%s, result:%s" %
                                  (id, result))
            if len(data) > 3:
                if not update_special_cmd(
                        self.mysql_hdlr, id, {
                            'status': 'finished',
                            'end_time': timeStamp,
                            'result': result,
                            'reserved': ' '.join(data[3:])
                        }):
                    self.prv_logger.error(
                        "update mysql failed; status: running->finished")
            elif not update_special_cmd(self.mysql_hdlr, id, {
                    'status': 'finished',
                    'end_time': timeStamp,
                    'result': result
            }):
                self.prv_logger.error(
                    "update mysql failed; status: running->finished")
            self.transport.write('ENDMSG\n')
        elif command == 'help':
            self.transport.write('Available commands:\n\n')

            for key, value in COMMANDS.iteritems():
                self.transport.write('%s - %s\n' % (value[0], value[1]))

            self.transport.write('ENDMSG\n')
        elif command == 'hb':
            try:
                owner = data[1]
                hostname = data[2].lower()
                macaddr = data[3].lower()
                duttype = data[4]
                dutip = data[5]
                swversion = data[6]
                status = data[7]
                taskid = data[8]
                timeStamp = time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime())
                update_connection_cmd(
                    self.mysql_hdlr, {
                        'end_time': timeStamp,
                        'status': 'offline',
                        'client_pcname': hostname
                    }, {'mac_addr': macaddr},
                    where_str_addtional='client_conn_port != %s' %
                    str(self.transport.getPeer().port))
                update_connection_cmd(
                    self.mysql_hdlr, {
                        'mac_addr': macaddr,
                        'owner': owner,
                        'dut_type': duttype,
                        'dut_ip': dutip,
                        'sw_version': swversion,
                        'status': status,
                        'client_pcname': hostname
                    }, {
                        'client_conn_port': str(self.transport.getPeer().port),
                        'client_ip': str(self.transport.getPeer().host)
                    },
                    where_str_addtional='order by id desc limit 1')
                update_connection_id(self.mysql_hdlr, {'mac_addr': macaddr})
                conn_info = get_connection_info(
                    self.mysql_hdlr, {
                        'client_conn_port': str(self.transport.getPeer().port),
                        'client_ip': str(self.transport.getPeer().host)
                    })
                if conn_info != None:
                    client_id = conn_info['client_id']
                else:
                    client_id = 0
                #hardcode
                self.prv_logger.trace("current connection id:%d" % client_id)
                private_cmd = get_private_cmd(self.mysql_hdlr, owner, duttype,
                                              client_id, swversion)
                neighbour_cmd = get_neighbour_cmd(self.mysql_hdlr, owner,
                                                  duttype, client_id,
                                                  swversion)
                if status == 'idle':
                    self.busy_cnt = 0
                    #self.transport.write('start_testcase %s\n'%os.path.join("BG2CDP", "Chromecast_HBOGO.tar.gz"))
                    if private_cmd != None: cmd_list = private_cmd
                    elif neighbour_cmd != None: cmd_list = neighbour_cmd
                    else:
                        self.prv_logger.trace(
                            "could not get any command from mysql")
                        cmd_list = None

                    if cmd_list != None:
                        case_info = get_case_info(self.mysql_hdlr,
                                                  {'id': cmd_list['case_id']})
                        if case_info != None:
                            start_case_cmd = case_info['path']
                        else:
                            start_case_cmd
                    else:
                        start_case_cmd = None
                    if start_case_cmd != None:
                        self.transport.write(
                            'start_testcase %s %s %s %s\n' %
                            (start_case_cmd,
                             os.path.join("TestCase", "Config",
                                          str(cmd_list['id']), 'config.py'),
                             cmd_list['id'], cmd_list['case_parametar']))
                        timeStamp = time.strftime("%Y-%m-%d %H:%M:%S",
                                                  time.localtime())
                        if not update_special_cmd(
                                self.mysql_hdlr, cmd_list['id'], {
                                    'status': 'running',
                                    'exc_client_id': client_id,
                                    'start_time': timeStamp,
                                    'sw_version': swversion
                                }):
                            self.prv_logger.error(
                                "update mysql failed;status:not run->running")
                    #self.transport.write('ENDMSG\n')
                elif status == 'busy':
                    #update_special_cmd(self.mysql_hdlr, taskid, {'status':'running', 'sw_version':swversion})
                    self.prv_logger.trace("dut is busy(id:%s)" % taskid)
                    res = get_special_cmd(self.mysql_hdlr, taskid)
                    if res != None:
                        if res['status'] == 'running':
                            self.prv_logger.trace('got it(id:%s)' % taskid)
                            if res['cmd_owner'] != owner and private_cmd != None:
                                self.prv_logger.trace(
                                    'case(id:%s; case_id:%s; owner:%s) will be canceled;'
                                    % (res['id'], res['case_id'],
                                       res['cmd_owner']))
                                self.prv_logger.trace(
                                    'case(id:%s; case_id:%s; owner:%s) will be run;'
                                    %
                                    (private_cmd['id'], private_cmd['case_id'],
                                     private_cmd['cmd_owner']))
                                if not update_special_cmd(
                                        self.mysql_hdlr, taskid,
                                    {'status': 'not run'}):
                                    self.prv_logger.error(
                                        "update mysql failed;status:not running->not run"
                                    )
                                self.transport.write('cancel_testcase\n')
                                update_special_cmd(self.mysql_hdlr, taskid, {
                                    'status': 'not run',
                                    'sw_version': swversion
                                })
                        elif res['status'] == 'stopped':
                            self.transport.write('stop_testcase\n')
                            update_special_cmd(
                                self.mysql_hdlr, taskid, {
                                    'status': 'finished',
                                    'result': 'stopped',
                                    'reserved': 'manually stopped',
                                    'sw_version': swversion
                                })
                        elif res['status'] == 'restart':
                            self.transport.write('cancel_testcase\n')
                            update_special_cmd(
                                self.mysql_hdlr, taskid, {
                                    'status': 'not run',
                                    'reserved': 'manually canceled',
                                    'sw_version': swversion
                                })
                        else:
                            update_special_cmd(self.mysql_hdlr, taskid, {
                                'status': 'running',
                                'sw_version': swversion
                            })
                            self.prv_logger.trace('invalid status:%s (id:%s)' %
                                                  (res['status'], taskid))
                    else:
                        self.prv_logger.error('could not get(id:%s) in db' %
                                              taskid)

                else:
                    """
                                    should be hang or other unhandle status,
                                    need notify administrator and client owner
                                    """
                self.transport.write('ENDMSG\n')
                print "owner:%s hostname:%s macaddr:%s duttype:%s dutip:%s swversion:%s status:%s" % (
                    owner, hostname, macaddr, duttype, dutip, swversion,
                    status)
            except IndexError:
                self.transport.write(
                    'Missing hostname, macaddr, duttype or swversion\n')
                self.transport.write('ENDMSG\n')
                self.prv_logger.trace(
                    'Missing hostname, macaddr, duttype or swversion\n')
                return

#except Exception, e:
#        self.prv_logger.trace('Capture exception:%s'%str(e))
#except:
#        self.prv_logger.trace('Capture unknown exception')
        elif command == 'quit':
            self.transport.loseConnection()
示例#7
0
    def lineReceived(self, line):
	global clients
        display_message('Received the following line from the client [%s]: %s' % (self.transport.getPeer().host, line))

        data = self._cleanAndSplitInput(line)
        if len(data) == 0 or data == '':
            return
	
	user = data.pop()

        command = data[0].lower()
        if not command in COMMANDS:
            self.transport.write('Invalid command\n')
            self.transport.write('ENDMSG\n')
            return

	if command != 'login' and command != 'quit' and user not in clients:
		self.transport.write('You must be logged in\n')
		self.transport.write('ENDMSG\n')
		return

        if command == 'list':
            self._send_list_of_files()

        elif command == 'get':
            try:
                filename = data[1]
            except IndexError:
                self.transport.write('Missing filename\n')
                self.transport.write('ENDMSG\n')
                return

            if not self.factory.files:
                self.factory.files = self._get_file_list()

            if not filename in self.factory.files:
                self.transport.write('File with filename %s does not exist\n' % (filename))
                self.transport.write('ENDMSG\n')
                return

            display_message('Sending file: %s (%d KB)' % (filename, self.factory.files[filename][1] / 1024))

            self.transport.write('HASH %s %s\n' % (filename, self.factory.files[filename][2]))
            self.setRawMode()

            for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, filename)):
                self.transport.write(bytes)

            self.transport.write('\r\n')
            self.setLineMode()
        elif command == 'put':

            try:
                filename = data[1]
                file_hash = data[2]
                #replace the '|' back with ' '
                filename = filename.replace('|',' ')
                file_hash = file_hash.replace('|',' ')

            except IndexError:
                self.transport.write('Missing filename or file MD5 hash\n')
                self.transport.write('ENDMSG\n')
                return

            self.file_data = (filename, file_hash)

            # Switch to the raw mode (for receiving binary data)
            print 'Receiving file: %s' % (filename)
            self.setRawMode()
        elif command == 'help':
            self.transport.write('Available commands:\n\n')

            for key, value in COMMANDS.iteritems():
                self.transport.write('%s - %s\n' % (value[0], value[1]))

            self.transport.write('ENDMSG\n')

	elif command == 'registry':
		registry = login_demo.retrieve_login_info()
		self.transport.write('username\t\tpassword\n')
		for key, value in registry.iteritems():
			self.transport.write('%s\t\t\t%s\n' % (key, value[0]))
		
		self.transport.write('ENDMSG\n')			

        elif command == 'register':
            username = data[1]
            password = data[2]
            answer = login_demo.register_user(username, password)
            print answer
            self.transport.write('%s\n' % answer)
            self.transport.write('ENDMSG\n')

        elif command == 'login':
	    global clients
	    if user in clients:
		self.transport.write('%s is already logged in.\n' % user)
                self.transport.write('ENDMSG\n')
	    else: 
                username = data[1]
                password = data[2]
                answer = login_demo.login(username, password)
       	        if answer == "Logged In":
         	    display_message(username)
		    clients.append(username)
                print answer
	    	print clients
                self.transport.write('%s %s\n' % (answer, username))
                self.transport.write('ENDMSG\n')

	elif command == 'logout':
	    global clients
	    clients.remove(user)
	    self.transport.write('%s logged out of system\n' % user)				
	    self.transport.write('ENDMSG\n')				
			
        elif command == 'quit':
            self.transport.loseConnection()
示例#8
0
	def lineReceived(self, line):
		
		data = self._cleanAndSplitInput(line)
		if len(data) == 0 or data == '':
			return 
		
		command = data[0].lower()
		display_message('Received the following command from the client %s ,[%s]: %s' % (self.nick,self.ip, command))
		log_message('Received the following command from the client %s ,[%s]: %s' % (self.nick,self.ip, command),self.factory.log)
		
		if not ((command in COMMANDS) or (command in RESPONSE)) :
			self.transport.write('Invalid command\n')
			self.transport.write('ENDMSG\n')
			return
		
		if command == 'list':
			self._send_list_of_files()
			
		if command == 'finger':
			if not self.authenticated :
				self.transport.write('Please authenitcate using "nick identify" before using file transfer \n')
				self.transport.write('ENDMSG\n')
				return 
				
			try:
				nickname = data[1]
			except IndexError:
				self.transport.write('Missing nickname\n')
				self.transport.write('ENDMSG\n')
				return
				
			for user in self.factory.onlineClients :
				if user.nick == nickname :
					self.transport.write('-- INFORMATION --  \n')
					self.transport.write('Nickname : %s \n'%(nickname))
					self.transport.write('IP : %s \n'%(user.ip))
					self.transport.write('PORT : %d \n'%(user.port))
					self.transport.write('OS : %s \n'%(user.osType.split('#')[0]))
					self.transport.write('Platform : %s \n'%(user.osType.split('#')[1]))
					self.transport.write('ENDMSG\n')
					
					return 
				
			self.transport.write('Nickname not found\n')
			self.transport.write('ENDMSG\n')	
			
		
		elif command =='platform':
			print data[1]
			self.osType = data[1]
		
		elif command == 'get':
			if not self.authenticated :
				self.transport.write('Please authenitcate using "nick identify" before using file transfer \n')
				self.transport.write('ENDMSG\n')
				return 
				
			try:
				filename = data[1]
			except IndexError:
				self.transport.write('Missing filename\n')
				self.transport.write('ENDMSG\n')
				return
			
			if not self.factory.files:
				self.factory.files = self._get_file_list()
				
			if not filename in self.factory.files:
				self.transport.write('File with filename %s does not exist\n' % (filename))
				self.transport.write('ENDMSG\n')
				return
			
			display_message('%s : Sending file: %s (%d KB)' % (self.nick,filename, self.factory.files[filename][1] / 1024))
			log_message('%s : Sending file: %s (%d KB)' % (self.nick,filename, self.factory.files[filename][1] / 1024),self.factory.log)
			
			self.transport.write('HASH %s %s\n' % (filename, self.factory.files[filename][2]))
			self.setRawMode()
			
			for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, filename)):
				self.transport.write(bytes)
			
			self.transport.write('\r\n')	
			self.setLineMode()
		
		elif command == 'put':
			if not self.authenticated :
				self.transport.write('Please authenitcate using "nick identify" before using file transfer \n')
				self.transport.write('ENDMSG\n')
				return
			
			try:
				filename = data[1]
				file_hash = data[2]
			except IndexError:
				self.transport.write('Missing filename or file MD5 hash\n')
				self.transport.write('ENDMSG\n')
				return

			self.file_data = (filename, file_hash)
			
			# Switch to the raw mode (for receiving binary data)
			print 'Receiving file: %s' % (filename)
			self.setRawMode()
		
		elif command == "people" :
			self._send_online_clients()
		
		elif command == "sync" :
			
			self.factory.files = self._get_file_list()
			self.sync = 1 			
			
				
			if not self.authenticated :
				self.transport.write('Please authenitcate using "nick identify" before using sync \n')
				self.transport.write('ENDMSG\n')
				return
			
			now = datetime.datetime.now()
			
			self.transport.write('Initiating sync \n')
			self.transport.write('ENDMSG\n')
			display_message('initiating sync with %s(%s) : %s ' % (self.nick,self.ip,now.strftime("%Y-%m-%d %H:%M")))
			log_message('initiating sync with %s(%s) : %s ' % (self.nick,self.ip,now.strftime("%Y-%m-%d %H:%M")),self.factory.log)
			
			#self.transport.write('Initiating sync\n')
			#self.transport.write('ENDMSG\n')
			try:
				cfiles = data[1].split('#')
				
			except IndexError:
				cfiles = []
				
			sfiles = [ f for f in os.listdir(self.factory.files_path) if os.path.isfile(os.path.join(self.factory.files_path,f)) ]
			file_outbox = []
			
			for file in sfiles :
				if file not in cfiles :
					self.file_outbox.append(file)
			
			no_of_files = len(self.file_outbox)
			self.transport.write('Sending %d files\n'%(no_of_files))
			self.transport.write('ENDMSG\n')
				
			if no_of_files == 0 :
				self.sync = 0
				self.transport.write('Folders are in sync \n')
				self.transport.write('ENDMSG\n')
				return
			
			file = self.file_outbox.pop()
			#self.sendFile(file)
			
			display_message('%s : Sending file: %s (%d KB)' % (self.nick,file, self.factory.files[file][1] / 1024))
			log_message('%s : Sending file: %s (%d KB)' % (self.nick,file, self.factory.files[file][1] / 1024),self.factory.log)
			
			self.transport.write('HASH %s %s\n' % (file, self.factory.files[file][2]))
			self.setRawMode()
			
			for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, file)):
				self.transport.write(bytes)
			
			self.transport.write('\r\n')	
			self.setLineMode()
				
				
			'''
			@defer.inlineCallbacks
			def _sync():
				
				for file in file_outbox :
					display_message('%s : Sending file: %s (%d KB)' % (self.nick,file, self.factory.files[file][1] / 1024))
					log_message('%s : Sending file: %s (%d KB)' % (self.nick,file, self.factory.files[file][1] / 1024),self.factory.log)
					yield sendFile(file)
						
		    _sync()	
			'''
				
				#self.transport.write('ENDMSG\n')
				
			
					
		
		elif command == 'nick':
			subcommand = data[1]
			if not (subcommand and data[2] and data[3]) :
				self.transport.write('Missing nickname and/or password\n')
				self.transport.write('ENDMSG\n')
			else :
				if data[1] == "reg" :
					self._register(data[2],data[3])
					
				elif data[1] == "identify" :
					self._identify(data[2],data[3])
					
				else :
					self.transport.write('unknown subcommand %s to nick\n' % (data[1]))
					self.transport.write('ENDMSG\n')
						 
			
		
		
		elif command == 'recv' :
			now = datetime.datetime.now()
			display_message('%s : File recieved - %s' % (self.nick,data[1]))
			log_message('%s : File recieved - %s' % (self.nick,data[1]),self.factory.log)
			
			if self.sync == 1 :
				no_of_files = len(self.file_outbox)
				
				if no_of_files != 0 :
					file = self.file_outbox.pop()
					
					
					
					self.transport.write('HASH %s %s\n' % (file, self.factory.files[file][2]))
					self.setRawMode()
			
					for bytes in read_bytes_from_file(os.path.join(self.factory.files_path, file)):
						self.transport.write(bytes)
			
					self.transport.write('\r\n')	
					self.setLineMode()
					
					
				
					
					#self.sendFile(file)
					
					
				else :
					display_message('terminating sync with %s(%s) : %s ' % (self.nick,self.ip,now.strftime("%Y-%m-%d %H:%M")))
					log_message(' sync with %s(%s) : %s ' % (self.nick,self.ip,now.strftime("%Y-%m-%d %H:%M")),self.factory.log)
					#self.transport.write('Terminating sync\n')
					self.setLineMode()
					self.transport.write('Sync complete\n')
					self.transport.write('ENDMSG\n')
					#self.transport.write('ENDMSG\n')
					self.sync = 0
					
				
		
		elif command == 'search':
			
			self.factory.search_request = 1
			self.factory.responses = 0 
			self.factory.requester = self
			for user in self.factory.onlineClients :
				if user.nick != self.nick :
					user.transport.write('SEARCH-REQUEST %s\n'%(data[1]))
				else :
					user.transport.write('ENDMSG\n')
					
                    
		elif command == 'sresponse':
			
			
			if self.factory.search_request == 1 :
				self.factory.responses+=1
				found = data[1]
				print data
				if found == 'true' :
					tupple = (self.nick,self.ip)
					self.factory.search_dump.append(tupple)
				if self.factory.responses >= len(self.factory.onlineClients) - 1:
					self.factory.requester.setLineMode()
					
					if len(self.factory.search_dump) == 0 :
						self.factory.requester.transport.write('File not found \n')
						self.factory.requester.transport.write('ENDMSG\n')
					else :
						self.factory.requester.transport.write('File found in following clients \n')
						for user in self.factory.search_dump : 
							self.factory.requester.transport.write('%s - %s\n'%(user[0],user[1]))
						self.factory.requester.transport.write('ENDMSG\n')
                            
					self.factory.search_request = 0
					self.factory.requester = None
                        
                
		
		
		elif command == 'help':
			self.transport.write('Available commands:\n\n')
			
			for key, value in COMMANDS.iteritems():
				self.transport.write('%s - %s\n' % (value[0], value[1]))
			
			self.transport.write('ENDMSG\n')				
		elif command == 'quit':
			self.transport.loseConnection()