def sendMsgToStorage(cmd): '''Forwarder of messages to storage''' log.debug("In sendMsgToStorage - cmd: {0}".format(cmd)) try: if not util.connLock.acquire(True, 5): raise IKException( ErrorCode.operationFailed, "Failed to acquire the lock for connecting to storage.") log.debug("Sending...") connHere.send(cmd) log.debug("Sent. Receiving...") if connHere.poll(15): ret = connHere.recv() log.debug("In sendMsgToStorage - ret: {0}".format(ret)) else: ret = composeResponse( "0", "Socket timed out or no data to receive.") log.debug("Nothing to receive") util.connLock.release() except Exception as e: ret = composeResponse("0", str(e)) log.error( "In sendMsgToStorage exception received: {0}".format(ret)) return ret
def handleBinToken(self, dest, tok, optmap): if dest: tok = os.path.join( dest, tok ) path, nam, val = modtok.parse_token( tok, bNam=True, bVal=True) sec = self.fs.getItem( path ) exefile = sec.getItem( nam ) log.debug( "Calling: " + exefile.val + " " + val ) if tok.startswith(stor.BINPATH + "/sh/"): subprocess.call( exefile.val + " " + val, shell=True ) else: subprocess.call( [exefile.val, val], shell=False )
def chCheckServer(self, cmd): '''Check regd server''' # Polling the file storage log.debug("Checking storage...") bresp = CmdSwitcher.switchCmd({"cmd": fs.FS_CHECK}) log.debug("Storage checked.") lresp = util.parsePacket(bresp) fsresp = "Storage:\n" + str(lresp[1]) resp = "Server:\nUp and running since {0}\nUptime:{1}.\n".format( str(self.timestarted).rpartition(".")[0], str(datetime.now() - self.timestarted).rpartition(".")[0]) return composeResponse('1', resp + fsresp)
def startRegistry(servername, sockfile=None, host=None, port=None, acc=defs.PL_PRIVATE, datafile=None, binsecfile=None): srv = connStor = None def shutdown(): log.info("Registry is shutting down...") cmds.CmdSwitcher.switchCmd({"cmd": fs.FS_STOP}) log.info("Shutdown complete.") def signal_handler(signal, frame): #shutdown() # Returning normally, so that the signal notification be forwarded to # the wakeup socket. return sigHandler.push(signal.SIGINT, signal_handler) sigHandler.push(signal.SIGTERM, signal_handler) sigHandler.push(signal.SIGHUP, signal_handler) sigHandler.push(signal.SIGABRT, signal_handler) sigHandler.push(signal.SIGALRM, signal_handler) try: # Storage log.debug("Creating storage") connStor, sigStor = fs.startStorage(acc, datafile, binsecfile) # Server log.debug("Creating server instance") srv = serv.RegdServer(servername, sockfile, host, port, acc) # Info log.debug("Creating info") info.Info() log.debug("Starting server") srv.start_loop(sigStor) except Exception as e: log.error("Failed to start server: {0}".format(e)) else: #glSignal.acquire() # Wait till notification on df.SERVER_STOP #glSignal.wait() shutdown() log.info("Exiting.")
def close( self ): '''Dispose.''' log.debug("Closing...") if self.disposed: log.debug("Already closed.") return self.disposed = True if os.path.exists( str( self.sockfile ) ): log.info( "Stopping server: unlinking socket file..." ) os.unlink( self.sockfile ) log.debug("Closed OK.")
def chStopServer( self, cmd ): '''Stop regd server''' log.debug("In chStopServer") return composeResponse( '1', "Exiting..." )
def _handle_connection( self, connection, client_address, storage_lock ): '''Connection handler''' if not self.host: creds = connection.getsockopt( socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize( "3i" ) ) pid, uid, gid = struct.unpack( "3i", creds ) log.debug( "new connection: pid: {0}; uid: {1}; gid: {2}".format( pid, uid, gid ) ) else: log.debug( "new connection: client address: %s" % ( str( client_address ) ) ) connection.settimeout( 5 ) data = bytearray() util.recvPack( connection, data ) bytesReceived = len( data ) log.debug( "data: %s" % ( data[:1000] ) ) data = data[10:] # .decode( 'utf-8' ) bresp = bytearray() cmd = None perm = False # dcmd - command dictionary. Contains three fields: # cmd - command name, received from client # params - command parameters, received from client # res - internal command processing result, set by the command processor or # command handler. This result has the server semantics, rather than the # command semantics: if it's 0 - this means a general program error, e.g. # non-existing command name. It's meant to be handled by the server before # sending response to the client. try: dcmd = util.parsePacket( data ) # 'internal' switch is only used within regd server if "internal" in dcmd: raise Exception("Unrecognized syntax.") cmd = dcmd["cmd"] log.debug( "command received: {0}".format( cmd ) ) except Exception as e: bresp = composeResponse( "0", "Exception while parsing the command: " + str( e ) ) else: # Check permission and persistency if self.host: # IP-based server if not self.trustedIps: perm = True else : try: clientIp = ipaddress.IPv4Address( client_address[0] ) except ValueError: log.error( "Client IP address format is not recognized." ) else: for i in self.trustedIps: if clientIp in i: perm = True log.debug( "Client IP is trusted." ) break if not perm: log.error( "Client IP is NOT trusted : '%s : %s" % ( client_address[0], client_address[1] ) ) else: # File socket server if self.useruid == uid: perm = True elif uid in self.trustedUserids: perm = True elif cmd not in defs.secure_cmds: if self.acc == defs.PL_PUBLIC: perm = True elif self.acc == defs.PL_PUBLIC_READ: if cmd in defs.pubread_cmds: perm = True log.debug( "perm: {0}".format( perm ) ) if not perm: bresp = composeResponse( "0", str( IKException( ErrorCode.permissionDenied, cmd ) ) ) #elif not self.datafile and defs.PERS in cmd: # bresp = composeResponse( "0", str( IKException( ErrorCode.operationFailed, None, "Persistent tokens are not enabled." ) ) ) if not len( bresp ): util.connLock = storage_lock bresp = CmdSwitcher.handleCmd( dcmd ) try: bytesSent = util.sendPack( connection, bresp ) except OSError as er: log.error( "Socket error {0}: {1}\nClient address: {2}\n".format( er.errno, er.strerror, client_address ) ) else: if type( bytesSent ) is int: info.setShared( "bytesReceived", bytesReceived, defs.SUM ) info.setShared( "bytesSent", bytesSent, defs.SUM ) if cmd == defs.STOP_SERVER and perm: self.sigsock_w.send("stop".encode()) return