示例#1
0
 def response(progress):
   if progress >= 85:
     if not self.isReady:
       self.isReady = True
       self.torApp.on_ready()
       return
   #TODO:  handle the case where we get here with <80% progress.  What then?  Can it even happen?
   elif progress >= 80:
     #start a thread to periodically try launching circuits to random routers:
     self.startup_circuits = []
     Scheduler.schedule_repeat(2, self.try_new_circuit)
示例#2
0
  def start(self):
    """Delete the old logs and open the new ones"""
    if ProgramState.PY2EXE:
      #these redirect output, to avoid writing to the Main.exe.log (default py2exe behavior)
      #we want to avoid that because it pops a dialog about errors, and we definitely want to fail silently when demoing the app...
      sys.stdout = open(os.path.join(Globals.LOG_FOLDER, 'stdout.out'), "w")
      sys.stderr = open(os.path.join(Globals.LOG_FOLDER, 'stderr.out'), "w")

    #remove the old tor logs:
    Files.delete_file(os.path.join(Globals.LOG_FOLDER, 'tor.out'), True)
    #open up the debug logs and create the testfile:
    self.start_logs(["main", "errors", "automated", "pysocks", "tor_conn"], "main", Globals.LOG_FOLDER)
    #rotate the logs every half an hour, so that they can have lots of info, but not fill someone's hard drive...
    Scheduler.schedule_repeat(30 * 60, self.rotate_logs)
示例#3
0
 def _on_bank_ready(self, result):
   """Called when the bank has finished starting.  Alerts the applications to any
   startup arguments that were passed in, which will likely cause them to actually start."""
   if result != True:
     log_msg("Bank failed to start correctly!", 0)
     return result
     
   #handle the starting arguments:
   Startup.handle_args(ProgramState.STARTING_DIR, sys.argv[1:])
   GlobalEvents.throw_event("startup")
   
   #if this is the first run, save all the settings files:
   if self.bbApp.isFirstRun:
     for app in [self.bbApp, self.btApp, self.torApp, self.ffApp]:
       if app:
         app.settings.save()
   self.coreSettings.save()
    
   #schedule update function:
   def do_update():
     BWHistory.update_all()
     return True
   ProgramState.DO_UPDATES = True
   self.updateEvent = Scheduler.schedule_repeat(Globals.INTERVAL_BETWEEN_UPDATES, do_update)
   return result
示例#4
0
 def start_connections(self, list):
     peers_added = 0
     #add to our current list except duplicates:       
     for peer in list:
         if self.to_connect.count(peer) == 0:
             if self.prev_connected.count(peer) == 0:
                 self.never_connected.append(peer)
                 peers_added += 1
             else:
                 self.to_connect.append(peer)
                 peers_added += 1
     log_msg("Added %s to our list of peers, now %s long." % (peers_added, len(self.to_connect)), 2, "tracker")
     
     #without this, the peers would be each get connected to twice on the very first update if they fail
     if self.lastPeerCycleTime == 0:
       self.lastPeerCycleTime = time.time()
     
     #for testing:  sometimes handy to print out peers so I can make sure we can connect to them later
     #f = open("peer_list.txt", "wb")
     #for x in list:
     #  dns, id, encrypted = x
     #  #log_msg("%s %s (%s)" % (encrypted, dns, id))
     #  f.write("%s:%s\n" % (dns[0], dns[1]))
     #f.close()
     #make sure we're starting connections from that list:
     if not self.startConnectionsEvent:
       self.startConnectionsEvent = Scheduler.schedule_repeat(1.0, self._start_connection_from_queue)
       self._start_connection_from_queue()
 def _start_test(self, widget=None):
   self.torApp.start_server()
   for box in (self.relayBox, self.dirBox, self.dhtBox):
     box.apply_value()
   self.torApp.settings.on_apply(self.torApp, "")
   
   self._cancel_test_update()
   self.testUpdateEvent = Scheduler.schedule_repeat(0.1, self._test_update)
   #update the title to reflect the fact that we are currently testing
   self._on_test_started()
 def _check_apps(self):
   if not self.programCheckEvent:
     self.programCheckEvent = Scheduler.schedule_repeat(1.0, self._check_apps)
   #program still running?
   if self.currentApp and self.currentApp.poll() == None:
     log_msg("Waiting for UAC app to finish...", 1)
     return True
   #are there any more to launch?
   if len(self.launchList) > 0:
     #launch the next one:
     cmd, nextDeferred = self.launchList.pop(0)
     log_msg("Launching next UAC app:  %s" % (cmd), 1)
     self.currentApp = LaunchProcess.LaunchProcess(cmd)
     process = Process.Process(self.currentApp.pid)
     process.d.chainDeferred(nextDeferred)
     return True
   #nothing else to launch:
   else:
     log_msg("No more UAC apps to launch.", 1)
     self.programCheckEvent = None
     return False
示例#7
0
  def do_expose_event(self, event):
    #schedule the draw event if this is the first time we've ever been exposed
    if not self.shouldDraw:
      self.shouldDraw = True
      Scheduler.schedule_repeat(1.0, self.draw)
    self.visible_cb()
    #Create the cairo context
    self.cr = self.window.cairo_create()
    #Restrict Cairo to the exposed area; avoid extra work
    self.cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height)
    self.cr.clip()
    width, height = self.window.get_size()
    cr = self.cr

    cr.set_source_rgb(*self.cFill)
    cr.rectangle(0, 0, width, height)
    cr.fill()
    
    #figure out the scale mapping between values and pixels:
    maxYVal = self.maxVal
    maxValueText, maxValueUnits = Format.bytes_per_second(maxYVal).split(" ")
    x_bearing, y_bearing, w, h = cr.text_extents(maxValueText)[:4]
    xStart = w + self.PADDING_LEFT + self.PADDING_AXIS
    xEnd = width - self.PADDING_RIGHT 
    xStepSize = float(xEnd - xStart) / float(self.NUM_VALUES)
    x_bearing, y_bearing, w, h = cr.text_extents("100MB/s")[:4]
    bottomY = height - (self.PADDING_BOTTOM + h + self.PADDING_AXIS)
    yScale = float(bottomY - self.PADDING_TOP) / float(maxYVal)
    
    #shade enclosed rectangle white
    cr.set_source_rgb(self.cInnerShade[0], self.cInnerShade[1], self.cInnerShade[2])
    cr.rectangle(xStart, self.PADDING_TOP, width-self.PADDING_RIGHT-xStart, bottomY-self.PADDING_TOP)
    cr.fill()
    
    #labels
    cr.set_line_width(0.6)
    cr.set_font_size(self.FONT_SIZE)
    
    #vertical lines:
    numLines = self.NUM_VERT_LINES
    cr.set_source_rgb(self.cLines[0], self.cLines[1], self.cLines[2])
    if self.xMiddleTics:
      numLines = (numLines * (self.xMiddleTics+1))
    for i in range(0, numLines + 1):
      if self.xMiddleTics:
        if i % (1+self.xMiddleTics) == 0:
          cr.set_line_width(0.6)
        else:
          cr.set_line_width(0.2)
      s = (self.NUM_VALUES / numLines) * i
      #should be a dark color...
      x = xStart + int(xStepSize * s)
      cr.move_to(x, self.PADDING_TOP)
      cr.line_to(x, bottomY)
      cr.stroke()

    x_bearing, y_bearing, w, h = cr.text_extents("Time (1 second step)")[:4]
    yPos = bottomY + self.PADDING_AXIS + h - self.lineWidth
    #make left label:
    cr.move_to(xStart, yPos)
    cr.show_text("Time (1 second step)")
        
    #middle label:
    x_bearing, y_bearing, w, h = cr.text_extents("Grid: 10 seconds")[:4]
    cr.move_to((xStart+xEnd)/2 - w/2, yPos)
    cr.show_text("Grid: 10 seconds")
    
    #make right label:
    x_bearing, y_bearing, w, h = cr.text_extents("Now")[:4]
    cr.move_to(xEnd-w, yPos)
    cr.show_text("Now")

    #horizontal lines:
    cr.set_source_rgb(self.cLines[0], self.cLines[1], self.cLines[2])
    numLines = self.NUM_HORIZ_LINES
    if self.yMiddleTics:
      numLines = (numLines * (self.yMiddleTics+1))
    j = 0
    for i in range(0,maxYVal+1,maxYVal/numLines):
      if self.yMiddleTics:
        if j % (1+self.yMiddleTics) == 0:
          cr.set_line_width(0.6)
        else:
          cr.set_line_width(0.2)
        j += 1
      #should be a dark color...
      y = bottomY - int(yScale * i)
      cr.move_to(xEnd, y)
      cr.line_to(xStart, y)
      cr.stroke()
        
    #make top label:
    x_bearing, y_bearing, w, h = cr.text_extents("0")[:4]
    cr.move_to(self.PADDING_LEFT, self.PADDING_TOP+h)
    cr.show_text(maxValueText)
        
    #middle label:
    self.cr.rotate(-1*math.pi / 2.0)
    x_bearing, y_bearing, w, h = cr.text_extents(maxValueUnits)[:4]
    cr.move_to(-1 * height / 2.0 - w/2 + self.PADDING_TOP, self.PADDING_LEFT + h + 2)
    cr.show_text(maxValueUnits)
    self.cr.rotate(math.pi / 2.0)
    
    #make bottom label:
    x_bearing, y_bearing, w, h = cr.text_extents("0")[:4]
    cr.move_to(xStart-self.PADDING_AXIS-w, bottomY)
    cr.show_text("0")

    #draw the data lines on the graph:
    for sourceVals in (self.dataSource.bytesRead, self.dataSource.bytesWritten):
      # Set properties for the line (different colors for read and written)
      if sourceVals == self.dataSource.bytesWritten:
        cr.set_source_rgb(self.cWritten[0], self.cWritten[1], self.cWritten[2])
      else:
        cr.set_source_rgb(self.cRead[0], self.cRead[1], self.cRead[2])
      cr.set_line_width(self.lineWidth)
      #for every bw value,
      vals = sourceVals[len(sourceVals)-self.NUM_VALUES:]
      for i in range(0, len(vals)-1):
        #draw a line segment:
        startX = xStart + int(xStepSize * i)
        endX = xStart + int(xStepSize * (i+1))
        y1 = bottomY - (vals[i] * yScale)
        y2 = bottomY - (vals[i+1] * yScale)
        cr.move_to(startX, y1)
        cr.line_to(endX, y2)
      #Apply the ink
      cr.stroke()
      #update the maximum y value and scale for next time:
      newMax = 0
      for v in vals:
        if v > newMax:
          newMax = v
      #double the scale until we contain the max value:
      while newMax > self.maxVal:
        self.maxVal *= 2
      else:
        if newMax < self.maxVal / 2:
          self.scale_too_big += 1
        else:
          self.scale_too_big = 0
      #if the scale has been too big for more than 5 ticks, make it smaller
      if self.scale_too_big > 5:
        #dont go below the original axis value:
        if self.maxVal > 32 * 1024:
          self.maxVal /= 2
示例#8
0
 def start(self):
   self.check_for_updates()
   Scheduler.schedule_repeat(60 * 60 * 12, self.check_for_updates)
示例#9
0
      if controller: 
        controller.prompt_about_port(portNum, successFunc)
      else:
        log_msg("no gui controller yet to prompt_about_port", 2)
      return
  successFunc()
  
def add_updater(obj):
  def update():
    if ProgramState.DO_UPDATES:
      try:
        obj.on_update()
      except Exception, error:
        log_ex(error, "During update for %s" % (obj))
    return True
  Scheduler.schedule_repeat(Globals.INTERVAL_BETWEEN_UPDATES, update)
  
def get_image_file(imageName):
  """Given the name of an image, return the filename for the image data"""
  return os.path.join(Globals.DATA_DIR, unicode(imageName))
  
def create_error_archive(description):
  logs = ["main.out", "errors.out", "stderr.out", "tor.out", "tor_conn.out", "tor_conn.out.old", "log.out.old"]
  zipFile = zipfile.ZipFile(Globals.BUG_REPORT_NAME, "w")
  MAX_SIZE = 2 * 1024L * 1024L
  for log in logs:
    #write the file log with name log
    logName = os.path.join(Globals.LOG_FOLDER, log)
    if Files.file_exists(logName):
      fileSize = os.path.getsize(logName)
      if fileSize > MAX_SIZE:
示例#10
0
            else:
                log_msg("no gui controller yet to prompt_about_port", 2)
            return
    successFunc()


def add_updater(obj):
    def update():
        if ProgramState.DO_UPDATES:
            try:
                obj.on_update()
            except Exception, error:
                log_ex(error, "During update for %s" % (obj))
        return True

    Scheduler.schedule_repeat(Globals.INTERVAL_BETWEEN_UPDATES, update)


def get_image_file(imageName):
    """Given the name of an image, return the filename for the image data"""
    return os.path.join(Globals.DATA_DIR, unicode(imageName))


def create_error_archive(description):
    logs = [
        "main.out", "errors.out", "stderr.out", "tor.out", "tor_conn.out",
        "tor_conn.out.old", "log.out.old"
    ]
    zipFile = zipfile.ZipFile(Globals.BUG_REPORT_NAME, "w")
    MAX_SIZE = 2 * 1024L * 1024L
    for log in logs:
示例#11
0
    def __init__(self, config, Output, isAnonymous):
        try:
            self.config = config
            self.Output = Output

            self.torrent_dir = config['torrent_dir']
            self.torrent_cache = {}
            self.file_cache = {}
            self.blocked_files = {}
            self.scan_period = config['parse_dir_interval']
            self.stats_period = config['display_interval']

            self.torrent_list = []
            self.downloads = {}
            self.counter = 0
            self.doneflag = Event()

            self.hashcheck_queue = []
            self.hashcheck_current = None

            self.rawserver = JashRawServer()
            upnp_type = UPnP_test(config['upnp_nat_access'])
            self.listen_port = None
            while True:
                try:
                    self.listen_port = self.rawserver.find_and_bind(
                        config['minport'],
                        config['maxport'],
                        config['bind'],
                        ipv6_socket_style=config['ipv6_binds_v4'],
                        upnp=upnp_type,
                        randomizer=config['random_port'])
                    break
                except socketerror, e:
                    if upnp_type and e == UPnP_ERROR:
                        log_msg('WARNING: COULD NOT FORWARD VIA UPnP', 0)
                        upnp_type = 0
                        continue
                    self.failed("Couldn't listen - " + str(e))
                    return

            self.dht = None
            if isAnonymous:
                self.dht = dht.Proxy.DHTProxy(
                    BitTorrent.BitTorrentClient.get())
            else:
                if self.listen_port:
                    self.dht = dht.Node.LocalDHTNode(self.listen_port,
                                                     config['dht_file_name'])
            self.ratelimiter = RateLimiter(self.rawserver.add_task,
                                           config['upload_unit_size'])
            self.ratelimiter.set_upload_rate(config['max_upload_rate'])

            self.handler = MultiHandler(self.rawserver, self.doneflag, config)
            seed(createPeerID())
            #self.rawserver.add_task(self.scan, 0)
            if self.scan_period:
                self.scan()
                self.scanEvent = Scheduler.schedule_repeat(
                    self.scan_period, self.scan)
            else:
                self.scanEvent = None
示例#12
0
  def icon_menu_cb(self, status_icon, button, activate_time):
    """creates a drop down menu on the system tray icon when right clicked hopefully
    pay attention: both the popup menu and the menu list are passed to the trigger,
    which adds to both with new menuitems"""
    if self.popupMenu:
      self.popupMenu.destroy()
    
    self.popupMenu = gtk.Menu()
    self.allMenus = []
    #note, popupMenu and menus are changed externally....
    self._trigger_event("popup", self.popupMenu, self.allMenus)
      
    self.popupMenu.show()

    self.popupMenu.popup(None, None, None, button, activate_time)
      
#    self.popupMenu.connect("selection-done", self._recursive_menu_activate)

    def on_click(menu, event, popupMenu):
      if popupMenu != self.popupMenu:
        return
      log_msg("clicked %s %s" % (event.x, event.y), 4)
      if self.bestWidget:
        self.bestWidget.emit("activate")
      else:
        children = menu.get_children()
        if len(children) > 0:
          children[0].emit("activate")
      self._hide_popup_menu()
      return True
#    def debugprint(widget, eventName):
#      log_msg(eventName)
    for menuItem in self.popupMenu.get_children():
#      for eventName in ("activate", "activate-item"):
#        menuItem.connect(eventName, debugprint, eventName)
      submenu = menuItem.get_submenu()
      if submenu:
        self.popupMenu.window.set_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.ENTER_NOTIFY_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.EXPOSURE_MASK | gtk.gdk.STRUCTURE_MASK)
        submenu.connect('button_press_event', on_click, self.popupMenu)
#        for eventName in ("activate-current", "selection-done"):
#          submenu.connect(eventName, debugprint, eventName)
#    self.popupMenu.window.set_events(gtk.gdk.BUTTON_PRESS_MASK)
#    for eventName in ("activate-current", "selection-done"):
#      self.popupMenu.connect(eventName, debugprint, "parent"+eventName)
#    self.popupMenu.connect('button_press_event', on_click)

    self.bestWidget = None

    self.isHoveringOverMenu = False
    self.lastHoveredOverMenu = time.time()
    
#    self.popupMenu.window.raise_()
#    self.popupMenu.window.set_accept_focus(True)
##    self.popupMenu.window.focus()
#    self.popupMenu.window.set_modal_hint(True)

    #need to kill the popup when the mouse leaves... menus was populated in the triggered events
    self.allMenus.append(self.popupMenu)
    for menu in self.allMenus:
      menu.connect("enter_notify_event", self._on_hover_over_menu)
      menu.connect("leave_notify_event", self._on_leave_menu)
      if menu != self.popupMenu:
        for child in menu.get_children():
          child.connect("enter_notify_event", self._on_hover_over_widget)
          child.connect("leave_notify_event", self._on_leave_widget)
    
    Scheduler.schedule_repeat(0.1, self._fade_out_window)
示例#13
0
 def connectionMade(self):
   self.bytesLeft = 2 * 1024 * 1024
   self.transport.write(struct.pack("!I", self.bytesLeft))
   self.sendEvent = Scheduler.schedule_repeat(0.1, self.send_more, 1024 * 10)
示例#14
0
                    if acoin.is_fresh(self.currentACoinInterval):
                        addFunc(acoin)
                    else:
                        log_msg("Dropped an expired acoin from %s interval because we are at %s." % \
                                (acoin.interval,self.currentACoinInterval), 1)
                    f.close()

            assert not self.ACoins, "must not load coins more than once?"
            read(self.ACOIN_FILE_NAME, self.add_acoin)
            assert not self.depositingACoins, "cannot deposit coins while loading?"
            read(self.DEPOSITED_FILE_NAME, self.depositingACoins.append)
        except Exception, e:
            log_ex(e, "Failed to load coins from disk")
        #schedule the event to save the coins, now that they are loaded
        #TODO:  make this save way less often, this is just for debugging
        self.updateEvent = Scheduler.schedule_repeat(10, self.update_coins)

    def save_coins(self):
        """This function is called periodically.  It checks if any coins have been
    added or removed from our collections, and if so, stores them back to disk."""
        #if there have been any changes to our coins recently:
        if self.coinsChanged:
            #TODO:  properly deal with various filesystem errors--permissions, etc  :-/
            try:

                def write(unicodeFileName, coins):
                    fileName = System.encode_for_filesystem(unicodeFileName)
                    #do not overwrite existing until we're sure the whole file has been output
                    newFileName = fileName + ".new"
                    f = open(newFileName, "wb")
                    msg = ""