Ejemplo n.º 1
0
def fuse_mount(mountpoint, opts=None):
    if not isinstance(mountpoint, str):
        raise TypeError
    if opts is not None and not isinstance(opts, str):
        raise TypeError
    import dl
    try:
        fuse = dl.open('libfuse.so')
    except dl.error:
        fuse = dl.open('libfuse.so.2')
    if fuse.sym('fuse_mount_compat22'):
        fnname = 'fuse_mount_compat22'
    else:
        fnname = 'fuse_mount'  # older versions of libfuse.so
    return fuse.call(fnname, mountpoint, opts)
Ejemplo n.º 2
0
def fuse_mount(mountpoint, opts=None):
    if not isinstance(mountpoint, str):
        raise TypeError
    if opts is not None and not isinstance(opts, str):
        raise TypeError
    import dl
    try:
        fuse = dl.open('libfuse.so')
    except dl.error:
        fuse = dl.open('libfuse.so.2')
    if fuse.sym('fuse_mount_compat22'):
        fnname = 'fuse_mount_compat22'
    else:
        fnname = 'fuse_mount'     # older versions of libfuse.so
    return fuse.call(fnname, mountpoint, opts)
Ejemplo n.º 3
0
def main():
    DBusGMainLoop(set_as_default=True)

    global HAS_INDICATOR
    gtk.gdk.threads_init()
    config.loads();
    try:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        libc.prctl(15, 'hotot', 0, 0, 0)
    except:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'hotot', 0, 0, 0)

    agent.init_notify()
    app = Hotot()
    agent.app = app
    if HAS_INDICATOR:
        indicator = appindicator.Indicator('hotot',
                                            'hotot',
                                            appindicator.CATEGORY_COMMUNICATIONS,
                                            utils.get_ui_object('image'))
        indicator.set_status(appindicator.STATUS_ACTIVE)
        indicator.set_icon('ic24_hotot_mono_light')
        indicator.set_attention_icon('ic24_hotot_mono_light_blink')
        indicator.set_menu(app.menu_tray)
        app.indicator = indicator


    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
Ejemplo n.º 4
0
def renameprocess(newname, debug=False):
    errors = []
    # Renaming ourselves for ps et al.
    try:
        import procname

        procname.setprocname(newname)
    except:
        errors.append("Failed procname module")
        # Renaming ourselves for pkill et al.
    try:
        import ctypes

        # Linux style
        libc = ctypes.CDLL("libc.so.6")
        libc.prctl(15, newname, 0, 0, 0)
    except:
        errors.append("Failed linux style")
    try:
        import dl

        # FreeBSD style
        libc = dl.open("/lib/libc.so.6")
        libc.call("setproctitle", newname + "\0")
        renamed = True
    except:
        errors.append("Failed FreeBSD style")
    if debug and errors:
        msg = [_("Errors occured while trying to change process name:")]
        for i in errors:
            msg.append("%s" % (i,))
        log.addwarning("\n".join(msg))
Ejemplo n.º 5
0
def main():
    DBusGMainLoop(set_as_default=True)

    global HAS_INDICATOR
    gtk.gdk.threads_init()
    config.loads();
    try:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        libc.prctl(15, 'hermelin', 0, 0, 0)
    except:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'hermelin', 0, 0, 0)

    agent.init_notify()
    app = Hermelin()
    agent.app = app
    if HAS_INDICATOR:
        indicator = appindicator.Indicator('hermelin',
                                            'hermelin',
                                            appindicator.CATEGORY_COMMUNICATIONS,
                                            utils.get_ui_object('image'))
        indicator.set_status(appindicator.STATUS_ACTIVE)
        indicator.set_icon('ic24_hermelin_mono_light')
        indicator.set_attention_icon('ic24_hermelin_mono_light_blink')
        indicator.set_menu(app.menu_tray)
        app.indicator = indicator


    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
Ejemplo n.º 6
0
def main():
    global HAS_INDICATOR
    gtk.gdk.threads_init()
    config.loads();
    if config.get('no_use_indicator'):
        HAS_INDICATOR = False
    try:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'hotot', 0, 0, 0)
    except:
        pass
    agent.init_notify()
    app = MainWindow()
    agent.app = app
    if HAS_INDICATOR:
        #TODO the icon is only work when installed to /usr/share/icons/hicolor/
        indicator = appindicator.Indicator('hotot',
                                           'hotot',
                                           appindicator.CATEGORY_COMMUNICATIONS)
        indicator.set_status(appindicator.STATUS_ACTIVE)
        indicator.set_attention_icon(config.get_ui_object('imgs/ic64_hotot.png'))
        indicator.set_menu(app.menu_tray)
        pass
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
Ejemplo n.º 7
0
def renameprocess(newname, debug=False):

    errors = []

    # Renaming ourselves for ps et al.
    try:
        import procname
        procname.setprocname(newname)
    except:
        errors.append("Failed procname module")

    # Renaming ourselves for pkill et al.
    try:
        import ctypes
        # GNU/Linux style
        libc = ctypes.CDLL('libc.so.6')
        libc.prctl(15, newname, 0, 0, 0)
    except:
        errors.append("Failed GNU/Linux style")

    try:
        import dl
        # FreeBSD style
        libc = dl.open('/lib/libc.so.6')
        libc.call('setproctitle', newname + '\0')
        renamed = True
    except:
        errors.append("Failed FreeBSD style")

    if debug and errors:
        msg = [_("Errors occured while trying to change process name:")]
        for i in errors:
            msg.append("%s" % (i, ))
        log.addwarning('\n'.join(msg))
Ejemplo n.º 8
0
Archivo: hotot.py Proyecto: fma16/Hotot
def main():
    global HAS_INDICATOR
    gtk.gdk.threads_init()
    config.loads();
    try:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        libc.prctl(15, 'hotot', 0, 0, 0)
    except:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'hotot', 0, 0, 0)
        
    agent.init_notify()
    app = Hotot()
    agent.app = app
    if HAS_INDICATOR:
        indicator = appindicator.Indicator('hotot',
                                            'hotot',
                                            appindicator.CATEGORY_COMMUNICATIONS)
        indicator.set_status(appindicator.STATUS_ACTIVE)
        indicator.set_icon(utils.get_ui_object('image/ic24_hotot_mono_light.svg'))
        indicator.set_attention_icon(utils.get_ui_object('image/ic24_hotot_mono_dark.svg'))
        indicator.set_menu(app.menu_tray)
        app.indicator = indicator

    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
    HDService = HototDbusService(app)

    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
Ejemplo n.º 9
0
    def __init__(self, svc):
        super(HephaestusMonTool, self).__init__()
        self.svc = svc
        self.name = svc.name + ".Heph"
        self.lag = 2  # event lag between execute and report
        # guard against not correctly initialized Hephaestus
        # This can happen when e.g. an error occurs during initialize
        # preventing Hephaestus to install a checkPoint, leading to a segfault
        # during our finalize.
        self._heph_has_checkPoint = False
        import sys
        if not 'Hephaestus.atexit' in sys.modules.keys():
            self.msg.warning('Hephaestus was not correctly initialized !')
            self.msg.warning('Final report may be inaccurate...')
            self.msg.warning('(to fix this, run athena with --leak-check)')

        import dl, Hephaestus.MemoryTracker as m
        _hephLib = dl.open(m.__file__, dl.RTLD_GLOBAL | dl.RTLD_NOW)
        memtrack = m

        from os.path import splitext
        self.outFileName = splitext(self.svc.outFileName)[0] + '.heph.log'
        outFile = open(self.outFileName, 'w')
        from time import gmtime, strftime
        now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

        outFile.writelines([
            "#" * 80 + os.linesep,
            "## Report file for Hephaestus [%s]" % outFile.name + os.linesep,
            "## %s" % now + os.linesep,
            "#" * 80 + os.linesep,
        ])
        outFile.flush()

        memtrack.outstream(outFile)
Ejemplo n.º 10
0
def rename_process(name):
    """rename process by libc"""
    if os.name == 'posix':
        try:
            libc = dl.open('/lib/libc.so.6')
            libc.call('prctl', 15, '%s\0' % name, 0, 0, 0)
        except:
            pass
Ejemplo n.º 11
0
def rename_process(name):
    """rename process by libc"""
    if os.name == 'posix':
        try:
            libc = dl.open('/lib/libc.so.6')
            libc.call('prctl', 15, '%s\0' % name, 0, 0, 0)
        except:
            pass
Ejemplo n.º 12
0
 def mcast(self, iface):
     """set IP6 connector into multicast mode"""
     import dl
     _libc = dl.open('libc.so')
     ifn = _libc.call('if_nametoindex', iface)
     self.sock.setsockopt(IPPROTO_IPV6, IPV6_MULTICAST_LOOP, 1)
     self.sock.setsockopt(IPPROTO_IPV6, IPV6_MULTICAST_HOPS, 5)
     self.sock.setsockopt(IPPROTO_IPV6, IPV6_MULTICAST_IF, ifn)
Ejemplo n.º 13
0
def define_process_name():
    '''自定义python程序进程名'''
    procname = 'Hello'
    import os, sys
    if not os.environ.has_key('NEWPROCNAME'):
        os.execlpe(sys.executable, procname, __file__, {'NEWPROCNAME': procname})
    import dl
    libc = dl.open('/lib/libc.so.6')
    libc.call('prctl', 15, '%s\0' %procname, 0, 0, 0)
Ejemplo n.º 14
0
def main():
	global clients, clients_mutex, pypy
	print
	print "OpenWebRX - Open Source Web Based SDR for Everyone  | for license see LICENSE file in the package"
	print "_________________________________________________________________________________________________"
	print 
	print "Author contact info:    Andras Retzler, HA7ILM <*****@*****.**>"
	print 

	#Set signal handler
	signal.signal(signal.SIGINT, handle_signal) #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python

	#Load plugins
	import_all_plugins("plugins/dsp/")

	#Pypy
	if pypy: print "pypy detected (and now something completely different: a c code is expected to run at a speed of 3*10^8 m/s?)"

	#Change process name to "openwebrx" (to be seen in ps)
	try:
		for libcpath in ["/lib/i386-linux-gnu/libc.so.6","/lib/libc.so.6"]:
			if os.path.exists(libcpath):
				libc = dl.open(libcpath)
				libc.call("prctl", 15, "openwebrx", 0, 0, 0)
				break
	except:
		pass

	#Start rtl thread
	if cfg.start_rtl_thread:
		rtl_thread=threading.Thread(target = lambda:subprocess.Popen(cfg.start_rtl_command, shell=True), args=())
		rtl_thread.start()
		print "[openwebrx-main] Started rtl thread: "+cfg.start_rtl_command

	#Run rtl_mus.py in a different OS thread
	python_command="pypy" if pypy else "python2"
	rtl_mus_thread=threading.Thread(target = lambda:subprocess.Popen(python_command+" rtl_mus.py config_rtl", shell=True), args=())
	rtl_mus_thread.start() # The new feature in GNU Radio 3.7: top_block() locks up ALL python threads until it gets the TCP connection.
	print "[openwebrx-main] Started rtl_mus."
	time.sleep(1) #wait until it really starts	

	#Initialize clients
	clients=[]
	clients_mutex=threading.Lock()

	#Start spectrum thread
	print "[openwebrx-main] Starting spectrum thread."
	spectrum_thread=threading.Thread(target = spectrum_thread_function, args = ())
	spectrum_thread.start()
	
	#threading.Thread(target = measure_thread_function, args = ()).start()
	
	#Start HTTP thread
	httpd = MultiThreadHTTPServer(('', cfg.web_port), WebRXHandler)
	print('[openwebrx-main] Starting HTTP server.')
	httpd.serve_forever()
Ejemplo n.º 15
0
def setprocname(procname, libc='/lib/libc.so.6', env='__PROCNAME', format='%s:'):
	import os, sys
	if not os.environ.has_key(env):
		kw = dict(os.environ); kw[env] = procname
		os.execlpe(*([sys.executable, format%procname] + sys.argv + [kw]))

	import dl
	libc = dl.open(libc)

	platform = sys.platform.upper()
	if 'LINUX' in platform:
		libc.call('prctl', 15, '%s\0' %procname, 0, 0, 0)
	elif 'BSD' in platform:
		libc.call('setproctitle', '%s\0' %procname)
Ejemplo n.º 16
0
def setprocname(name=None):
    if not dl_mod: return False
    
    if name==None:
        name = sys.argv[0].split('/')[-1]

    for libc_path in libc_options:
        if os.path.exists(libc_path):
            try:
                libc = dl.open(libc_path)
                libc.call('prctl', 15, name, 0, 0, 0)
                return True
            except:
                return False
    return False
Ejemplo n.º 17
0
    def __init__(self, rootfile, scene=Scene):
        if _DEBUG: print "OpioidInterface.__init__"
        try:
            # for process watching purposes
            import dl #@UnresolvedImport
            libc = dl.open('/lib/libc.so.6')
            libc.call('prctl', 15, 'python_pig', 0, 0, 0)
        except:
            # we're probably not in linux
            pass
        rootfile = fix_project_path(rootfile)
        projectPath = os.path.dirname(os.path.realpath(rootfile))
        set_project_path( projectPath)
        self.project_name = os.path.split(projectPath)[1]

        self.import_settings()
        if getattr(self.project_settings, 'title'):
            self.project_name = self.project_settings.title 

        self.Display = Opioid2D.Display
        self.Director = Director   
        self.Director.editorMode = True
        opioid_rect = self.pug_settings.rect_opioid_window # x, y, w, h
        thread.start_new_thread(self.start_opioid, 
                                          (opioid_rect,
                                           os.path.split(projectPath)[1],
                                           get_image_path('pug.png'),
                                           StartScene))
        
        # wait for scene to load
        while not getattr(self.Director, 'scene', False):
            time.sleep(0.001)

        pug.App(projectObject=self, 
                      projectFolder=get_project_path(),
                      projectObjectName=self.project_name)
        if _DEBUG: print "OpioidInterface done with loop. Director.realquit"
        self.Director.realquit()
        try:
            if _DEBUG: print "OpioidInterface: wx.GetApp().Exit()"
            wx.GetApp().Exit()
            if _DEBUG: print "OpioidInterface: wx.GetApp().Exit() done"
            raise SystemExit
        except:
            pass
Ejemplo n.º 18
0
def setprocname(procname,
                libc='/lib/libc.so.6',
                env='__PROCNAME',
                format='%s:'):
    import os, sys
    if not os.environ.has_key(env):
        kw = dict(os.environ)
        kw[env] = procname
        os.execlpe(*([sys.executable, format % procname] + sys.argv + [kw]))

    import dl
    libc = dl.open(libc)

    platform = sys.platform.upper()
    if 'LINUX' in platform:
        libc.call('prctl', 15, '%s\0' % procname, 0, 0, 0)
    elif 'BSD' in platform:
        libc.call('setproctitle', '%s\0' % procname)
Ejemplo n.º 19
0
def plaunch():
    try:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, PROCESS, 0, 0, 0)
    except:
        quit() 
    from HotKey_Linux import KeyHook
    gobject.threads_init()
    statusicon = PLaunchStatusIcon()
    hotkey = KeyHook(statusicon.maindialog.open_main)   
    #thread.start_new_thread(hotkey.start, ())
    hotkey.start()
    try:
        gtk.main()
    except KeyboardInterrupt:
        print 'User Cancled.'
    hotkey.stop()
Ejemplo n.º 20
0
	def __init__(self,listname=None,debug=False):	#listname is just a name , not a path!!!
		import dl
		libc = dl.open('/lib/libc.so.6')
		libc.call('prctl',15,'musicmanager',0,0,0)	#set process name to 'musicmanager'
		self.USER_HOME=os.environ['HOME']
		self.MUSIC_HOME=os.path.join(self.USER_HOME,'Music')
		self.PROGRAM_HOME=os.path.join(self.USER_HOME,'.musicmanager')
		self.LIST_HOME=os.path.join(self.PROGRAM_HOME,'musiclist')

		if os.path.isdir(self.PROGRAM_HOME) == False:	#no ~/.musicmanager
			os.makedirs(self.PROGRAM_HOME)
			os.makedirs(self.LIST_HOME)	#list is in there

		if debug:
			print('USER_HOME='+self.USER_HOME)
			print('MUSIC_HOME='+self.MUSIC_HOME)
			print('PROGRAM_HOME='+self.PROGRAM_HOME)
			print('LIST_HOME='+self.LIST_HOME)
Ejemplo n.º 21
0
    def __init__(self, rootfile, scene=Scene):
        if _DEBUG: print "OpioidInterface.__init__"
        try:
            # for process watching purposes
            import dl  #@UnresolvedImport
            libc = dl.open('/lib/libc.so.6')
            libc.call('prctl', 15, 'python_pig', 0, 0, 0)
        except:
            # we're probably not in linux
            pass
        rootfile = fix_project_path(rootfile)
        projectPath = os.path.dirname(os.path.realpath(rootfile))
        set_project_path(projectPath)
        self.project_name = os.path.split(projectPath)[1]

        self.import_settings()
        if getattr(self.project_settings, 'title'):
            self.project_name = self.project_settings.title

        self.Display = Opioid2D.Display
        self.Director = Director
        self.Director.editorMode = True
        opioid_rect = self.pug_settings.rect_opioid_window  # x, y, w, h
        thread.start_new_thread(self.start_opioid,
                                (opioid_rect, os.path.split(projectPath)[1],
                                 get_image_path('pug.png'), StartScene))

        # wait for scene to load
        while not getattr(self.Director, 'scene', False):
            time.sleep(0.001)

        pug.App(projectObject=self,
                projectFolder=get_project_path(),
                projectObjectName=self.project_name)
        if _DEBUG: print "OpioidInterface done with loop. Director.realquit"
        self.Director.realquit()
        try:
            if _DEBUG: print "OpioidInterface: wx.GetApp().Exit()"
            wx.GetApp().Exit()
            if _DEBUG: print "OpioidInterface: wx.GetApp().Exit() done"
            raise SystemExit
        except:
            pass
Ejemplo n.º 22
0
    def __init__(self,
                 listname=None,
                 debug=False):  #listname is just a name , not a path!!!
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'musicmanager', 0, 0,
                  0)  #set process name to 'musicmanager'
        self.USER_HOME = os.environ['HOME']
        self.MUSIC_HOME = os.path.join(self.USER_HOME, 'Music')
        self.PROGRAM_HOME = os.path.join(self.USER_HOME, '.musicmanager')
        self.LIST_HOME = os.path.join(self.PROGRAM_HOME, 'musiclist')

        if os.path.isdir(self.PROGRAM_HOME) == False:  #no ~/.musicmanager
            os.makedirs(self.PROGRAM_HOME)
            os.makedirs(self.LIST_HOME)  #list is in there

        if debug:
            print('USER_HOME=' + self.USER_HOME)
            print('MUSIC_HOME=' + self.MUSIC_HOME)
            print('PROGRAM_HOME=' + self.PROGRAM_HOME)
            print('LIST_HOME=' + self.LIST_HOME)
Ejemplo n.º 23
0
def setprocname(name):
    # From comments on http://davyd.livejournal.com/166352.html
    try:
        # For Python-2.5
        import ctypes
        libc = ctypes.CDLL(None)
        # Linux 2.6 PR_SET_NAME
        if libc.prctl(15, name, 0, 0, 0):
            # BSD
            libc.setproctitle(name)
    except:
        try:
            # For 32 bit
            import dl
            libc = dl.open(None)
            name += '\0'
            # Linux 2.6 PR_SET_NAME
            if libc.call('prctl', 15, name, 0, 0, 0):
                # BSD
                libc.call('setproctitle', name)
        except:
            pass
Ejemplo n.º 24
0
def main():
    DBusGMainLoop(set_as_default=True)

    global HAS_INDICATOR
    gtk.gdk.threads_init()
    config.loads();
    try:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        libc.prctl(15, 'hotot', 0, 0, 0)
    except:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'hotot', 0, 0, 0)

    agent.init_notify()
    app = Hotot()
    agent.app = app
    if HAS_INDICATOR:
        indicator = appindicator.Indicator('hotot',
                                            'hotot',
                                            appindicator.CATEGORY_COMMUNICATIONS,
                                            utils.get_ui_object('image'))
        indicator.set_status(appindicator.STATUS_ACTIVE)
        indicator.set_icon('ic24_hotot_mono_light')
        indicator.set_attention_icon('ic24_hotot_mono_light_blink')
        indicator.set_menu(app.menu_tray)
        app.indicator = indicator

    # Set display functions (MeMenu)
    if HAS_MEMENU:
        global ind_server, indicator_unread
        ind_server.connect("server-display", app.on_mitem_resume_activate)
        indicator_unread.connect("user-display", app.on_mitem_resume_activate) 

    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
Ejemplo n.º 25
0
def main():
    global HAS_INDICATOR
    gtk.gdk.threads_init()
    config.loads();
    try:
        import dl
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'hotot', 0, 0, 0)
    except:
        pass
    agent.init_notify()
    app = Hotot()
    agent.app = app
    if HAS_INDICATOR:
        indicator = appindicator.Indicator('hotot',
                                           'hotot',
                                           appindicator.CATEGORY_COMMUNICATIONS)
        indicator.set_status(appindicator.STATUS_ACTIVE)
        indicator.set_attention_icon(utils.get_ui_object('image/ic24_hotot_mono_light.svg'))
        indicator.set_menu(app.menu_tray)
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
Ejemplo n.º 26
0
def set_process_name(name):
    try:
        import dl
    except ImportError:
        try:
            import ctypes
        except ImportError:
            pass
        else:
            try:
                libc = ctypes.CDLL('libc.so.6')
            except OSError:
                pass
            else:
                libc.prctl(15, name, 0, 0, 0)
                # FreeBSD: libc.setproctitle(name)
    else:
        try:
            libc = dl.open('/lib/libc.so.6')
        except (OSError, dl.error):
            pass
        else:
            libc.call('prctl', 15, name+'\0', 0, 0, 0)
Ejemplo n.º 27
0
import dl
from test.test_support import verbose,TestSkipped

sharedlibs = [
    ('/usr/lib/libc.so', 'getpid'),
    ('/lib/libc.so.6', 'getpid'),
    ('/usr/bin/cygwin1.dll', 'getpid'),
    ('/usr/lib/libc.dylib', 'getpid'),
    ]

for s, func in sharedlibs:
    try:
        if verbose:
            print 'trying to open:', s,
        l = dl.open(s)
    except dl.error, err:
        if verbose:
            print 'failed', repr(str(err))
        pass
    else:
        if verbose:
            print 'succeeded...',
        l.call(func)
        l.close()
        if verbose:
            print 'worked!'
        break
else:
    raise TestSkipped, 'Could not open any shared libraries'
Ejemplo n.º 28
0
    print e
    sys.exit(1)

GObject.threads_init()

gdk = CDLL("libgdk-x11-2.0.so.0")

# Rename the process
architecture = commands.getoutput("uname -a")
if (architecture.find("x86_64") >= 0):
    libc = CDLL('libc.so.6')
    libc.prctl(15, 'devuanmenu', 0, 0, 0)
else:
    import dl
    if os.path.exists('/lib/libc.so.6'):
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'devuanmenu', 0, 0, 0)
    elif os.path.exists('/lib/i386-linux-gnu/libc.so.6'):
        libc = dl.open('/lib/i386-linux-gnu/libc.so.6')
        libc.call('prctl', 15, 'devuanmenu', 0, 0, 0)

# i18n
gettext.install("devuanmenu", "/usr/share/devuan/locale")

NAME = _("Menu")
PATH = os.path.abspath(os.path.dirname(sys.argv[0]))

sys.path.append(os.path.join(PATH, "plugins"))

windowManager = os.getenv("DESKTOP_SESSION")
if not windowManager:
Ejemplo n.º 29
0
	print e
	sys.exit( 1 )

global mbindkey
# Load the key binding lib (developped by deskbar-applet, copied into mintMenu so we don't end up with an unnecessary dependency)
try:
	from deskbar.core.keybinder import tomboy_keybinder_bind as bind_key
except Exception, cause:
        print "*********** Keybind Driver Load Failure **************"
        print "Error Report : ", str(cause)
        pass

# Rename the process
try:
	import dl
	libc = dl.open( "/lib/libc.so.6" )
	libc.call( "prctl", 15, "mintmenu", 0, 0, 0 )
	libc.close()
except ImportError:
	pass

# i18n
gettext.install("mintmenu", "/usr/share/linuxmint/locale")

NAME = _("Menu")
PATH = os.path.abspath( os.path.dirname( sys.argv[0] ) )

ICON = "/usr/lib/linuxmint/mintMenu/mintMenu.png"

sys.path.append( os.path.join( PATH , "plugins") )
Ejemplo n.º 30
0
def xattr_detect():
    import os
    import sys
    is_linux = sys.platform.startswith('linux')
    implspec = os.getenv('PYTHON_XATTR_IMPL', '')

    try:
        if (implspec and implspec != 'ctypes') or not is_linux:
            # TODO(pts): Also support Mac OS X, similarly to
            # ppfiletagger_shell_functions does it (with syscall).
            raise ImportError
        import ctypes
        import errno
        try:
            LIBC_CTYPES = ctypes.CDLL(None)  # Also: 'libc.so.6'.
        except EnvironmentError:
            LIBC_CTYPES = None
        try:
            if LIBC_CTYPES and LIBC_CTYPES['lgetxattr']:
                return xattr_impl_ctypes
        except (KeyError, AttributeError):
            pass
    except ImportError:
        pass

    try:
        if (implspec and implspec != 'dl') or not is_linux:
            raise ImportError
        import struct
        import dl  # Only 32-bit architectures, e.g. i386.
        import errno
        try:
            LIBC_DL = dl.open(None)  # Also: dl.open('libc.so.6')
        except dl.error:
            LIBC_DL = None
        if (LIBC_DL and LIBC_DL.sym('memcpy')
                and LIBC_DL.sym('__errno_location')
                and LIBC_DL.sym('lgetxattr')):
            return xattr_impl_dl
    except ImportError:
        pass

    # We try this last, because it does 2 syscalls by default.
    try:
        import xattr
        # pyxattr <0.2.2 are buggy.
        if getattr(xattr, '__version__', '') < '0.2.2':
            xattr = None
    except ImportError:
        xattr = None
    if xattr is None and __import__('sys').platform.startswith('linux'):
        v1, v2 = __import__('sys').version_info[:2]
        a = __import__('os').uname()[4]  # Kernel architecture.
        if a in ('x86', '386', '486', '586', '686', 'ia32', 'x86_64', 'amd64',
                 'em64t'):
            # This is not accurata e.g. with qemu-user-arm.
            a = ('i386', 'amd64'
                 )[__import__('struct').calcsize('P') == 8]  # Pointer size.
        else:
            a = a.replace('-', '_')
        import os.path
        d = __file__
        for _ in __name__.split('.'):
            d = os.path.dirname(d)
        d = os.path.join(d, 'ppfiletagger', 'py%d%d_linux_%s' % (v1, v2, a))
        if os.path.isfile(os.path.join(d, 'xattr.so')):
            __import__('sys').path[:0] = (d, )
            try:
                try:
                    # TODO(pts): Do it as a non-global import.
                    import xattr
                    # pyxattr <0.2.2 are buggy.
                    if getattr(xattr, '__version__', '') < '0.2.2':
                        xattr = None
                    #a = ''  # Always remove from path.
                except ImportError:
                    xattr = None
            finally:
                if a and d in __import__('sys').path:
                    __import__('sys').path.remove(d)
        del v1, v2, a, d
    if xattr:
        if (not (implspec and implspec != 'xattr_xattr') and is_linux
                and getattr(xattr, '_xattr', None)
                and getattr(xattr._xattr, 'getxattr', None)):
            # This works with python-xattr, but not with python-pyxattr.
            return xattr_impl_xattr_xattr
        elif not (implspec and implspec != 'xattr'):
            # This works with python-xattr and python-pyxattr.
            return xattr_impl_xattr

    raise NotImplementedError(
        'xattr implementation not found or too old. Please install xattr (python-xattr) or ctypes.'
    )
Ejemplo n.º 31
0
def main():
    global clients, clients_mutex, pypy, lock_try_time, avatar_ctime
    print
    print "OpenWebRX - Open Source SDR Web App for Everyone!  | for license see LICENSE file in the package"
    print "_________________________________________________________________________________________________"
    print
    print "Author contact info:    Andras Retzler, HA7ILM <*****@*****.**>"
    print

    #Set signal handler
    signal.signal(
        signal.SIGINT, handle_signal
    )  #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python

    #Load plugins
    import_all_plugins("plugins/dsp/")

    #Pypy
    if pypy:
        print "pypy detected (and now something completely different: a c code is expected to run at a speed of 3*10^8 m/s?)"

    #Change process name to "openwebrx" (to be seen in ps)
    try:
        for libcpath in ["/lib/i386-linux-gnu/libc.so.6", "/lib/libc.so.6"]:
            if os.path.exists(libcpath):
                libc = dl.open(libcpath)
                libc.call("prctl", 15, "openwebrx", 0, 0, 0)
                break
    except:
        pass

    #Start rtl thread
    if cfg.start_rtl_thread:
        rtl_thread = threading.Thread(
            target=lambda: subprocess.Popen(cfg.start_rtl_command, shell=True),
            args=())
        rtl_thread.start()
        print "[openwebrx-main] Started rtl thread: " + cfg.start_rtl_command

    #Run rtl_mus.py in a different OS thread
    python_command = "pypy" if pypy else "python2"
    rtl_mus_thread = threading.Thread(target=lambda: subprocess.Popen(
        python_command + " rtl_mus.py config_rtl", shell=True),
                                      args=())
    rtl_mus_thread.start(
    )  # The new feature in GNU Radio 3.7: top_block() locks up ALL python threads until it gets the TCP connection.
    print "[openwebrx-main] Started rtl_mus."
    time.sleep(1)  #wait until it really starts

    #Initialize clients
    clients = []
    clients_mutex = threading.Lock()
    lock_try_time = 0

    #Start watchdog thread
    print "[openwebrx-main] Starting watchdog threads."
    mutex_test_thread = threading.Thread(target=mutex_test_thread_function,
                                         args=())
    mutex_test_thread.start()
    mutex_watchdog_thread = threading.Thread(
        target=mutex_watchdog_thread_function, args=())
    mutex_watchdog_thread.start()

    #Start spectrum thread
    print "[openwebrx-main] Starting spectrum thread."
    spectrum_thread = threading.Thread(target=spectrum_thread_function,
                                       args=())
    spectrum_thread.start()

    get_cpu_usage()
    bcastmsg_thread = threading.Thread(target=bcastmsg_thread_function,
                                       args=())
    bcastmsg_thread.start()

    #threading.Thread(target = measure_thread_function, args = ()).start()

    #Start sdr.hu update thread
    if sdrhu and cfg.sdrhu_key and cfg.sdrhu_public_listing:
        print "[openwebrx-main] Starting sdr.hu update thread..."
        sdrhu_thread = threading.Thread(target=sdrhu.run, args=())
        sdrhu_thread.start()
        avatar_ctime = str(os.path.getctime("htdocs/gfx/openwebrx-avatar.png"))

    #Start HTTP thread
    httpd = MultiThreadHTTPServer(('', cfg.web_port), WebRXHandler)
    print('[openwebrx-main] Starting HTTP server.')
    httpd.serve_forever()
Ejemplo n.º 32
0
    server_core = server_asyncore()

    asyncore.loop(0.1)


if __name__ == "__main__":
    print
    print "rtl_mus: Multi-User I/Q Data Server for RTL-SDR v0.22, made at HA5KFU Amateur Radio Club (http://ha5kfu.hu)"
    print "    code by Andras Retzler, HA7ILM <*****@*****.**>"
    print "    distributed under GNU GPL v3"
    print

    try:
        for libcpath in ["/lib/i386-linux-gnu/libc.so.6", "/lib/libc.so.6"]:
            if os.path.exists(libcpath):
                libc = dl.open(libcpath)
                libc.call("prctl", 15, "rtl_mus", 0, 0, 0)
                break
    except:
        pass

    # === Load configuration script ===
    if len(sys.argv) == 1:
        print "[rtl_mus] Warning! Configuration script not specified. I will use: \"config_rtl.py\""
        config_script = "config_rtl"
    else:
        config_script = sys.argv[1]
    cfg = __import__(config_script)
    if cfg.setuid_on_start:
        os.setuid(cfg.uid)
    main()
Ejemplo n.º 33
0
#
# Read rates from online IS server (or "public" mirror)
#
# Results are one rate per lumiblock
#

#print 'Hello world TrigCostIS.py'

import dl
import math
import os
import sys
import time
#print '\tLoaded standard packages'

dl.open("libers.so", dl.RTLD_GLOBAL| dl.RTLD_NOW) #

try:
    import ipc;  #print '\tLoaded special ipc'
except:
    print 'WARNING -- TrigCostIS -- Cannot load module `ipc`. Set-up release for AtlasCAFHLT or AtlasP1HLT.'

try:
    from ispy import *;  #print '\tLoaded special ispy'
except:
    print 'WARNING -- TrigCostIS -- Cannot load module `ispy`. Set-up release for AtlasCAFHLT or AtlasP1HLT.'

from TrigCostPython import TrigCostAnalysis # print '\tLoaded special TrigCostPython.TrigCostAnalysis package'
from TrigCostPython import TrigCostXML      # print '\tLoaded special TrigCostPython.TrigCostXML package'
#print '\tDone prelim import for TrigCostIS'
Ejemplo n.º 34
0
except ImportError:
    addfunc = None

import pyaddfunc

import ctypes

# ______________________________________________________________________

with open('add42_%s.ll' % platform.architecture()[0]) as src_file:
    add42_module = lc.Module.from_assembly(src_file)

ee = le.ExecutionEngine.new(add42_module)

if dl and addfunc:
    add42_dl_ptr = dl.open('./addfunc.so').sym('addfunc_add42')

    if __debug__:
        print("add42_dl_ptr = %s" % hex(add42_dl_ptr))

    add42_dl = addfunc.addfunc("add42_dl", add42_dl_ptr)

add42_llvm_fn = add42_module.get_function_named('add42')

if __debug__:
    print add42_llvm_fn
    print add42_module.to_native_assembly()

add42_llvm_ptr = ee.get_pointer_to_function(add42_llvm_fn)

if __debug__:
Ejemplo n.º 35
0
 def itimer(seconds, libc=dl.open('libc.so.6')):
     sec = int(seconds)
     msec = int((seconds - sec) * 1e6)
     timeval = array.array('I', [0, 0, sec, msec])
     if libc.call('setitimer', 0, timeval.buffer_info()[0], 0) == -1:
         raise RuntimeError("Who knows what")
Ejemplo n.º 36
0
	server_core = server_asyncore()

	asyncore.loop(0.1)


if __name__=="__main__":
	print
	print "rtl_mus: Multi-User I/Q Data Server for RTL-SDR v0.22, made at HA5KFU Amateur Radio Club (http://ha5kfu.hu)"
	print "    code by Andras Retzler, HA7ILM <*****@*****.**>"
	print "    distributed under GNU GPL v3"
	print 

	try:
		for libcpath in ["/lib/i386-linux-gnu/libc.so.6","/lib/libc.so.6"]:
			if os.path.exists(libcpath):
				libc = dl.open(libcpath)
				libc.call("prctl", 15, "rtl_mus", 0, 0, 0)
				break
	except:
		pass

	# === Load configuration script ===
	if len(sys.argv)==1:
		print "[rtl_mus] Warning! Configuration script not specified. I will use: \"config_rtl.py\""
		config_script="config_rtl"
	else:
		config_script=sys.argv[1]
	cfg=__import__(config_script)
	if cfg.setuid_on_start:
		os.setuid(cfg.uid)
	main()
Ejemplo n.º 37
0
 def _hephLib(self):
     import dl, Hephaestus.MemoryTracker as m
     return dl.open(m.__file__, dl.RTLD_GLOBAL | dl.RTLD_NOW)
Ejemplo n.º 38
0
def xattr_impl_dl():
    import dl  # Only i386, in Python >= 2.4.
    import errno
    import os
    import struct

    LIBC_DL = dl.open(None)
    XATTR_ENOATTR = getattr(errno, 'ENOATTR', getattr(errno, 'ENODATA', 0))
    XATTR_ERANGE = errno.ERANGE
    del errno  # Save memory.
    assert struct.calcsize('l') == 4  # 8 on amd64.

    def getxattr(filename, attr_name, do_not_follow_symlinks=False):
        getxattr_name = ('getxattr', 'lgetxattr')[bool(do_not_follow_symlinks)]
        # TODO(pts): Do we need to protect errno in multithreaded code?
        errno_loc = LIBC_DL.call('__errno_location')
        err_str = 'X' * 4
        value = 'x' * 256
        got = LIBC_DL.call(getxattr_name, filename, attr_name, value,
                           len(value))
        if got < 0:
            LIBC_DL.call('memcpy', err_str, errno_loc, 4)
            err = struct.unpack('i', err_str)[0]
            if err == XATTR_ENOATTR:
                # The file exists, but doesn't have the specified xattr.
                return None
            elif err != XATTR_ERANGE:
                raise OSError(err, '%s: %r' % (os.strerror(err), filename))
            got = LIBC_DL.call(getxattr_name, filename, attr_name, None, 0)
            if got < 0:
                LIBC_DL.call('memcpy', err_str, errno_loc, 4)
                err = struct.unpack('i', err_str)[0]
                raise OSError(err, '%s: %r' % (os.strerror(err), filename))
            assert got > len(value)
            value = 'x' * got
            # We have a race condition here, someone might have changed the xattr
            # by now.
            got = LIBC_DL.call(getxattr_name, filename, attr_name, value, got)
            if got < 0:
                LIBC_DL.call('memcpy', err_str, errno_loc, 4)
                err = struct.unpack('i', err_str)[0]
                raise OSError(err, '%s: %r' % (os.strerror(err), filename))
            return value
        assert got <= len(value)
        return value[:got]

    def listxattr(filename, do_not_follow_symlinks=False):
        listxattr_name = ('listxattr',
                          'llistxattr')[bool(do_not_follow_symlinks)]
        errno_loc = LIBC_DL.call('__errno_location')
        err_str = 'X' * 4
        value = 'x' * 256
        got = LIBC_DL.call(listxattr_name, filename, value, len(value))
        if got < 0:
            LIBC_DL.call('memcpy', err_str, errno_loc, 4)
            err = struct.unpack('i', err_str)[0]
            if err != XATTR_ERANGE:
                raise OSError(err, '%s: %r' % (os.strerror(err), filename))
            got = LIBC_DL.call(listxattr_name, filename, None, 0)
            if got < 0:
                LIBC_DL.call('memcpy', err_str, errno_loc, 4)
                err = struct.unpack('i', err_str)[0]
                raise OSError(err, '%s: %r' % (os.strerror(err), filename))
            assert got > len(value)
            value = 'x' * got
            # We have a race condition here, someone might have changed the xattr
            # by now.
            got = LIBC_DL.call(listxattr_name, filename, value, got)
            if got < 0:
                LIBC_DL.call('memcpy', err_str, errno_loc, 4)
                err = struct.unpack('i', err_str)[0]
                raise OSError(err, '%s: %r' % (os.strerror(err), filename))
        if got:
            assert got <= len(value)
            assert value[got - 1] == '\0'
            return value[:got - 1].split('\0')
        else:
            return []

    return dict(
        _xattr_doc(k, v) for k, v in locals().iteritems() if k in XATTR_KEYS)
Ejemplo n.º 39
0
# i18n
gettext.install("mintinstall", "/usr/share/linuxmint/locale")

# i18n for menu item
menuName = _("Software Manager")
menuComment = _("Install new applications")

architecture = commands.getoutput("uname -a")
if (architecture.find("x86_64") >= 0):
	import ctypes
	libc = ctypes.CDLL('libc.so.6')
	libc.prctl(15, 'mintInstall', 0, 0, 0)	
else:
	import dl
	libc = dl.open('/lib/libc.so.6')
	libc.call('prctl', 15, 'mintInstall', 0, 0, 0)

global cache
import apt
cache = apt.Cache()
global num_apps
num_apps = 0

def close_application(window, event=None):	
	gtk.main_quit()
	sys.exit(0)

def close_window(widget, window):	
	window.hide_all()
Ejemplo n.º 40
0
def main():
    global clients, clients_mutex, pypy, lock_try_time, avatar_ctime, cfg, logs
    global serverfail, rtl_thread
    print
    print "OpenWebRX - Open Source SDR Web App for Everyone!  | for license see LICENSE file in the package"
    print "_________________________________________________________________________________________________"
    print
    print "Author contact info:    Andras Retzler, HA7ILM <*****@*****.**>"
    print

    no_arguments=len(sys.argv)==1
    if no_arguments: print "[openwebrx-main] Configuration script not specified. I will use: \"config_webrx.py\""
    cfg=__import__("config_webrx" if no_arguments else sys.argv[1])
    for option in ("access_log","csdr_dynamic_bufsize","csdr_print_bufsizes","csdr_through"):
        if not option in dir(cfg): setattr(cfg, option, False) #initialize optional config parameters

    #Open log files
    logs = type("logs_class", (object,), {"access_log":open(cfg.access_log if cfg.access_log else "/dev/null","a"), "error_log":""})()

    #Set signal handler
    signal.signal(signal.SIGINT, handle_signal) #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
    signal.signal(signal.SIGUSR1, handle_signal)
    signal.signal(signal.SIGUSR2, handle_signal)

    #Pypy
    if pypy: print "pypy detected (and now something completely different: c code is expected to run at a speed of 3*10^8 m/s?)"

    #Change process name to "openwebrx" (to be seen in ps)
    try:
        for libcpath in ["/lib/i386-linux-gnu/libc.so.6","/lib/libc.so.6"]:
            if os.path.exists(libcpath):
                libc = dl.open(libcpath)
                libc.call("prctl", 15, "openwebrx", 0, 0, 0)
                break
    except:
        pass

    #Start rtl thread
    if os.system("csdr 2> /dev/null") == 32512: #check for csdr
        print "[openwebrx-main] You need to install \"csdr\" to run OpenWebRX!\n"
        return
    if os.system("nmux --help 2> /dev/null") == 32512: #check for nmux
        print "[openwebrx-main] You need to install an up-to-date version of \"csdr\" that contains the \"nmux\" tool to run OpenWebRX! Please upgrade \"csdr\"!\n"
        return
    if cfg.start_rtl_thread:
        nmux_bufcnt = nmux_bufsize = 0
        while nmux_bufsize < cfg.samp_rate/4: nmux_bufsize += 4096
        while nmux_bufsize * nmux_bufcnt < cfg.nmux_memory * 1e6: nmux_bufcnt += 1
        if nmux_bufcnt == 0 or nmux_bufsize == 0: 
            print "[openwebrx-main] Error: nmux_bufsize or nmux_bufcnt is zero. These depend on nmux_memory and samp_rate options in config_webrx.py"
            return
        print "[openwebrx-main] nmux_bufsize = %d, nmux_bufcnt = %d" % (nmux_bufsize, nmux_bufcnt)
        cfg.start_rtl_command += "| nmux --bufsize %d --bufcnt %d --port %d --address 127.0.0.1" % (nmux_bufsize, nmux_bufcnt, cfg.iq_server_port)
        rtl_thread=threading.Thread(target = lambda:subprocess.Popen(cfg.start_rtl_command, shell=True),  args=())
        rtl_thread.start()
        print "[openwebrx-main] Started rtl_thread: "+cfg.start_rtl_command
    print "[openwebrx-main] Waiting for I/Q server to start..."
    while True:
        testsock=socket.socket()
        try: testsock.connect(("127.0.0.1", cfg.iq_server_port))
        except:
            time.sleep(0.1)
            continue
        testsock.close()
        break
    print "[openwebrx-main] I/Q server started."

    #Initialize clients
    clients=[]
    clients_mutex=threading.Lock()
    lock_try_time=0

    #Start watchdog thread
    print "[openwebrx-main] Starting watchdog threads."
    mutex_test_thread=threading.Thread(target = mutex_test_thread_function, args = ())
    mutex_test_thread.start()
    mutex_watchdog_thread=threading.Thread(target = mutex_watchdog_thread_function, args = ())
    mutex_watchdog_thread.start()


    #Start spectrum thread
    print "[openwebrx-main] Starting spectrum thread."
    spectrum_thread=threading.Thread(target = spectrum_thread_function, args = ())
    spectrum_thread.start()
    #spectrum_watchdog_thread=threading.Thread(target = spectrum_watchdog_thread_function, args = ())
    #spectrum_watchdog_thread.start()

    get_cpu_usage()
    bcastmsg_thread=threading.Thread(target = bcastmsg_thread_function, args = ())
    bcastmsg_thread.start()

    #threading.Thread(target = measure_thread_function, args = ()).start()

    #Start sdr.hu update thread
    if sdrhu and cfg.sdrhu_key and cfg.sdrhu_public_listing:
        print "[openwebrx-main] Starting sdr.hu update thread..."
        avatar_ctime=str(os.path.getctime("htdocs/gfx/openwebrx-avatar.png"))
        sdrhu_thread=threading.Thread(target = sdrhu.run, args = ())
        sdrhu_thread.start()

    #Start HTTP thread
    httpd = MultiThreadHTTPServer(('', cfg.web_port), WebRXHandler)
    print('[openwebrx-main] Starting HTTP server.')
    access_log("Starting OpenWebRX...")
    httpd.serve_forever()
Ejemplo n.º 41
0
def main():
	global clients, clients_mutex, pypy, lock_try_time, avatar_ctime, cfg, logs
	global serverfail, rtl_thread
	print
	print "OpenWebRX - Open Source SDR Web App for Everyone!  | for license see LICENSE file in the package"
	print "_________________________________________________________________________________________________"
	print
	print "Author contact info:    Andras Retzler, HA7ILM <*****@*****.**>"
	print

	no_arguments=len(sys.argv)==1
	if no_arguments: print "[openwebrx-main] Configuration script not specified. I will use: \"config_webrx.py\""
	cfg=__import__("config_webrx" if no_arguments else sys.argv[1])
	for option in ("access_log","csdr_dynamic_bufsize","csdr_print_bufsizes","csdr_through"):
		if not option in dir(cfg): setattr(cfg, option, False) #initialize optional config parameters

	#Open log files
	logs = type("logs_class", (object,), {"access_log":open(cfg.access_log if cfg.access_log else "/dev/null","a"), "error_log":""})()

	#Set signal handler
	signal.signal(signal.SIGINT, handle_signal) #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
	signal.signal(signal.SIGTERM, handle_signal) #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
	signal.signal(signal.SIGQUIT, handle_signal) #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python

	#Load plugins
	import_all_plugins("plugins/dsp/")

	#Pypy
	if pypy: print "pypy detected (and now something completely different: a c code is expected to run at a speed of 3*10^8 m/s?)"

	#Change process name to "openwebrx" (to be seen in ps)
	try:
		for libcpath in ["/lib/i386-linux-gnu/libc.so.6","/lib/libc.so.6"]:
			if os.path.exists(libcpath):
				libc = dl.open(libcpath)
				libc.call("prctl", 15, "openwebrx", 0, 0, 0)
				break
	except:
		pass

	#Start rtl thread
	if os.system("ncat --version > /dev/null") == 32512: #check for ncat
		print "[openwebrx-main] Error: ncat not detected, please install it! The ncat tool is a netcat alternative, used for distributing the I/Q data stream. It is usually available in the nmap package (sudo apt-get install nmap). For more explanation, look into the README.md"
		return
	if cfg.start_rtl_thread:
		cfg.start_rtl_command += "| ncat -4l %d -k --send-only --allow 127.0.0.1" % cfg.iq_server_port
		rtl_thread=threading.Thread(target = lambda:subprocess.Popen(cfg.start_rtl_command, shell=True),  args=())
		rtl_thread.start()
		print "[openwebrx-main] Started rtl_thread: "+cfg.start_rtl_command
	print "[openwebrx-main] Waiting for I/Q server to start..."
	while True:
		testsock=socket.socket()
		try: testsock.connect(("127.0.0.1", cfg.iq_server_port))
		except:
			time.sleep(0.1)
			continue
		testsock.close()
		break
	print "[openwebrx-main] I/Q server started."

	#Initialize clients
	clients=[]
	clients_mutex=threading.Lock()
	lock_try_time=0

	#Start watchdog thread
	print "[openwebrx-main] Starting watchdog threads."
	mutex_test_thread=threading.Thread(target = mutex_test_thread_function, args = ())
	mutex_test_thread.start()
	mutex_watchdog_thread=threading.Thread(target = mutex_watchdog_thread_function, args = ())
	mutex_watchdog_thread.start()

	#Shutdown trehad:
	shutdown_thread = threading.Thread(target = auto_shutdown_thread_function, args = ())
	shutdown_thread.start()

	#Start spectrum thread
	print "[openwebrx-main] Starting spectrum thread."
	spectrum_thread=threading.Thread(target = spectrum_thread_function, args = ())
	spectrum_thread.start()
	#spectrum_watchdog_thread=threading.Thread(target = spectrum_watchdog_thread_function, args = ())
	#spectrum_watchdog_thread.start()

	get_cpu_usage()
	bcastmsg_thread=threading.Thread(target = bcastmsg_thread_function, args = ())
	bcastmsg_thread.start()

	#threading.Thread(target = measure_thread_function, args = ()).start()

	#Start sdr.hu update thread
	if sdrhu and cfg.sdrhu_key and cfg.sdrhu_public_listing:
		print "[openwebrx-main] Starting sdr.hu update thread..."
		avatar_ctime=str(os.path.getctime("htdocs/gfx/openwebrx-avatar.png"))
		sdrhu_thread=threading.Thread(target = sdrhu.run, args = ())
		sdrhu_thread.start()

	#Start HTTP thread
	httpd = MultiThreadHTTPServer(('', cfg.web_port), WebRXHandler)
	print('[openwebrx-main] Starting HTTP server.')
	access_log("Starting OpenWebRX...")
	httpd.serve_forever()
            if err < best:
                best = err
                bestvals = (err, column, thresh, a, b)

        err, column, thresh, a, b = bestvals
        array([err, column, thresh], float32).tofile(stdout)
        a.astype(float32).tofile(stdout)
        b.astype(float32).tofile(stdout)
        stdout.flush()



if __name__ == '__main__':
    try:
        import dl
        h = dl.open('change_malloc_zone.dylib')
        h.call('setup')
    except:
        pass
    if len(argv) != 1:
        import cProfile
        cProfile.runctx("doit()", globals(), locals(), "worker.cprof")
    else:
        try: # Use binary I/O on Windows
            import msvcrt, os
            try:
                msvcrt.setmode(stdin.fileno(), os.O_BINARY)
            except:
                stderr.write("Couldn't deal with stdin\n")
                pass
            try:
Ejemplo n.º 43
0
#!/usr/bin/python
import dl
import sys

result="chadFunk"
print >> sys.stdout, result
a=dl.open("libjunk.so")
result=a.call('fun1','1.12','1.22')
a.close()
print >> sys.stdout, result
Ejemplo n.º 44
0
import dl, time
a = dl.open('/lib64/libc.so.6')
a.call('time'), time.time()
# i18n
gettext.install("mintinstall", "/usr/share/linuxmint/locale")

# i18n for menu item
menuName = _("Software Manager")
menuComment = _("Install new applications")

architecture = commands.getoutput("uname -a")
if (architecture.find("x86_64") >= 0):
	import ctypes
	libc = ctypes.CDLL('libc.so.6')
	libc.prctl(15, 'mintInstall', 0, 0, 0)	
else:
	import dl
	libc = dl.open('/lib/libc.so.6')
	libc.call('prctl', 15, 'mintInstall', 0, 0, 0)

global cache
import apt
cache = apt.Cache()
global num_apps
num_apps = 0

def close_application(window, event=None):	
	gtk.main_quit()
	sys.exit(0)

def close_window(widget, window):	
	window.hide_all()
Ejemplo n.º 46
0
    print "*********** Keybind Driver Load Failure **************"
    print "Error Report : ", str(cause)
    pass

# Rename the process
architecture = commands.getoutput("uname -a")
if architecture.find("x86_64") >= 0:
    import ctypes

    libc = ctypes.CDLL("libc.so.6")
    libc.prctl(15, "mintmenu", 0, 0, 0)
else:
    import dl

    if os.path.exists("/lib/libc.so.6"):
        libc = dl.open("/lib/libc.so.6")
        libc.call("prctl", 15, "mintmenu", 0, 0, 0)
    elif os.path.exists("/lib/i386-linux-gnu/libc.so.6"):
        libc = dl.open("/lib/i386-linux-gnu/libc.so.6")
        libc.call("prctl", 15, "mintmenu", 0, 0, 0)

# i18n
gettext.install("mintmenu", "/usr/share/linuxmint/locale")

NAME = _("Menu")
PATH = os.path.abspath(os.path.dirname(sys.argv[0]))

ICON = "/usr/lib/linuxmint/mintMenu/visualisation-logo.png"

sys.path.append(os.path.join(PATH, "plugins"))
Ejemplo n.º 47
0
def main():
    global clients, clients_mutex, pypy, lock_try_time, avatar_ctime, cfg, logs
    global serverfail, rtl_thread
    print
    print "OpenWebRX - Open Source SDR Web App for Everyone!  | for license see LICENSE file in the package"
    print "_________________________________________________________________________________________________"
    print
    print "Author contact info:    Andras Retzler, HA7ILM <*****@*****.**>"
    print

    no_arguments = len(sys.argv) == 1
    if no_arguments:
        print "[openwebrx-main] Configuration script not specified. I will use: \"config_webrx.py\""
    cfg = __import__("config_webrx" if no_arguments else sys.argv[1])
    for option in ("access_log", "csdr_dynamic_bufsize", "csdr_print_bufsizes",
                   "csdr_through"):
        if not option in dir(cfg):
            setattr(cfg, option, False)  #initialize optional config parameters

    #Open log files
    logs = type(
        "logs_class", (object, ), {
            "access_log":
            open(cfg.access_log if cfg.access_log else "/dev/null", "a"),
            "error_log":
            ""
        })()

    #Set signal handler
    signal.signal(
        signal.SIGINT, handle_signal
    )  #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
    signal.signal(signal.SIGUSR1, handle_signal)
    signal.signal(signal.SIGUSR2, handle_signal)

    #Pypy
    if pypy:
        print "pypy detected (and now something completely different: c code is expected to run at a speed of 3*10^8 m/s?)"

    #Change process name to "openwebrx" (to be seen in ps)
    try:
        for libcpath in ["/lib/i386-linux-gnu/libc.so.6", "/lib/libc.so.6"]:
            if os.path.exists(libcpath):
                libc = dl.open(libcpath)
                libc.call("prctl", 15, "openwebrx", 0, 0, 0)
                break
    except:
        pass

    #Start rtl thread
    if os.system("csdr 2> /dev/null") == 32512:  #check for csdr
        print "[openwebrx-main] You need to install \"csdr\" to run OpenWebRX!\n"
        return
    if os.system("nmux --help 2> /dev/null") == 32512:  #check for nmux
        print "[openwebrx-main] You need to install an up-to-date version of \"csdr\" that contains the \"nmux\" tool to run OpenWebRX! Please upgrade \"csdr\"!\n"
        return
    if cfg.start_rtl_thread:
        nmux_bufcnt = nmux_bufsize = 0
        while nmux_bufsize < cfg.samp_rate / 4:
            nmux_bufsize += 4096
        while nmux_bufsize * nmux_bufcnt < cfg.nmux_memory * 1e6:
            nmux_bufcnt += 1
        if nmux_bufcnt == 0 or nmux_bufsize == 0:
            print "[openwebrx-main] Error: nmux_bufsize or nmux_bufcnt is zero. These depend on nmux_memory and samp_rate options in config_webrx.py"
            return
        print "[openwebrx-main] nmux_bufsize = %d, nmux_bufcnt = %d" % (
            nmux_bufsize, nmux_bufcnt)
        cfg.start_rtl_command += " %d %d %d 127.0.0.1" % (
            nmux_bufsize, nmux_bufcnt, cfg.iq_server_port)
        rtl_thread = threading.Thread(
            target=lambda: subprocess.Popen(cfg.start_rtl_command, shell=True),
            args=())
        rtl_thread.start()
        print "[openwebrx-main] Started rtl_thread: " + cfg.start_rtl_command
    print "[openwebrx-main] Waiting for I/Q server to start..."
    while True:
        testsock = socket.socket()
        try:
            testsock.connect(("127.0.0.1", cfg.iq_server_port))
        except:
            time.sleep(0.1)
            continue
        testsock.close()
        break
    print "[openwebrx-main] I/Q server started."

    #Initialize clients
    clients = []
    clients_mutex = threading.Lock()
    lock_try_time = 0

    #Start watchdog thread
    print "[openwebrx-main] Starting watchdog threads."
    mutex_test_thread = threading.Thread(target=mutex_test_thread_function,
                                         args=())
    mutex_test_thread.start()
    mutex_watchdog_thread = threading.Thread(
        target=mutex_watchdog_thread_function, args=())
    mutex_watchdog_thread.start()

    #Start spectrum thread
    print "[openwebrx-main] Starting spectrum thread."
    spectrum_thread = threading.Thread(target=spectrum_thread_function,
                                       args=())
    spectrum_thread.start()
    #spectrum_watchdog_thread=threading.Thread(target = spectrum_watchdog_thread_function, args = ())
    #spectrum_watchdog_thread.start()

    get_cpu_usage()
    bcastmsg_thread = threading.Thread(target=bcastmsg_thread_function,
                                       args=())
    bcastmsg_thread.start()

    #threading.Thread(target = measure_thread_function, args = ()).start()

    #Start sdr.hu update thread
    if sdrhu and cfg.sdrhu_key and cfg.sdrhu_public_listing:
        print "[openwebrx-main] Starting sdr.hu update thread..."
        avatar_ctime = str(os.path.getctime("htdocs/gfx/openwebrx-avatar.png"))
        sdrhu_thread = threading.Thread(target=sdrhu.run, args=())
        sdrhu_thread.start()

    #Start HTTP thread
    httpd = MultiThreadHTTPServer(('', cfg.web_port), WebRXHandler)
    print('[openwebrx-main] Starting HTTP server.')
    access_log("Starting OpenWebRX...")
    httpd.serve_forever()
Ejemplo n.º 48
0
def py_generate_random():
    """Generate a UUID using a high-quality source of randomness.
    """
    return _uuid_unparse(_uuid_generate_random())


################################################################################
### Here is an interface to libuuid, just in case it happens to be available ###
################################################################################

_libuuid = None

try:
    import dl
    _libuuid = dl.open("libuuid.so")
except:
    pass

# I am being a bad boy: libuuid functions, when invoked, are passed strings
# which they modify.  This is supposed to be a no-no as documented in the dl
# module.  However, I create these strings anew each time using struct.pack,
# they are never uniquified nor hashed, and they are thrown away as soon as
# possible.  I think this is actually safe.  If I am wrong, please let me know.


def libuuid_generate():
    """Generate a UUID with libuuid using the best available method.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s", "")
Ejemplo n.º 49
0
import dl
from test.test_support import verbose, TestSkipped

sharedlibs = [
    ('/usr/lib/libc.so', 'getpid'),
    ('/lib/libc.so.6', 'getpid'),
    ('/usr/bin/cygwin1.dll', 'getpid'),
    ('/usr/lib/libc.dylib', 'getpid'),
]

for s, func in sharedlibs:
    try:
        if verbose:
            print 'trying to open:', s,
        l = dl.open(s)
    except dl.error, err:
        if verbose:
            print 'failed', repr(str(err))
        pass
    else:
        if verbose:
            print 'succeeded...',
        l.call(func)
        l.close()
        if verbose:
            print 'worked!'
        break
else:
    raise TestSkipped, 'Could not open any shared libraries'
Ejemplo n.º 50
0
    return _uuid_unparse(_uuid_generate_time())

def py_generate_random():
    """Generate a UUID using a high-quality source of randomness.
    """
    return _uuid_unparse(_uuid_generate_random())

################################################################################
### Here is an interface to libuuid, just in case it happens to be available ###
################################################################################

_libuuid = None

try:
    import dl
    _libuuid = dl.open("libuuid.so")
except:
    pass

# I am being a bad boy: libuuid functions, when invoked, are passed strings
# which they modify.  This is supposed to be a no-no as documented in the dl
# module.  However, I create these strings anew each time using struct.pack,
# they are never uniquified nor hashed, and they are thrown away as soon as
# possible.  I think this is actually safe.  If I am wrong, please let me know.

def libuuid_generate():
    """Generate a UUID with libuuid using the best available method.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
Ejemplo n.º 51
0
        return '[' + ', '.join([repr(v, seen) for v in value]) + ']'
    elif istype(value, "dict"):
        return '{' + ', '.join([repr(k, seen) + ': ' + repr(value[k], seen) for k in value]) + '}'
    return old_str(value)

def globals():
    return BUILTINS['__globals__']

BUILTINS['__globals__'] = {}
BUILTINS['globals'] = globals
BUILTINS['str'] = my_str
BUILTINS['repr'] = repr

fgets = dl.load('', 'fgets', 'S', 'SI*')
puts = dl.load('', 'printf', 'V', 'S')
handle = dl.open('')
stdin = dl.sym(handle, '_IO_2_1_stdin_')

data = " " * 1024

while True:
    puts('> ')
    source = fgets(data, len(data), stdin)
    if source is None:
        break
    if source.strip() == '':
        continue
    try:
        result = eval(source, globals())
        print(str(result))
    except:
Ejemplo n.º 52
0
    try: import ctypes
    except ImportError: pass
    else:
        _libc = ctypes.cdll.libc
        def if_nametoindex(interfaceName):
            # if you have a better way to get the interface index, I'd love to hear
            # it...  You are supposed to be able to leave the interface number as 0,
            # but I get an exception when I try this.  (MacOS 10.4)  It may be because
            # it is a multihomed device...
            return _libc.if_nametoindex(interfaceName)

if if_nametoindex is None:
    try: import dl
    except ImportError: pass
    else:
        _libc = dl.open('libc.so')
        def if_nametoindex(interfaceName):
            # if you have a better way to get the interface index, I'd love to hear
            # it...  You are supposed to be able to leave the interface number as 0,
            # but I get an exception when I try this.  (MacOS 10.4)  It may be because
            # it is a multihomed device...
            return _libc.call('if_nametoindex', interfaceName)

if if_nametoindex is None:
    raise RuntimeError("No implementation allowing access to if_nametoindex available")

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Definitions 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

maddr = ('ff12::4242', 4242)
Ejemplo n.º 53
0
def main():
    global clients, clients_mutex, pypy, lock_try_time, avatar_ctime, cfg, logs
    global serverfail, rtl_thread
    print
    print "OpenWebRX - Open Source SDR Web App for Everyone!  | for license see LICENSE file in the package"
    print "_________________________________________________________________________________________________"
    print
    print "Author contact info:    Andras Retzler, HA7ILM <*****@*****.**>"
    print

    no_arguments = len(sys.argv) == 1
    if no_arguments:
        print "[openwebrx-main] Configuration script not specified. I will use: \"config_webrx.py\""
    cfg = __import__("config_webrx" if no_arguments else sys.argv[1])
    for option in ("access_log", "csdr_dynamic_bufsize", "csdr_print_bufsizes",
                   "csdr_through"):
        if not option in dir(cfg):
            setattr(cfg, option, False)  #initialize optional config parameters

    #Open log files
    logs = type(
        "logs_class", (object, ), {
            "access_log":
            open(cfg.access_log if cfg.access_log else "/dev/null", "a"),
            "error_log":
            ""
        })()

    #Set signal handler
    signal.signal(
        signal.SIGINT, handle_signal
    )  #http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
    signal.signal(signal.SIGUSR1, handle_signal)

    #Load plugins
    import_all_plugins("plugins/dsp/")

    #Pypy
    if pypy:
        print "pypy detected (and now something completely different: a c code is expected to run at a speed of 3*10^8 m/s?)"

    #Change process name to "openwebrx" (to be seen in ps)
    try:
        for libcpath in ["/lib/i386-linux-gnu/libc.so.6", "/lib/libc.so.6"]:
            if os.path.exists(libcpath):
                libc = dl.open(libcpath)
                libc.call("prctl", 15, "openwebrx", 0, 0, 0)
                break
    except:
        pass

    #Start rtl thread
    if os.system("ncat --version > /dev/null") == 32512:  #check for ncat
        print "[openwebrx-main] Error: ncat not detected, please install it! The ncat tool is a netcat alternative, used for distributing the I/Q data stream. It is usually available in the nmap package (sudo apt-get install nmap). For more explanation, look into the README.md"
        return
    if cfg.start_rtl_thread:
        cfg.start_rtl_command += "| ncat -4l %d -k --send-only --allow 127.0.0.1" % cfg.iq_server_port
        rtl_thread = threading.Thread(
            target=lambda: subprocess.Popen(cfg.start_rtl_command, shell=True),
            args=())
        rtl_thread.start()
        print "[openwebrx-main] Started rtl_thread: " + cfg.start_rtl_command
    print "[openwebrx-main] Waiting for I/Q server to start..."
    while True:
        testsock = socket.socket()
        try:
            testsock.connect(("127.0.0.1", cfg.iq_server_port))
        except:
            time.sleep(0.1)
            continue
        testsock.close()
        break
    print "[openwebrx-main] I/Q server started."

    #Initialize clients
    clients = []
    clients_mutex = threading.Lock()
    lock_try_time = 0

    #Start watchdog thread
    print "[openwebrx-main] Starting watchdog threads."
    mutex_test_thread = threading.Thread(target=mutex_test_thread_function,
                                         args=())
    mutex_test_thread.start()
    mutex_watchdog_thread = threading.Thread(
        target=mutex_watchdog_thread_function, args=())
    mutex_watchdog_thread.start()

    #Start spectrum thread
    print "[openwebrx-main] Starting spectrum thread."
    spectrum_thread = threading.Thread(target=spectrum_thread_function,
                                       args=())
    spectrum_thread.start()
    #spectrum_watchdog_thread=threading.Thread(target = spectrum_watchdog_thread_function, args = ())
    #spectrum_watchdog_thread.start()

    get_cpu_usage()
    bcastmsg_thread = threading.Thread(target=bcastmsg_thread_function,
                                       args=())
    bcastmsg_thread.start()

    #threading.Thread(target = measure_thread_function, args = ()).start()

    #Start sdr.hu update thread
    if sdrhu and cfg.sdrhu_key and cfg.sdrhu_public_listing:
        print "[openwebrx-main] Starting sdr.hu update thread..."
        avatar_ctime = str(os.path.getctime("htdocs/gfx/openwebrx-avatar.png"))
        sdrhu_thread = threading.Thread(target=sdrhu.run, args=())
        sdrhu_thread.start()

    #Start HTTP thread
    httpd = MultiThreadHTTPServer(('', cfg.web_port), WebRXHandler)
    print('[openwebrx-main] Starting HTTP server.')
    access_log("Starting OpenWebRX...")
    httpd.serve_forever()
Ejemplo n.º 54
0
    print e
    sys.exit( 1 )

GObject.threads_init()

gdk = CDLL("libgdk-x11-2.0.so.0")

# Rename the process
architecture = platform.uname()[4]
if architecture in 'x86_64':
    libc = CDLL('libc.so.6')
    libc.prctl(15, 'mate-menu', 0, 0, 0)
else:
    import dl
    if os.path.exists('/lib/libc.so.6'):
        libc = dl.open('/lib/libc.so.6')
        libc.call('prctl', 15, 'mate-menu', 0, 0, 0)
    elif os.path.exists('/lib/i386-linux-gnu/libc.so.6'):
        libc = dl.open('/lib/i386-linux-gnu/libc.so.6')
        libc.call('prctl', 15, 'mate-menu', 0, 0, 0)

# i18n
gettext.install("mate-menu", "/usr/share/locale")

NAME = _("Menu")

xdg.Config.setWindowManager('MATE')

from mate_menu.execute import *

class MainWindow( object ):
Ejemplo n.º 55
0
def _load_libalfcrypto():
    # Most of the magic here needs Python 2.6 or Python 2.7. It may work with
    # Python 2.5 as well if the ctypes package is installed, but that's not
    # tested.
    #
    # Tested on:
    #
    # * Linux i386
    # * Linux x86_64
    # * Mac OS X i386
    # * Mac OS X x86_64
    # * Windows XP i386
    # * Windows XP x86_64
    # * Windows 7 i386
    # * Windows 7 x86_64

    import os
    import sys

    ctypes = dl = None
    try:
        import ctypes
    except ImportError:
        try:
            import dl
            import struct
        except ImportError:
            raise ImportError('Neither ctypes nor dl found.')

    platform = sys.platform

    if ctypes:
        pointer_size = ctypes.sizeof(ctypes.c_voidp)
    else:
        pointer_size = struct.calcsize('P')

    try:
        arch = os.uname()[4]
    except AttributeError:  # platform == 'win32' doesn't have it.
        arch = 'unknown'

    # TODO: Maybe it runs on FreeBSD too. Try it.
    if (arch not in ('i386', 'i486', 'i586', 'i686', 'x86', 'unknown',
                     'x86_64', 'amd64')
            or platform not in ('linux', 'linux2', 'win', 'windows', 'win32',
                                'win64', 'darwin', 'darwin32', 'darwin64')):
        raise ImportError('Unsupported arch=%r platform=%r' % (arch, platform))
    if dl and pointer_size != 4:
        raise ImportError('Cannot use dl with pointer_size=%r, expecting 4' %
                          pointer_size)

    if pointer_size == 4:
        machine = MACHINE32
    elif platform.startswith('win'):
        # The Windows 64-bit calling conventions are different.
        # http://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions
        machine = MACHINE64WIN
    else:
        machine = MACHINE64

    global m  # Don't free it until the alfcrypto module is freed.
    s = machine['code']
    if platform.startswith('win'):
        # MEM_COMMIT = 0x1000
        # MEM_RESERVE = 0x2000
        # MEM_RELEASE = 0x8000
        # PAGE_EXECUTE_READWRITE = 0x40
        class Releaser(object):
            __slots__ = ('p', )

            def __init__(self, p):
                self.p = int(p)

            def __del__(self):
                ctypes.windll.kernel32.VirtualFree(self.p, 0, 0x8000)

        # Allocate executable memory.
        #
        # This works as expected on Windows x86_64 as well, because each
        # argument is passed in a 64-bit register.
        vp = ctypes.windll.kernel32.VirtualAlloc(0, len(s), 0x3000, 0x40)
        m = Releaser(vp)
        ctypes.memmove(vp, s, len(s))
    elif dl:
        # dl is usually Linux i386. Not on Mac OS X 10.7 arch -32.
        # Not on Windows. Not on x86_64.
        import mmap
        # TODO: Report better exceptions here.
        d = dl.open(None)
        assert d.sym('mmap')
        assert d.sym('munmap')
        assert d.sym('memcpy')
        assert d.sym('qsort')

        # TODO: Call munmap later.
        class MmapReleaser(object):
            __slots__ = ('p', 'size')

            def __init__(self, p, size):
                self.p = int(p)
                self.size = int(size)

            def __del__(self):
                d.call('munmap', self.p, self.size)

        vp = d.call('mmap', 0, len(s),
                    mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
                    mmap.MAP_PRIVATE | mmap.MAP_ANON, -1, 0)
        assert vp != 0
        assert vp != -1
        m = MmapReleaser(vp, len(s))
        d.call('memcpy', vp, s, len(s))
        vp_cmp = vp + machine['cmp']

        def make_function(d, fp):
            if isinstance(fp, long):
                fp = int(fp)
            if not isinstance(fp, (str, int)):
                raise TypeError
            if isinstance(fp, int) and not fp:
                raise ValueError

            def call(*args):
                if isinstance(fp, str):
                    return d.call(fp, *args)
                assert len(args) <= 10
                ary = [0] * 24
                ary[0] = fp
                for i, arg in enumerate(args):
                    if isinstance(arg, str):
                        arg = d.call('memcpy', arg, 0, 0)
                    ary[i + 1] = arg
                arys = struct.pack('24i',
                                   *ary)  # This may fail with out-of-bounds.
                # Since we can't call an integer address (d.call(fp, ...)),
                # we call qsort and make it call us.
                d.call('qsort', arys, 2, 48, vp_cmp)
                return struct.unpack('i', arys[44:48])[0]

            return call
    elif not getattr(ctypes.c_char_p, 'from_buffer', None):
        # Method .from_buffer is missing in Python 2.5. Present in Python 2.6.
        import mmap

        class CtypesMmapReleaser(object):
            __slots__ = ('p', 'size')

            def __init__(self, p, size):
                self.p = int(p)
                self.size = int(size)

            def __del__(self):
                ctypes.pythonapi.munmap(self.p, self.size)

        vp = ctypes.pythonapi.mmap(
            0, len(s), mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
            mmap.MAP_PRIVATE | mmap.MAP_ANON, -1, 0)
        m = CtypesMmapReleaser(vp, len(s))
        ctypes.memmove(vp, s, len(s))
    else:
        import mmap
        # Allocate executable memory.
        m = mmap.mmap(-1, len(s), mmap.MAP_PRIVATE | mmap.MAP_ANON,
                      mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
        m.write(s)
        vp = ctypes.addressof(ctypes.c_char_p.from_buffer(m))

    if dl:
        PC1 = make_function(d, vp + machine['PC1'])
        topazCryptoInit = make_function(d, vp + machine['topazCryptoInit'])
        topazCryptoDecrypt = make_function(d,
                                           vp + machine['topazCryptoDecrypt'])
    else:
        c_char_pp = ctypes.POINTER(ctypes.c_char_p)

        def F(restype, name, argtypes):
            return ctypes.CFUNCTYPE(restype, *argtypes)(vp + machine[name])

        # Pukall 1 Cipher
        # unsigned char *PC1(const unsigned char *key, unsigned int klen, const unsigned char *src,
        #                unsigned char *dest, unsigned int len, int decryption);

        PC1 = F(ctypes.c_char_p, 'PC1', [
            ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p, ctypes.c_char_p,
            ctypes.c_ulong, ctypes.c_ulong
        ])

        # Topaz Encryption
        # typedef struct _TpzCtx {
        #    unsigned int v[2];
        # } TpzCtx;
        #
        # void topazCryptoInit(TpzCtx *ctx, const unsigned char *key, int klen);
        # void topazCryptoDecrypt(const TpzCtx *ctx, const unsigned char *in, unsigned char *out, int len);

        class TPZ_CTX(ctypes.Structure):
            _fields_ = [('v', ctypes.c_int * 2)]

        TPZ_CTX_p = ctypes.POINTER(TPZ_CTX)
        topazCryptoInit = F(None, 'topazCryptoInit',
                            [TPZ_CTX_p, ctypes.c_char_p, ctypes.c_ulong])
        topazCryptoDecrypt = F(
            None, 'topazCryptoDecrypt',
            [TPZ_CTX_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong])

    class Pukall_Cipher(object):
        def __init__(self):
            self.key = None

        def PC1(self, key, src, decryption=True):
            self.key = key
            de = 0
            if decryption:
                de = 1
            if dl:
                out = '\0' * max(len(src), 8)
                PC1(key, len(key), src, out, len(src), de)
                out = out[:len(src)]  # Fast, because no-op if out is long.
                return out
            else:
                out = ctypes.create_string_buffer(len(src))
                rv = PC1(key, len(key), src, out, len(src), de)
                return out.raw

    class Topaz_Cipher(object):
        def __init__(self):
            self._ctx = None

        def ctx_init(self, key):
            if dl:
                # Call `max' to prevent the Python compiler from inlining.
                tpz_ctx = self._ctx = '\0' * max(8, 8)
            else:
                tpz_ctx = self._ctx = TPZ_CTX()
            topazCryptoInit(tpz_ctx, key, len(key))
            return tpz_ctx

        def decrypt(self, data, ctx=None):
            if ctx == None:
                ctx = self._ctx
            if dl:
                out = '\0' * max(len(data), 8)
                topazCryptoDecrypt(ctx, data, out, len(data))
                out = out[:len(data)]  # Fast, because no-op if out is long.
                return out
            else:
                out = ctypes.create_string_buffer(len(data))
                topazCryptoDecrypt(ctx, data, out, len(data))
                return out.raw

    print "Using inlined AlfCrypto machine code."
    return (Pukall_Cipher, Topaz_Cipher)
Ejemplo n.º 56
0
#! /usr/bin/env python
"""Test dlmodule.c
   Roger E. Masse  revised strategy by Barry Warsaw
"""
import dl
from test_support import verbose, TestSkipped
sharedlibs = [
    ('/usr/lib/libc.so', 'getpid'),
    ('/lib/libc.so.6', 'getpid'),
    ('/usr/bin/cygwin1.dll', 'getpid'),
]
for s, func in sharedlibs:
    try:
        if verbose:
            print 'trying to open:', s,
        l = dl.open(s)
    except dl.error, err:
        if verbose:
            print 'failed', repr(str(err))
        pass
    else:
        if verbose:
            print 'succeeded...',
        l.call(func)
        l.close()
        if verbose:
            print 'worked!'
        break
else:
    raise TestSkipped, 'Could not open any shared libraries'