Ejemplo n.º 1
0
  def run(self):
    port = None
    if self.use_unix_socket:
        socket_family = socket.AF_UNIX
        
        if self.lirc_file is not None:
            port = self.lirc_file
    else:
        socket_family = socket.AF_INET
        port = (socket.gethostname(), app.lirc_port)

    s = socket.socket(socket_family, socket.SOCK_STREAM)
    
    log("[LircServer] Using port " + str(port))

    if self.use_unix_socket:
        if os.access(port, os.F_OK):
            try:
              os.remove(port)
            except OSError:
              self.mainapp.die("[LircServer] Can't delete file: " + app.lirc_file)
              return

    logger.info("[LircServer] LIRC Server Listening on " + str(port))

    try:
        s.bind(port)
        if self.use_unix_socket:
            os.chmod(port, 0666)
    except Exception, e:
        self.mainapp.die("[LircServer] Can't bind socket: " + str(e[1]))
        return
Ejemplo n.º 2
0
 def addCommand(self, cmd):
   mutex.acquire()
   
   log("[CommandQueue] Adding command: "+cmd)
   self.commands.append(cmd)
   
   mutex.release()
Ejemplo n.º 3
0
 def split(self, addr, endAddr=-1):
     """
     Splits the basic block into two. This function shall only be used in the case of the latter discovery of a jump into the midst of an already defined basic block.
     Creates two new basic blocks that are saved to self.hiBb and self.loBb. 
     @param addr: The address where to split the block. The address of the first instruction of the new basic block. 
     """
     if not (addr >= self.startAddr and addr <= self.endAddr):
         raise AddressOutOfRange("The supplied address lies not within the basicblock")
     
     if self.isSplit:
         log(DEBUG_LEVEL_TRACE_EVENTS, "[!] Going to split a basic block that was already split (address: %x)." % addr)
         # dispatch to lower level bbs
         if addr < self.loBb.startAddr:
             return self.hiBb.split(addr, endAddr)
         else:
             return self.loBb.split(addr, endAddr)
     
     if (endAddr == -1):
         newEndAddr = addr -1 # TODO: rather hackish, unfortunately we do not know the size of the previous instruction
     else:
         newEndAddr = endAddr    
     
     self.loBb = BasicBlock(addr, self.endAddr, nExits=self.nExits)
     self.loBb.knownExits = self.knownExits
     self.hiBb = BasicBlock(self.startAddr, newEndAddr, nExits=1)
     self.hiBb.addExit(self.loBb)
     
     # now distribute flags
     hiType = (self.type & self.TYPE.ADJACENT_TO_VIRTUAL) | (self.type & self.TYPE.START_BLOCK) | self.TYPE.SINGLE_EXIT 
     self.hiBb.addType(hiType)
     loType = (self.type & self.TYPE.END_BLOCK) | (self.type & self.TYPE.SINGLE_EXIT)
     self.loBb.addType(loType)
     
     self.isSplit = True
     return (self.hiBb, self.loBb)
Ejemplo n.º 4
0
  def handleClient(self, socket):
    mutex.acquire()
    
    log("[LircServer] Adding client")
    
    self.clients.append(LircClient(socket))

    mutex.release()
Ejemplo n.º 5
0
 def _setupCheckpoints(self, checkpoints, maxHits):
     t0 = time.time()
     self.checkpoints = {}
     for addr in checkpoints:
         self.checkpoints[addr] = Checkpoint(addr, maxHits)
     
     self.replug()
     log(DEBUG_LEVEL.SOME, "[i] Setting %d trace breakpoints took %f seconds." % (len(checkpoints),time.time() - t0))
Ejemplo n.º 6
0
 def _virtCondBranchHandler(self, pygdb, event):
     
     log(DEBUG_LEVEL_TRACE_EVENTS, "Vbb hit at %x" % event.addr)
     vbb = self.virtBasicBlocks[event.addr]
     self._processVirtCondBranch(pygdb, vbb, event.tid)
     
     # add adjacent bb
     if len(vbb.knownExits) != 1:
         raise InvalidTracerState("A virtual basic-block was encountered that has not exactly one exit. This should never be the case.")
     
     nextBb = vbb.knownExits.values()[0].bb
     self._processBb(pygdb, nextBb, event.tid)
     
     return PyGdb.CONTINUE.RUN_KEEP_BREAKPOINT
Ejemplo n.º 7
0
    def _defaultBpHandler(self, pygdb, event):
        pid = event.pid
        if event.tid not in self.traces:
            self.traces[event.tid] = Trace(event.tid)
        
        addr = self.undoRebasing and pygdb.environment.unrebaseCodeAddr(pygdb, event.addr, event.pid) or event.addr
        self.traces[event.tid].addWaypoint(addr)
        log(DEBUG_LEVEL.IMPORTANT, "[e] Waypoint hit at address %08x. Continuing ..." % addr)
        
        # remove breakpoint if it was hit too often
        if not self.checkpoints[addr].hit(pid):
            pygdb.removeBreakpoint(addr, pid)
            log(DEBUG_LEVEL.IMPORTANT, "[i] Removed breakpoint %x after too many hits." % (addr))

        return PyGdb.CONTINUE.RUN    
Ejemplo n.º 8
0
 def run(self):
   log("[BluetoothServer] Initializing Bluetooth Server")
   
   stype = bluetooth.RFCOMM
   port = bluetooth.PORT_ANY
   
   server_sock = bluetooth.BluetoothSocket(stype)
   server_sock.bind(("", port))
   server_sock.listen(5)
   
   try:
       bluetooth.advertise_service(server_sock, "Bluemote Service", globals.UUID)
   except bluetooth.BluetoothError, be:
       self.mainapp.die("[BluemoteServer] Can't advertise service. Are the drivers running? Is there a bluetooth device?: " + str(be))
       return
Ejemplo n.º 9
0
 def _dynamicBranchHandler(self, pygdb, event):
     
     log(DEBUG_LEVEL_TRACE_EVENTS, "Dcb hit at %x" % event.addr)
     pygdb.stepInto(event.tid, True)
     nextAddr = pygdb.getPC(event.tid)
     db = self.dynamicBranches[event.addr] 
     if db.characteristics & instruction.CHARACTERISTIC.CALL != 0:
         db.basicBlock.addCall(event.addr, nextAddr)
     else:
         db.basicBlock.addExit(nextAddr)
         if db.characteristics & instruction.CHARACTERISTIC.FAR_BRANCH == 0:
             newBb = BasicBlock(pygdb.getPC(event.tid))
             self._addBasicBlock(newBb)
             return self._bbEntryHandler(pygdb, newBb, event.tid)
         
     return PyGdb.CONTINUE.RUN_KEEP_BREAKPOINT
Ejemplo n.º 10
0
 def _virtCondBranchInDelaySlotHandler(self, pygdb, event):
     """
     TODO: Currently not in use! Think about how to best represent cond. instruction in delay slots on graph-level. 
     The best solution is probably to treat delay slots as distinct basic blocks. This way the real order of instructions would not be messed up.
     """
     willExecute = True
     characteristics = pygdb.cpu.getInstrCharacteristics(pygdb, event.tid, event.addr)
     if characteristics & instruction.CHARACTERISTIC.DELAY_SLOT_LIKELY != 0:
         willExecute = pygdb.cpu.evaluateCondInstr(pygdb, event.tid, event.addr)
         
     if willExecute:
         addrDelaySlot = pygdb.cpu.getAddressDelaySlot(event.addr)
         log(DEBUG_LEVEL_TRACE_EVENTS, "Vbb hit in delay-slot at %x" % addrDelaySlot)
         vbbDS = self.virtBasicBlocks[addrDelaySlot]
         self._processVirtCondBranch(pygdb, vbbDS, event.tid)
     
     return PyGdb.CONTINUE.RUN_KEEP_BREAKPOINT
Ejemplo n.º 11
0
 def _bpDispatcher(self, pygdb, event):
     
     # TODO: Dirty workaround for gdbserver screw up
     # pygdb.enableDieOnProcessExit(True)
     ###############################################
     
     log(DEBUG_LEVEL_TRACE_EVENTS, "[e] Tracer got notified of event at %x in thread %x." % (event.addr, event.tid))
     if event.tid not in self.traces:
         self.traces[event.tid] = BasicBlockTrace(event.tid)
     
     # check if this is a first time hit
     if self.breakOnEntireFunction: 
         pass
     else:
         # check for this being the entry event of the to be traced function
         if not event.addr == self.function:
             raise InvalidTracerState("_bpDispatcher should only be entered through its entry-point (in case breakOnEntireFunction is False).")
         
         if self.requiredCallStack is not None and self.functionTracer is not None:
             currentCallStack = self.functionTracer.getCurrentCallStack(event.tid)
             # check if the required callstack fits to the current callstack
             if not self.requiredCallStack.fitsInto(currentCallStack):
                 # this is not the callstack we wanted
                 # clear own breakpoints and hand the event to the function tracer
                 self._teardownKnownPointsOfInterest(event.pid)
                 return FunctionTracer._callHandler(self.functionTracer, pygdb, event)
             
             # this is the callstack we wanted, temporarily set own breakpoints and unplug the function tracer and start tracing on basic block level
             
             self._unplugFunctionTracer()
                     
     self._setActiveThread(event)
     
     if not self._isKnownAddr(event.addr):
         # TODO: little hack to prevent occasional deadlocks while tracing funcs in OpenSSH 
         pygdb.disableFollowFork()
         #
         newBb = self._createBasicBlock(event.addr, BasicBlock.TYPE.START_BLOCK)
         continueMode = self._bbEntryHandler(pygdb, newBb, event.tid)
         self._aboutToContinue(event.tid)
         return continueMode
     
     else:
         # dispatch the event
         return BasicBlockTracer._eventDispatcher(self, pygdb, event)
Ejemplo n.º 12
0
  def sendCommand(self, cmd):
    mutex.acquire()

    if len(self.clients) > 0:

      log("[LircServer] Received command " + cmd + " a " + str(len(self.clients)) + " clients")
      
      liveclients = []
      
      for c in self.clients:
        if c.sendCommand(cmd + "\n"):
          liveclients.append(c)
      
      self.clients = liveclients
        
    else:
      log("[LircServer] No clients connected, dropping command!")
        
    mutex.release()
Ejemplo n.º 13
0
 def _retHandler(self, pygdb, event):
     pid = event.pid
     if event.tid not in self.traces:
         return PyGdb.CONTINUE.RUN
         
     log(DEBUG_LEVEL.SOME, "[e] Function returned to %08x. Continuing ..." % event.addr)
     
     retAddr = event.addr
     retValues = pygdb.cpu.getFunctionReturnValues(pygdb, event.tid)
     # check if return breakpoint really belongs to this thread
     closedCalls = self.traces[event.tid].ret(retAddr, retValues)
     self.retBps[pid][retAddr].sub(event.tid, closedCalls)
     
     # check if there are still any references to the return breakpoint
     if not self.retBps[pid][retAddr].hasRefs():
         # remove breakpoint
         self.retBps[pid].pop(retAddr)
         pygdb.removeBreakpoint(retAddr, pid)
     
     return PyGdb.CONTINUE.RUN
Ejemplo n.º 14
0
 def _condBranchHandler(self, pygdb, event):
     
     """
     TODO: Dirty dirty hack, revert to release 'PROFTPD FULL AUTH' in order to clean this method up.
     """
     log(DEBUG_LEVEL_TRACE_EVENTS, "[e] Cb hit at %x" % event.addr)
     
     # evaluate condition
     cb = self.condBranches[event.addr]
     assert cb.characteristics & instruction.CHARACTERISTIC.FAR_BRANCH == 0
     
     condition = pygdb.cpu.evaluateCondInstr(pygdb, event.tid, event.addr)
     log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Condition of CB at %x is %s." % (cb.addr, str(condition))) 
     
     if cb.getCondAddr(condition) is None:
         log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Cb is now fully evaluated, removing bp.")
         pygdb.removeBreakpoint(event.addr, GDB.THREADS.ALL)
         pygdb.stepInto(event.tid, False)
         nextAddr = pygdb.getPC(event.tid)
         
         newBb = self._createBasicBlock(nextAddr)
         return self._bbEntryHandler(pygdb, newBb, event.tid)
     else:
         # get next addr for the opposite condition
         nextAddr = pygdb.cpu.getNextPC(pygdb, event.tid, not condition)
         if nextAddr is None:
             # fallback
             log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Cb is not fully evaluated yet. Could not determine other address.")
             return PyGdb.CONTINUE.RUN_KEEP_BREAKPOINT
         
         log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Cb is not fully evaluated yet. Other adress is %x." % nextAddr)
         pygdb.removeBreakpoint(event.addr, GDB.THREADS.ALL)
         newBb = self._createBasicBlock(nextAddr)
         self._addBasicBlock(newBb)
         lastBb = self.traces[event.tid].getLastWaypoint()
         lastBb.addExit(newBb)
     
         return PyGdb.CONTINUE.RUN_KEEP_BREAKPOINT
Ejemplo n.º 15
0
  def init(self):
    self.initlog();
    logger.info("[MainAppServer] Welcome to btlirc Server 0.1")

    lircServer = LircServer(self);
    queue = CommandQueue(self, lircServer)
    queue.start()
    lircServer.start()

    # start bluetooth server
    btServer = BluetoothServer(self, queue)
    btServer.start() 
    
    signal.signal(signal.SIGTERM, lambda *args: self.exit())

    while True:
        if self._exit: 
            break
        
        try:
            sleep(10)
        except KeyboardInterrupt:
            print "[MainAppServer] ** Got KeyboardInterrupt **"
            break
    
    log("[MainAppServer] Shutting down btlirc server.")
      
    #lircServer.join()
    self.killthread(btServer, "Bluetooth Server")
    self.killthread(queue, "Command Queue")
    self.killthread(lircServer, "LIRC Server")
   
    if self._errors:
      logger.info("[MainAppServer] ** Exit with error: " + self._errmsg)
      
    logger.info("[MainAppServer] Bye bye.")
Ejemplo n.º 16
0
 def _bbHandler(self, pygdb, event):
     
     bb = self.basicBlocks[event.addr]
     log(DEBUG_LEVEL_TRACE_EVENTS, "[e] Hit known bb %x in %x" % (bb.startAddr, event.tid))
     if bb.isFullyTraced():
         log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Bb was already fully traced. Continuing...")
         self._processBb(pygdb, bb, event.tid)
         return PyGdb.CONTINUE.RUN_KEEP_BREAKPOINT
     else:
         log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Bb was not fully traced yet. Doing so now...")
         continueMode = self._bbEntryHandler(pygdb, bb, event.tid)
         return continueMode
Ejemplo n.º 17
0
  def run (self):
    
    log("[BluetoothClientHandle] Taking connection")
    while True:
        
      if not self.srv.active:
        break
      
      log("[BluetoothClientHandle] waiting data...")
        
      try:
        buff = self.socket.recv(globals.MAX_MSG_SIZE)
        if not buff: break
      except bluetooth.BluetoothError, e:
        print "Error receiving: %s (%s)" % (e, self.socket)
        break

      log("[BluetoothClientHandle] got: " + buff)
      self.queue.addCommand(buff);
Ejemplo n.º 18
0
        help_ = show_text_file(location, lang)
        if html_output:
            return render_template('index.html', body=help_)
        return help_

    orig_location = location

    location, override_location_name, full_address, country, query_source_location = \
            location_processing()

    us_ip = query_source_location[1] == 'US' and 'slack' not in user_agent
    query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

    log(" ".join(
        map(
            str([
                ip_addr, user_agent, orig_location, location,
                query.get('use_imperial', False), lang
            ]))))

    if country and location != NOT_FOUND_LOCATION:
        location = "%s, %s" % (location, country)

    # We are ready to return the answer
    try:
        if png_filename:
            options = {'lang': None, 'location': "%s,%s" % (location, country)}
            options.update(query)

            cached_png_file = wttrin_png.make_wttr_in_png(png_filename,
                                                          options=options)
            response = make_response(
Ejemplo n.º 19
0
    def _callHandler(self, pygdb, event):
        pid = event.pid
        if pid not in self.retBps:
            self.retBps[pid] = {}
        
        funcAddr = event.addr
        retAddr = pygdb.cpu.getFunctionReturnAddress(pygdb, event.tid)
        outerFuncAddr = pygdb.environment.getNearestFunction(pygdb, retAddr, pid)
        
        # is this the first event for the thread?    
        if event.tid not in self.traces:
            # if so, create the corresponding FunctionTrace
            self.traces[event.tid] = FunctionTrace(event.tid, outerFuncAddr)
        else:
            trace = self.traces[event.tid]
            lastCall = self.traces[event.tid].getTopmostOpenCall()
            assert lastCall is not None
            
            # check if the return address on the stack is plausible
            if outerFuncAddr is None:
                # if not, use the return address of the logical caller
                log(DEBUG_LEVEL.SOME, "[i] Function %x has no sane return address (ret: %x,  logical parent: %x). Trying to merge return address with parent function..." % (funcAddr, retAddr, lastCall.addr ))
                if lastCall.retAddr == FunctionTrace.VIRTUAL_STARTING_NODE:
                    log(DEBUG_LEVEL.SOME, "[i] Apparently function %x is a callback called from outside the target image. We just keep the return address." % funcAddr)
                else:
                    retAddr = lastCall.retAddr
                
            # check if the function returns to the expected function
            elif not outerFuncAddr == lastCall.addr:
                if retAddr == lastCall.retAddr:
                    # do nothing :-)
                    # lastCall is probably just a proxy func
                    pass
                elif len(trace.openCallsStack) > 1:
                    # do nothing
                    # probably just some weird proxying
                    pass
                else:
                    # things are a bit more complicated...
                    # Apparently our virtual outer function has returned without us noticing.
                    # So we are going to close the virtual outer function, making it non virtual...
                    log(DEBUG_LEVEL.SOME, "[i] The return address (%x) of function %x suggests, that the outermost function returned. Going to create a new outer most function (%x)." % (retAddr, funcAddr, outerFuncAddr))
                    # at this point, there should only one open call left
                    dummyRetValues = []
                    ## FunctionTrace.VIRTUAL_STARTING_NODE is always the return address of the starting node. So we call a ret for this one.
                    closedCalls = trace.ret(FunctionTrace.VIRTUAL_STARTING_NODE, dummyRetValues)
                    assert closedCalls == 1
                    
                    # ...and install a new outer function.
                    trace.insertStartingNode(outerFuncAddr)                    

        self.traces[event.tid].call(funcAddr, retAddr)
        
        # check if this is a new return breakpoint
        if retAddr not in self.retBps[pid]:
            self.retBps[pid][retAddr] = _RetBp()
            pygdb.setBreakpoint(retAddr, self._retHandler, self, pid)
            
        # add reference to return breakpoint
        self.retBps[pid][retAddr].add(event.tid) 
        
        log(DEBUG_LEVEL.SOME, "[e] Function at address %08x called. Continuing ..." % funcAddr)
                
        # remove breakpoint if it was hit too often
        if not self.checkpoints[funcAddr].hit(pid):
            pygdb.removeBreakpoint(funcAddr, pid)
            self.traces[event.tid].removedBreakpoints.append(funcAddr)
            
            log(DEBUG_LEVEL.SOME, "[i] Removed function breakpoint %x from process %d after too many hits." % (funcAddr, pid))
                  
        return PyGdb.CONTINUE.RUN
Ejemplo n.º 20
0
def write_system_shutdown_handler(pin, value):
    if (int(value[0]) == 1):
        globals.log('debug', 'Blynk - System Shutdown')
        os.system('sudo poweroff')
Ejemplo n.º 21
0
def _gen_term(buf, graphemes, options=None):
    """Renders rendered pyte buffer `buf` and list of workaround `graphemes`
    to a PNG file, and return its content
    """

    if not options:
        options = {}

    current_grapheme = 0

    buf = _strip_buf(buf)
    cols = max(len(x) for x in buf)
    rows = len(buf)

    image = Image.new('RGB', (cols * CHAR_WIDTH, rows * CHAR_HEIGHT))

    buf = buf[-ROWS:]

    draw = ImageDraw.Draw(image)
    font = {}
    for cat in FONT_CAT:
        font[cat] = ImageFont.truetype(FONT_CAT[cat], FONT_SIZE)

    emojilib = _load_emojilib()

    x_pos = 0
    y_pos = 0
    for line in buf:
        x_pos = 0
        for char in line:
            current_color = _color_mapping(char.fg)
            if char.bg != 'default':
                draw.rectangle(((x_pos, y_pos),
                                (x_pos + CHAR_WIDTH, y_pos + CHAR_HEIGHT)),
                               fill=_color_mapping(char.bg))

            if char.data == "!":
                try:
                    data = graphemes[current_grapheme]
                except IndexError:
                    pass
                current_grapheme += 1
            else:
                data = char.data

            if data:
                cat = _script_category(data[0])
                if cat not in font:
                    globals.log("Unknown font category: %s" % cat)
                if cat == 'Emoji' and emojilib.get(data):
                    image.paste(emojilib.get(data), (x_pos, y_pos))
                else:
                    draw.text((x_pos, y_pos),
                              data,
                              font=font.get(cat, font.get('default')),
                              fill=current_color)

            x_pos += CHAR_WIDTH * constants.WEATHER_SYMBOL_WIDTH_VTE.get(
                data, 1)
        y_pos += CHAR_HEIGHT

    if 'transparency' in options:
        transparency = options.get('transparency', '255')
        try:
            transparency = int(transparency)
        except ValueError:
            transparency = 255

        if transparency < 0:
            transparency = 0

        if transparency > 255:
            transparency = 255

        image = image.convert("RGBA")
        datas = image.getdata()

        new_data = []
        for item in datas:
            new_item = tuple(list(item[:3]) + [transparency])
            new_data.append(new_item)

        image.putdata(new_data)

    img_bytes = io.BytesIO()
    image.save(img_bytes, format="png")
    return img_bytes.getvalue()
Ejemplo n.º 22
0
            return render_template('index.html', body=help_)
        return help_

    orig_location = location

    location, override_location_name, full_address, country, query_source_location = \
            location_processing(location, ip_addr)

    us_ip = query_source_location[1] == 'US' and 'slack' not in user_agent
    query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

    # logging query
    orig_location_utf8 = (orig_location or "").encode('utf-8')
    location_utf8 = location.encode('utf-8')
    use_imperial = query.get('use_imperial', False)
    log(" ".join(map(str,
                     [ip_addr, user_agent, orig_location_utf8, location_utf8, use_imperial, lang])))

    if country and location != NOT_FOUND_LOCATION:
        location = "%s,%s" % (location, country)

    # We are ready to return the answer
    try:
        if png_filename:
            options = {
                'lang': None,
                'location': location}
            options.update(query)

            cached_png_file = wttrin_png.make_wttr_in_png(png_filename, options=options)
            response = make_response(send_file(cached_png_file,
                                               attachment_filename=png_filename,
Ejemplo n.º 23
0
    while (globals.stop_threads == False):
        blynk.run()
        timer.run()
        if (init_loop == True):
            #on the first loop, set baseline variables
            blynk.virtual_write(status_text_vpin, 'Warming up')
            blynk.virtual_write(cook_time_remaining_vpin, '-')
            blynk.virtual_write(mode_selector_vpin, '1')
        
            blynk.virtual_write(manual_timer_hours_vpin, '0')
            blynk.virtual_write(manual_timer_minutes_vpin, '0')

            blynk.virtual_write(target_barrel_temp_vpin, globals.target_barrel_temp)
            blynk.virtual_write(target_meat_temp_vpin, globals.target_meat_temp)

            blynk.virtual_write(manual_pid_kp_vpin, globals.manual_pid_kp)
            blynk.virtual_write(manual_pid_ki_vpin, globals.manual_pid_ki)
            blynk.virtual_write(manual_pid_kd_vpin, globals.manual_pid_kd)
            blynk.virtual_write(pid_profile_override_vpin, 0)
            blynk.virtual_write(recipe_selector_vpin, 1)
            blynk.virtual_write(recipe_description_vpin, 'clr')

            init_loop = False

        
    globals.log('info', 'Blynk Interface Stopped')


if __name__ == "__main__":
    globals.log('error', 'Start the Blynk Interface with ./smokey_mc_smokerson.py')
Ejemplo n.º 24
0
    def _bbEntryHandler(self, pygdb, startBb, tid):
        """
        Traces until it reaches an ret-instruction or enters an already catalogued basic-block.
        TODO: Consider likely-delay slots!
        """
        
        continueMode = PyGdb.CONTINUE.RUN
        bb = startBb
        while (bb is not None) and not bb.isFullyTraced():
            
            log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Entering bb %x" % bb.startAddr) 
            
            nextBb = None
            nextAddr = bb.startAddr
            
            while True:
                addr = nextAddr
                
                # Is this the first instruction of the basic block?
                characteristics = pygdb.cpu.getInstrCharacteristics(pygdb, tid, addr)
                conditional = characteristics & instruction.CHARACTERISTIC.CONDITIONAL != 0
                jmp = characteristics & instruction.CHARACTERISTIC.JMP != 0
                dynamicBranch = characteristics & instruction.CHARACTERISTIC.DYNAMIC_BRANCH != 0 and BasicBlockTracer.EXAMINE_DYNAMIC_BRANCHES
                call = characteristics & instruction.CHARACTERISTIC.CALL != 0
                ret = characteristics & instruction.CHARACTERISTIC.RET != 0
                functionEnds = pygdb.cpu.isEndOfFunction(pygdb, tid, characteristics)
                
                if conditional:
                    condition = pygdb.cpu.evaluateCondInstr(pygdb, tid, addr)
                    
                # first check if we hit a ret instruction
                # TODO: What happens in the case of a conditional return?
                
                def functionEnd(bb):
                    bb.addType(BasicBlock.TYPE.END_BLOCK)
                    # no exits to other basic blocks in case of a ret
                    bb.setNExits(0)
                    
                if ret or functionEnds:
                    functionEnd(bb)
                    break
                
		# get (if exists) the next addresses of the true and false conditional branche (to store in the possibleExits list of the BB)
		# added by andre
                true_addr = pygdb.cpu.getNextPC(pygdb, tid, cond=True)
                false_addr = pygdb.cpu.getNextPC(pygdb, tid, cond=False)

                # Now already step to the next instruction.
                if call:
                    stepSuccess, nextAddr, stepIntoAddr = pygdb.stepOver(tid, stayInImage=False)
                else:
                    stepSuccess, nextAddr, stepIntoAddr = pygdb.stepOver(tid, stayInImage=True)
                    
                log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Stepped to instruction %x in bb %x" % (nextAddr,bb.startAddr))
                
                if not stepSuccess:
                    # this condition can happen if the debugger is killed just when we're trying to step
                    # we just end for now...
                    log(DEBUG_LEVEL.IMPORTANT, "[!] Failed to step instruction. We therefore just assume the function ends at %x." % addr)
                    functionEnd(bb)
                    break
                
                # check if we jumped into another function. This is equivalent to a ret.
                if jmp and nextAddr in pygdb.environment.getFunctionsRebased(pygdb):
                    functionEnd(bb)
                    break
                
                # check if we jumped out of our image. This is as well equivalent to a ret.
                if not pygdb.environment.addrBelongsToImage(pygdb, nextAddr):
                    functionEnd(bb)
                    break
                
                # so we manipulated the pc, we need to change the continue type
                continueMode = PyGdb.CONTINUE.RUN_NO_CLEANUP
                # now evaluate the instruction we just stepped over
                    
                if characteristics & instruction.CHARACTERISTIC.HAS_DELAY_SLOT != 0:
                    # we have a delay slot, this a special case
                    # if the delay slot does not contain a conditional instruction everything is fine
                    # else we need to create a new virtual basic block
                    addrDelaySlot = pygdb.cpu.getAddressDelaySlot(addr)
                    characteristicsDelaySlot = pygdb.cpu.getInstrCharacteristics(pygdb, tid, addrDelaySlot)
                    
                    if characteristicsDelaySlot & instruction.CHARACTERISTIC.IMPLICIT_BRANCH != 0:
                        # in case of an implicit conditional branch to a virtual basic block, the current basic block only has one real exit
                        bb.setNExits(2)
                        condictionDelaySlot = pygdb.cpu.evaluateCondInstr(pygdb, tid, addrDelaySlot)
                        
                        # create the next concrete basic block
                        nextBb = self._createBasicBlock(nextAddr)
                        
                        # now add the virtual basic block
                        if addr not in self.virtBasicBlocks:
                            vbbDS = BasicBlock(startAddr=addrDelaySlot, endAddr=addrDelaySlot, knownExits=[nextBb], nExits=1, t=(BasicBlock.TYPE.VIRTUAL | BasicBlock.TYPE.IN_DELAY_SLOT))
                            self._addVirtualBasicBlock(vbbDS, addr)
                            
                        if condictionDelaySlot:
                            self.addWaypoint(vbbDS, tid)
                            
                        break
                            
                if call:
                    bb.addCall(addr, stepIntoAddr)
                        
                if dynamicBranch:
                    
                    db = DynamicBranch(addr, characteristics, bb)
                    self._addDynamicBranch(db)
                    if jmp:
                        bb.setNExits(BasicBlock.DYNAMIC_EXIT)
                        nextBb = self._createBasicBlock(nextAddr)
                        break
                        
                elif conditional:
                    # in case of a conditional instruction, this is the last instruction of the basicblock
                    bb.setNExits(2)
                    # check if this an implicit conditional instruction
                    if characteristics & instruction.CHARACTERISTIC.IMPLICIT_BRANCH != 0:
                        # create new basic block directly after the conditional instruction
                        nextBb = BasicBlock(nextAddr, t=BasicBlock.TYPE.ADJACENT_TO_VIRTUAL)
                        
                        # now add the virtual basic block
                        if addr not in self.virtBasicBlocks:
                            vbb = BasicBlock(startAddr=addr, endAddr=addr, knownPredecessors = [bb], knownExits=[nextBb], nExits=1, t=BasicBlock.TYPE.VIRTUAL)
                            self._addVirtualBasicBlock(vbb)
                        else:
                            vbb = self.virtBasicBlocks[addr]
                            
                        bb.addExit(vbb)
                        bb.setEndAddr(addr)
                        
                        if condition:
                            # smuggle the vbb in
                            ## add current bb
                            self._addBasicBlock(bb)
                            self._addWaypoint(bb, tid)
                            
                            ## set current bb to vbb, such that it is added in the next step
                            bb = vbb
                        
                    elif jmp:
			# add true and false conditional branch to possibleExits list of BB
			# added by andre
                        bb.possibleExits.append(false_addr)
                        bb.possibleExits.append(true_addr)

                        cb = CondBranch(addr, characteristics)
                        self._addCondBranch(cb)
                        self.condBranches[addr].condTaken(condition, nextAddr)
                        nextBb = self._createBasicBlock(nextAddr)
                        
                    else:
                        raise InvalidTracerState("This state should never be reached. Address: %x" % addr) 
                    
                    break
                elif jmp:
                    # unconditional jump
                    bb.setNExits(1)
                    # before creating a new bb, check if we branched into an already existing basic block
                    nextBb = self._createBasicBlock(nextAddr)
                    break
            
                # finally check if we stepped on an already known bb
                elif nextAddr in self.basicBlocks:
                    bb.setNExits(1)
                    nextBb = self.basicBlocks[nextAddr]
                    break
                
            log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Completely traced bb %x" % bb.startAddr)
            bb.addExit(nextBb)
            bb.setEndAddr(addr)
            bb.setFullyTraced()
            self._addBasicBlock(bb)
            self._addWaypoint(bb, tid)
            bb = nextBb
        
        return continueMode
Ejemplo n.º 25
0
def write_target_meat_temp_handler(pin, value):
    global meat_ready_notification_sent
    globals.log('debug', 'Blynk - Target Meat Temperature Set to: {}'.format(value[0]))
    meat_ready_notification_sent = False
    globals.target_meat_temp = int(value[0])
Ejemplo n.º 26
0
def write_target_barrel_temp_handler(pin, value):
    globals.log('debug', 'Blynk - Target Smoker Temperature Set to: {}'.format(value[0]))

    globals.target_barrel_temp = int(value[0])
Ejemplo n.º 27
0
def write_manual_timer_minutes_handler(pin, value):
    global manual_timer_minutes
    manual_timer_minutes = int(value[0])
    globals.log('debug', 'Blynk - Manual Timer Minutes Set to: {}'.format(value[0]))
Ejemplo n.º 28
0
def write_manual_pid_KD_val_handler(pin, value):
    globals.log('debug', 'Blynk - Manual PID Kd Set to: {}'.format(value[0]))
    globals.manual_pid_kd = float(value[0])
Ejemplo n.º 29
0
import time
from simple_pid import PID
import globals
import MAX6675
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.PWM as PWMLib

try:
    platform = GPIO.Platform.platform_detect()
    assert(platform == 1)
    simulated_mode = False
except:
    simulated_mode = True
    globals.log('warning', "Temperature Controller - Platform is not a Raspberry Pi, running in simulated mode")

config = globals.config

#pins
CLK_pin = config['pin_outs']['thermocouple_clk']
DO_pin = config['pin_outs']['thermocouple_do']
TC1_CS_pin = config['pin_outs']['thermocouple_1_cs']
TC2_CS_pin = config['pin_outs']['thermocouple_2_cs']
TC3_CS_pin = config['pin_outs']['thermocouple_3_cs']
TC4_CS_pin = config['pin_outs']['thermocouple_4_cs']
TC5_CS_pin = config['pin_outs']['thermocouple_5_cs']

#Fan variables
fan1_frequency = 25000
fan1_pin = config['pin_outs']['fan_1']
fan2_frequency = 25000
fan2_pin = config['pin_outs']['fan_2']
Ejemplo n.º 30
0
def was_seen(sizes_with_links: list) -> dict:
    local_session = session_factory()

    # Checking whether a link is already in DB
    pic_already_in_db = list(
        map(lambda x: PictureSize.get_by_link(x.get('url'), local_session),
            sizes_with_links))
    if any(pic_already_in_db):
        # Already in DB
        log(label, "Same link")
        return {
            'result': True,
            'simpic': list(filter(lambda x: x, pic_already_in_db))[0]
        }

    sizes = sort_sizes(list(map(lambda x: x.get('type'), sizes_with_links)))

    optimal_sizes_futures = [
        pool.get().apply_async(get_optimal_pair, args=(
            sizes,
            pic_id,
        )) for pic_id in Picture.get_all_ids(local_session)
    ]
    optimal_sizes = []
    for pair in [i.get() for i in optimal_sizes_futures]:
        if pair is not None:
            optimal_sizes.append(pair)

    local_session.close()

    if not len(optimal_sizes):
        log(label, f"No common sizes")
        return {'result': False, 'simpic': None}

    optimal_sizes_set = set([x[1] for x in optimal_sizes])
    sizes_raw_cache = dict([
        x.get() for x in [
            pool.get().apply_async(load_pic,
                                   args=(pic_size,
                                         next(
                                             iter([
                                                 x.get('url')
                                                 for x in sizes_with_links
                                                 if x.get('type') == pic_size
                                             ]), )))
            for pic_size in optimal_sizes_set
        ]
    ])

    # Starting async_pool to compare all of pictures with same size with current
    log(label, f"Checking {len(optimal_sizes)} pictures")
    results = [
        pool.get().apply_async(rms_compare,
                               args=(
                                   pic,
                                   sizes_raw_cache.get(max_common_size),
                               )) for pic, max_common_size in optimal_sizes
    ]
    for res, pic in [i.get() for i in results]:
        if res < 10:
            # Pictures are similar enough
            log(label, f"Already seen, has similar picture, id={pic.id}")
            return {'result': True, 'simpic': pic}
    log(label, "No similar pic, returning...")
    return {'result': False, 'simpic': None}
Ejemplo n.º 31
0
 def killthread(self, t, name):
   log("[MainAppServer] Waiting for " + name + " to shutdown...") 
   
   t.setactive(False)
   
   log("[MainAppServer] ..." + name + " shutdown complete.")
Ejemplo n.º 32
0
 def _addCondBranch(self, cb):
     assert self.activeProcess is not None
     if not cb.addr in self.condBranches:
         log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Creating a new CB at %x." % cb.addr)
         self.condBranches[cb.addr] = cb
         self.pygdb.setBreakpoint(cb.addr, self._eventDispatcher, self, self.activeProcess)
Ejemplo n.º 33
0
    if location in PLAIN_TEXT_PAGES:
        help_ = show_text_file(location, lang)
        if html_output:
            return render_template('index.html', body=help_)
        return help_

    orig_location = location

    location, override_location_name, full_address, country, query_source_location = \
            location_processing(location, ip_addr)

    us_ip = query_source_location[1] == 'US' and 'slack' not in user_agent
    query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

    log(" ".join(map(str, [
        ip_addr, user_agent, orig_location.encode('utf-8'), location,
        query.get('use_imperial', False), lang
        ])))

    if country and location != NOT_FOUND_LOCATION:
        location = "%s, %s" % (location, country)

    # We are ready to return the answer
    try:
        if png_filename:
            options = {
                'lang': None,
                'location': "%s,%s" % (location, country)}
            options.update(query)

            cached_png_file = wttrin_png.make_wttr_in_png(png_filename, options=options)
            response = make_response(send_file(cached_png_file,
Ejemplo n.º 34
0
def process_pic(msg) -> None:
    # Getting all the attachments even in forwarded messages
    attachments = msg.get('attachments') + get_attachments(
        msg.get('fwd_messages'))
    # Leaving only the photos
    photos = list(
        map(lambda x: x.get('photo'),
            list(filter(lambda x: x.get('type') == 'photo', attachments))))
    # New thread - new session
    outer_session = session_factory()
    sender_id = msg.get('from_id')
    # Getting the user from DB or creating a new one
    user: User = outer_session.query(User).filter(User.id == sender_id).first()
    if not User:
        user = User(sender_id)
        outer_session.add(user)
        outer_session.commit()
    user.all_pics += len(photos)
    # Message that will be sent to chat if picture has been already seen
    seen_message = Phrase.get_random().split(':')[1].strip() + '\n'

    seen: int = 0
    start_time = time.time()
    # Count of seen pictures
    for pic in photos:
        sizes = pic.get('sizes')  # All sizes for this picture
        pic_id = pic.get('id')

        # Checking if a max size of this picture has been already seen
        result = was_seen(sizes)

        if result.get('result'):
            # Already seen
            seen += 1
            picture_size: PictureSize = result.get('simpic')
            local_session = session_factory()
            picture: Picture = Picture.get(
                picture_size.pic_id) if picture_size else None
            user.bads += picture.bads
            orig_user: User = User.get(picture.user_id,
                                       local_session) if picture else None
            if orig_user:
                seen_message += f'Отправил  {orig_user.first_name}' \
                                f' {orig_user.last_name}  в' \
                                f'  {format_time(picture_size.add_time)}\n'
            local_session.close()
        else:
            # New picture
            # Adding it to the DB
            picture = Picture(pic_id, sender_id, pic.get('owner_id'),
                              pic.get('access_key'))
            outer_session.add(picture)
            outer_session.commit()
            for size in sizes:
                outer_session.add(
                    PictureSize(pic_id, size.get('type'), size.get('url')))
            outer_session.add(PicMessage(sender_id, pic_id, msg.get('text')))
            outer_session.commit()

    end_time = time.time()
    log(label, f"Checked in {end_time - start_time}")

    # Adding negative carma for each seen picture

    # Sending a message if any picture was not new
    if seen > 0:
        log(label,
            f"{user.first_name} {user.last_name} downs +1 = {user.downs}")
        user.downs += 1
        peer_id = msg.get('peer_id')
        api.messages.send(peer_id=peer_id,
                          message=seen_message,
                          random_id=get_rand())

    outer_session.add(user)
    outer_session.commit()
    outer_session.close()
Ejemplo n.º 35
0
 def _aboutToContinue(self, tid):
     lastBb = self._getLastBb(tid)
     if lastBb.type & BasicBlock.TYPE.END_BLOCK != 0:
         self._unsetActiveThread()
         log(DEBUG_LEVEL_TRACE_EVENTS, "[i] Basic-block %x was the last one in the function. Continuing..." % lastBb.startAddr)
Ejemplo n.º 36
0
def wttr(location, request):
    """
    Main rendering function, it processes incoming weather queries.
    Depending on user agent it returns output in HTML or ANSI format.

    Incoming data:
        request.args
        request.headers
        request.remote_addr
        request.referrer
        request.query_string
    """
    def _wrap_response(response_text, html_output):
        response = make_response(response_text)
        response.mimetype = 'text/html' if html_output else 'text/plain'
        return response

    if is_location_blocked(location):
        return ""

    ip_addr = client_ip_address(request)

    try:
        LIMITS.check_ip(ip_addr)
    except RuntimeError as exception:
        return str(exception)

    png_filename = None
    if location is not None and location.lower().endswith(".png"):
        png_filename = location
        location = location[:-4]

    lang = get_answer_language(request)
    query = parse_query.parse_query(request.args)
    html_output = get_output_format(request, query)
    user_agent = request.headers.get('User-Agent', '').lower()

    if location in PLAIN_TEXT_PAGES:
        help_ = show_text_file(location, lang)
        if html_output:
            return _wrap_response(render_template('index.html', body=help_),
                                  html_output)
        return _wrap_response(help_, html_output)

    if location and ':' in location:
        location = cyclic_location_selection(location, query.get('period', 1))

    orig_location = location

    if not png_filename:
        location, override_location_name, full_address, country, query_source_location = \
                location_processing(location, ip_addr)

        us_ip = query_source_location[
            1] == 'United States' and 'slack' not in user_agent
        query = parse_query.metric_or_imperial(query, lang, us_ip=us_ip)

        # logging query
        orig_location_utf8 = (orig_location or "").encode('utf-8')
        location_utf8 = location.encode('utf-8')
        use_imperial = query.get('use_imperial', False)
        log(" ".join(
            map(str, [
                ip_addr, user_agent, orig_location_utf8, location_utf8,
                use_imperial, lang
            ])))

        if country and location != NOT_FOUND_LOCATION:
            location = "%s,%s" % (location, country)

    # We are ready to return the answer
    try:
        if 'format' in query:
            return _wrap_response(
                wttr_line(location, override_location_name, query, lang),
                html_output)

        if png_filename:
            options = {'ip_addr': ip_addr, 'lang': lang, 'location': location}
            options.update(query)

            cached_png_file = wttrin_png.make_wttr_in_png(png_filename,
                                                          options=options)
            response = make_response(
                send_file(cached_png_file,
                          attachment_filename=png_filename,
                          mimetype='image/png'))
            for key, value in {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0',
            }.items():
                response.headers[key] = value

            # Trying to disable github caching
            return response

        if location.lower() == 'moon' or location.lower().startswith('moon@'):
            output = get_moon(location,
                              html=html_output,
                              lang=lang,
                              query=query)
        else:
            output = get_wetter(
                location,
                ip_addr,
                html=html_output,
                lang=lang,
                query=query,
                location_name=override_location_name,
                full_address=full_address,
                url=request.url,
            )

        if query.get('days', '3') != '0' and not query.get('no-follow-line'):
            if html_output:
                output = add_buttons(output)
            else:
                #output += '\n' + get_message('NEW_FEATURE', lang).encode('utf-8')
                output += '\n' + get_message('FOLLOW_ME',
                                             lang).encode('utf-8') + '\n'

        return _wrap_response(output, html_output)

    except RuntimeError as exception:
        if 'Malformed response' in str(exception) \
                or 'API key has reached calls per day allowed limit' in str(exception):
            if html_output:
                return _wrap_response(MALFORMED_RESPONSE_HTML_PAGE,
                                      html_output)
            return _wrap_response(
                get_message('CAPACITY_LIMIT_REACHED', lang).encode('utf-8'),
                html_output)
        logging.error("Exception has occured", exc_info=1)
        return "ERROR"
Ejemplo n.º 37
0
def run_temperature_controller():
    
    globals.log('info', 'Temperature Controller Started')

    #Initialize Pid
    pid = PID(Kp=aggressive_kp, Ki=aggressive_ki, Kd=aggressive_kd, setpoint=globals.target_barrel_temp, output_limits=(0, 100), auto_mode=True, proportional_on_measurement=False)

    if (simulated_mode == False):
        #Initialize Fan
        pwm = PWMLib.get_platform_pwm()
        pwm.start(fan1_pin, globals.fan_speed, fan1_frequency)

        #if a second fan is defined, initialize that as well
        if(fan2_pin) :
            pwm.start(fan2_pin, globals.fan_speed, fan2_frequency)

        #initialize thermocouples
        TC1 = MAX6675.MAX6675(CLK_pin, TC1_CS_pin, DO_pin)
        TC2 = MAX6675.MAX6675(CLK_pin, TC2_CS_pin, DO_pin)
        TC3 = MAX6675.MAX6675(CLK_pin, TC3_CS_pin, DO_pin)
        TC4 = MAX6675.MAX6675(CLK_pin, TC4_CS_pin, DO_pin)
        TC5 = MAX6675.MAX6675(CLK_pin, TC5_CS_pin, DO_pin)

        #Initialize Temperatures
        #read sensors
        TC1_temp = TC1.readTempC()
        time.sleep(0.1)
        TC2_temp = TC2.readTempC()
        time.sleep(0.1)
        TC3_temp = TC3.readTempC()
        time.sleep(0.1)
        TC4_temp = TC4.readTempC()
        time.sleep(0.1)
        TC5_temp = TC5.readTempC()

    else:
        #if in simulated mode, set to 20 degrees baseline
        TC1_temp = 20
        TC2_temp = 20
        TC3_temp = 20
        TC4_temp = 20
        TC5_temp = 20

        #and create empty pwm object
        pwm = None

    #set variables used in the loop
    TC5_temp_last = TC5_temp
    temp_weighted_avg_last = ((TC1_temp + TC2_temp + TC3_temp + TC4_temp) / 4)

    #keep looping until instructed otherwise
    while(globals.stop_threads == False):
        #update setpoint if it differs
        if (pid.setpoint != globals.target_barrel_temp):
            globals.log('debug', 'Temperature Controller - PID Setpoint changed to: {}'.format(globals.target_barrel_temp))
            pid.setpoint = globals.target_barrel_temp

        #read sensors and if in simulated mode, calculate based on fan speed
        if (simulated_mode == False):
            TC1_temp = TC1.readTempC()
            time.sleep(0.1)
            TC2_temp = TC2.readTempC()
            time.sleep(0.1)
            TC3_temp = TC3.readTempC()
            time.sleep(0.1)
            TC4_temp = TC4.readTempC()
            time.sleep(0.1)
            TC5_temp = TC5.readTempC()
        else:
            simulated_temp = simulate_temperature(TC1_temp)
            TC1_temp = TC2_temp = TC3_temp = TC4_temp = simulated_temp
            TC5_temp += 0.01

        #Calculations
        temp_weighted_avg = ((TC1_temp + TC2_temp + TC3_temp + TC4_temp) / 4) # + 45 From SmokeyTheBarrel: temperature compensation between outside and center of the barrel
        temp_weighted_avg_last=(2 * temp_weighted_avg_last + temp_weighted_avg) / 3
        globals.current_barrel_temp = temp_weighted_avg_last
        temperature_gap = globals.target_barrel_temp - temp_weighted_avg_last
        globals.current_temp_gap = temperature_gap

        TC5_temp_last=(2 * TC5_temp_last + TC5_temp)/3;
        globals.current_meat_temp = TC5_temp_last

        #use conservative pid profile for small temperature differences
        if (temperature_gap >= -10  and temperature_gap <= 10):
            set_pid_profile(pid, 'conservative')

        #otherwise use the aggresive profile
        else:
            set_pid_profile(pid, 'aggressive')

        #calculate new fan speed and set the fan speed
        pid_output = pid(temp_weighted_avg_last)
        set_fan_speed(pwm, pid_output)

        #sleep for a second
        time.sleep(1)

    if (simulated_mode == False):
        pwm.stop(fan1_pin)
        if (fan2_pin):
            pwm.stop(fan2_pin)

    globals.log('info', 'Temperature Controller Stopped')
Ejemplo n.º 38
0
    def resign_ipa(self,
                   ipa_path,
                   entitlements_path,
                   mobileprovision_path,
                   identity,
                   sign_file=None):
        """
        important: type(sign_file) should be []

        1.unzip ipa file
        2.remove old sign dictionary
        3.copy mobileprovision
        4.sign and inject all sign_file if sign_file is not None
        5.sign app
        6.verify sign
        7.zip as ipa
        8.return new signed ipa_path
        """

        ipa_path = os.path.abspath(os.path.expanduser(ipa_path))
        entitlements_path = os.path.abspath(
            os.path.expanduser(entitlements_path))
        mobileprovision_path = os.path.abspath(
            os.path.expanduser(mobileprovision_path))
        #check ipa_path, entitlements_path, mobileprovision_path exists and is file
        if not self.local_file_exists(ipa_path):
            G.log(G.INFO, 'File \'%s\' not exists or not a file.' % ipa_path)
            return None
        elif not self.local_file_exists(entitlements_path):
            G.log(G.INFO,
                  'File \'%s\' not exists or not a file.' % entitlements_path)
            return None
        elif not self.local_file_exists(mobileprovision_path):
            G.log(
                G.INFO,
                'File \'%s\' not exists or not a file.' % mobileprovision_path)
            return None

        #mk temp dir
        basename = os.path.basename(ipa_path)
        cmd = '/usr/bin/mktemp -d %s' % os.path.join(
            '/tmp', '_SecAutid_IPA_%s_%s' % (basename, uuid.uuid1()))
        r = self.exec_shell(cmd)
        tmp = r[:-1]

        #1.unzip ipa file
        G.log(G.INFO, 'unzip ipa file')
        cmd = 'cd %s && /usr/bin/unzip -q \'%s\'' % (tmp, ipa_path)
        r = self.exec_shell(cmd)

        #get *.app path
        app_tmp_path = None
        for f in os.listdir(os.path.join(tmp, 'Payload')):
            if f.endswith('.app'):
                app_tmp_path = os.path.join(tmp, os.path.join('Payload', f))

        if app_tmp_path is None:
            G.log(G.INFO, 'unzip error')
            return None

        #2.remove old sign dictionary
        G.log(G.INFO, 'remove old sign dictionary')
        old_sign_dir = os.path.join(app_tmp_path, '_CodeSignature')
        if os.path.exists(old_sign_dir):
            cmd = 'rm -rf %s' % (old_sign_dir)
            r = self.exec_shell(cmd)

        #3.copy mobileprovision
        G.log(G.INFO, 'copy mobileprovision')
        cmd = 'cp %s %s' % (mobileprovision_path,
                            os.path.join(app_tmp_path,
                                         'embedded.mobileprovision'))
        r = self.exec_shell(cmd)

        #4.sign and inject all sign_file if sign_file is not None
        if sign_file is not None:
            if type(sign_file) is list:
                G.log(G.INFO, 'sign all inject file')

                #find binary path
                info_plist = os.path.join(app_tmp_path, 'Info.plist')
                import shutil
                info_plist_path = os.path.join(tmp, 'Info.plist')
                shutil.copy2(info_plist, info_plist_path)
                info_plist_util = InfoPlistUtil(info_plist_path)
                binary_name = info_plist_util.get_property(
                    "CFBundleExecutable")
                binary_path = os.path.join(app_tmp_path, binary_name)

                for f in sign_file:
                    #cp f Payload/WeChat.app/
                    #codesign -f -s 'iPhone Developer: Long Chen (3K54S797W6)' --entitlements entitlements.plist Payload/WeChat.app/libeeee.dylib
                    path = os.path.abspath(os.path.expanduser(f))
                    if self.local_file_exists(path):
                        #copy file into *.app
                        cmd = 'cp %s %s' % (path, app_tmp_path)
                        r = self.exec_shell(cmd)
                        #sign inject file
                        cmd = '/usr/bin/codesign -f -s \'%s\' --entitlements %s %s' % (
                            identity, entitlements_path,
                            os.path.join(app_tmp_path, os.path.basename(path)))
                        r = self.exec_shell(cmd)
                        #inject binary
                        self.inject_dylib_to_binary(binary_path, path)

        #5.sign app
        G.log(G.INFO, 'sign app')
        #cmd: codesign -f -s 'iPhone Developer: Name Name (XXXXXXXX)' --entitlements entitlements.plist Payload/WeChat.app
        cmd = '/usr/bin/codesign -f -s \'%s\' --entitlements %s %s' % (
            identity, entitlements_path, app_tmp_path)
        r = self.exec_shell(cmd)

        #6.verify sign
        G.log(G.INFO, 'verify sign')
        cmd = '/usr/bin/codesign --verify %s' % app_tmp_path
        r = self.exec_shell(cmd)
        if r != '':
            G.log(G.INFO, 'verify sign failed')
            return None

        #7.zip as ipa
        G.log(G.INFO, 'zip new ipa file')
        new_signed_ipa = os.path.join(os.path.dirname(ipa_path),
                                      '%s.resigned.ipa' % basename)
        cmd = 'cd %s && /usr/bin/zip -qr %s %s' % (tmp, new_signed_ipa,
                                                   'Payload')
        r = self.exec_shell(cmd)

        G.log(G.INFO, 'Resign success')
        G.log(G.INFO, 'resigned ipa: %s' % new_signed_ipa)

        return new_signed_ipa
Ejemplo n.º 39
0
def gen_term(filename, buf, options=None):
    buf = strip_buf(buf)
    cols = max(len(x) for x in buf)
    rows = len(buf)

    image = Image.new('RGB', (cols * CHAR_WIDTH, rows * CHAR_HEIGHT))

    buf = buf[-ROWS:]

    draw = ImageDraw.Draw(image)
    font = {}
    for cat in FONT_CAT:
        font[cat] = ImageFont.truetype(FONT_CAT[cat], FONT_SIZE)

    x_pos = 0
    y_pos = 0
    for line in buf:
        x_pos = 0
        for char in line:
            current_color = color_mapping(char.fg)
            if char.bg != 'default':
                draw.rectangle(((x_pos, y_pos),
                                (x_pos + CHAR_WIDTH, y_pos + CHAR_HEIGHT)),
                               fill=color_mapping(char.bg))

            if char.data:
                cat = script_category(char.data)
                if cat not in font:
                    log("Unknown font category: %s" % cat)
                draw.text((x_pos, y_pos),
                          char.data,
                          font=font.get(cat, font.get('default')),
                          fill=current_color)
            #sys.stdout.write(c.data)

            x_pos += CHAR_WIDTH
        y_pos += CHAR_HEIGHT
        #sys.stdout.write('\n')

    if 'transparency' in options:
        transparency = options.get('transparency', '255')
        try:
            transparency = int(transparency)
        except:
            transparceny = 255

        if transparency < 0:
            transparency = 0

        if transparency > 255:
            transparency = 255

        image = image.convert("RGBA")
        datas = image.getdata()

        new_data = []
        for item in datas:
            new_item = tuple(list(item[:3]) + [transparency])
            new_data.append(new_item)

        image.putdata(new_data)

    image.save(filename)