Added session type to login request

This commit is contained in:
Adolfo Gómez 2020-07-27 08:53:05 +02:00
parent 4e3dce37f7
commit 606e65eea4
8 changed files with 46 additions and 24 deletions

View File

@ -34,7 +34,7 @@ import datetime
import signal
import typing
from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtCore import QByteArray, QBuffer, QIODevice, pyqtSignal
from . import rest
@ -49,6 +49,7 @@ from .http import client
if typing.TYPE_CHECKING:
from . import types
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow
class UDSClientQApp(QApplication):
_app: 'UDSActorClient'
@ -182,7 +183,7 @@ class UDSActorClient(threading.Thread): # pylint: disable=too-many-instance-att
try:
# Notify loging and mark it
self._loginInfo = self.api.login(platform.operations.getCurrentUser())
self._loginInfo = self.api.login(platform.operations.getCurrentUser(), platform.operations.getSessionType())
if self._loginInfo.max_idle:
platform.operations.initIdleDuration(self._loginInfo.max_idle)

View File

@ -38,7 +38,7 @@ if typing.TYPE_CHECKING:
class LocalProvider(handler.Handler):
def post_login(self) -> typing.Any:
result = self._service.login(self._params['username'])
result = self._service.login(self._params['username'], self._params['session_type'])
return result._asdict()
def post_logout(self) -> typing.Any:

View File

@ -32,7 +32,7 @@
import configparser
import platform
import socket
import fcntl
import fcntl # Only available on Linux. Expect complains if edited from windows
import os
import subprocess
import struct
@ -50,7 +50,7 @@ def _getMacAddr(ifname: str) -> typing.Optional[str]:
Returns the mac address of an interface
Mac is returned as unicode utf-8 encoded
'''
ifnameBytes = ifname.encode('utf-8') # If unicode, convert to bytes
ifnameBytes = ifname.encode('utf-8')
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = bytearray(fcntl.ioctl(s.fileno(), 0x8927, struct.pack(str('256s'), ifnameBytes[:15])))
@ -64,7 +64,7 @@ def _getIpAddr(ifname: str) -> typing.Optional[str]:
Returns the ip address of an interface
Ip is returned as unicode utf-8 encoded
'''
ifnameBytes = ifname.encode('utf-8') # If unicode, convert to bytes (or str in python 2.7)
ifnameBytes = ifname.encode('utf-8')
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return str(socket.inet_ntoa(fcntl.ioctl(
@ -106,7 +106,7 @@ def _getIpAndMac(ifname: str) -> typing.Tuple[typing.Optional[str], typing.Optio
return (ip, mac)
def checkPermissions() -> bool:
return os.getuid() == 0
return os.getuid() == 0 # getuid only available on linux. Expect "complaioins" if edited from Windows
def getComputerName() -> str:
'''
@ -183,6 +183,14 @@ def getCurrentUser() -> str:
'''
return os.environ['USER']
def getSessionType() -> str:
'''
Known values:
* Unknown -> No SESSIONNAME environment variable
* Console -> Local session
* RDP-Tcp#[0-9]+ -> RDP Session
'''
return 'xrdp' if 'XRDP_SESSION' in os.environ else os.environ.get('XDG_SESSION_TYPE', 'unknown')
def forceTimeSync() -> None:
return

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014-2019 Virtual Cable S.L.
# Copyright (c) 2014-2020 Virtual Cable S.L.U.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
@ -31,6 +31,7 @@
import sys
from .. import rest
from .. import platform
from ..log import logger
from .service import UDSActorSvc
@ -46,12 +47,10 @@ def run() -> None:
try:
client: rest.UDSClientApi = rest.UDSClientApi()
if sys.argv[1] == 'login':
r = client.login(sys.argv[2])
r = client.login(sys.argv[2], platform.operations.getSessionType())
print('{},{},{},{}\n'.format(r.ip, r.hostname, r.max_idle, r.dead_line or ''))
elif sys.argv[1] == 'logout':
client.logout(sys.argv[2])
else:
usage()
except Exception as e:
logger.exception()
logger.error('Got exception while processing command: %s', e)
@ -69,7 +68,7 @@ def run() -> None:
elif sys.argv[1] == 'restart':
daemonSvr.restart()
elif sys.argv[1] == 'start-foreground':
daemonSvr.run() # Esecute in foreground
daemonSvr.run() # Execute in foreground
else:
usage()
sys.exit(0)

View File

@ -45,6 +45,9 @@ LISTEN_PORT = 43910
# Default timeout
TIMEOUT = 5 # 5 seconds is more than enought
# Constants
UNKNOWN = 'unknown'
class RESTError(Exception):
ERRCODE = 0
@ -265,17 +268,18 @@ class UDSServerApi(UDSApi):
)
def login(self, own_token: str, username: str) -> types.LoginResultInfoType:
def login(self, own_token: str, username: str, sessionType: typing.Optional[str] = None) -> types.LoginResultInfoType:
if not own_token:
return types.LoginResultInfoType(
ip='0.0.0.0',
hostname='unknown',
hostname=UNKNOWN,
dead_line=None,
max_idle=None
)
payload = {
'token': own_token,
'username': username
'username': username,
'session_type': sessionType or UNKNOWN
}
result = self._doPost('login', payload)
return types.LoginResultInfoType(
@ -334,9 +338,10 @@ class UDSClientApi(UDSApi):
}
self._doPost('unregister', payLoad)
def login(self, username: str) -> types.LoginResultInfoType:
def login(self, username: str, sessionType: typing.Optional[str] = None) -> types.LoginResultInfoType:
payLoad = {
'username': username
'username': username,
'session_type': sessionType or UNKNOWN,
}
result = self._doPost('login', payLoad)
return types.LoginResultInfoType(

View File

@ -402,14 +402,14 @@ class CommonService: # pylint: disable=too-many-instance-attributes
logger.debug('Base join invoked: {} on {}, {}'.format(name, domain, ou))
# Client notifications
def login(self, username: str) -> types.LoginResultInfoType:
def login(self, username: str, sessionType: typing.Optional[str] = None) -> types.LoginResultInfoType:
result = types.LoginResultInfoType(ip='', hostname='', dead_line=None, max_idle=None)
self._loggedIn = True
if not self.isManaged():
self.initialize()
if self._cfg.own_token:
result = self._api.login(self._cfg.own_token, username)
result = self._api.login(self._cfg.own_token, username, sessionType)
return result

View File

@ -34,10 +34,10 @@ import os
import tempfile
import typing
import servicemanager # @UnresolvedImport, pylint: disable=import-error
import servicemanager # pylint: disable=import-error
# Valid logging levels, from UDS Broker (uds.core.utils.log).
from ..loglevel import OTHER, DEBUG, INFO, WARN, ERROR, FATAL
from .. import loglevel
class LocalLogger: # pylint: disable=too-few-public-methods
linux = False
@ -69,14 +69,14 @@ class LocalLogger: # pylint: disable=too-few-public-methods
if self.logger:
self.logger.log(int(level / 1000), message)
if level < ERROR or self.serviceLogger is False: # Only information and above will be on event log
if level < loglevel.ERROR or self.serviceLogger is False: # Only information and above will be on event log
return
# In fact, we have restricted level in windows event log to ERROR or FATAL
# but left the code for just a case in the future...
if level < WARN: # Info
if level < loglevel.WARN: # Info
servicemanager.LogInfoMsg(message)
elif level < ERROR: # WARN
elif level < loglevel.ERROR: # WARN
servicemanager.LogWarningMsg(message)
else: # Error & Fatal
servicemanager.LogErrorMsg(message)

View File

@ -223,6 +223,15 @@ def getCurrentUser() -> str:
'''
return os.environ['USERNAME']
def getSessionType() -> str:
'''
Known values:
* Unknown -> No SESSIONNAME environment variable
* Console -> Local session
* RDP-Tcp#[0-9]+ -> RDP Session
'''
return os.environ.get('SESSIONNAME', 'Unknown')
def writeToPipe(pipeName: str, bytesPayload: bytes, waitForResponse: bool) -> typing.Optional[bytes]:
# (str, bytes, bool) -> Optional[bytes]
try: