Example #1
0
 def test_communicate_with_igd_succeed_despite_single_failure(
         self, mock_orchestrate, mock_get_local_ips):
     mock_get_local_ips.return_value = ['192.168.0.12']
     mock_orchestrate.side_effect = [upnp.UpnpError, None]
     upnp._communicate_with_igd(retries=2)
     assert mock_get_local_ips.called
     assert mock_orchestrate.called
Example #2
0
    def test_perform_m_search_socket_error(self, mock_socket):
        mock_socket.recv.side_effect = socket.error('Timeout error')

        with mock.patch('util.UpnpPunch.socket.socket',
                        return_value=mock_socket):
            with pytest.raises(upnp.UpnpError):
                upnp.perform_m_search('127.0.0.1')
Example #3
0
 def test_create_close_message_parsable(self):
     from xml.parsers.expat import ExpatError
     msg, _ = upnp._create_close_message('127.0.0.1', 8888)
     try:
         upnp.parseString(msg)
     except ExpatError as e:
         pytest.fail('Incorrect XML message: {}'.format(e))
Example #4
0
 def test_create_close_message_parsable(self):
     from xml.parsers.expat import ExpatError
     msg, _ = upnp._create_close_message('127.0.0.1', 8888)
     try:
         upnp.parseString(msg)
     except ExpatError as e:
         pytest.fail('Incorrect XML message: {}'.format(e))
Example #5
0
    def test_send_requests_success(self):
        with mock.patch(
                'util.UpnpPunch._send_soap_request') as mock_send_request:
            mock_send_request.return_value = mock.MagicMock(status=200)
            upnp._send_requests(['msg'], None, None, None)

        assert mock_send_request.called
Example #6
0
    def test_perform_m_search_socket_error(self, mock_socket):
        mock_socket.recv.side_effect = socket.error('Timeout error')

        with mock.patch('util.UpnpPunch.socket.socket',
                        return_value=mock_socket):
            with pytest.raises(upnp.UpnpError):
                upnp.perform_m_search('127.0.0.1')
Example #7
0
 def stop(self):
     if self.running and self.upnp_port_opened:
         try:
             UpnpPunch.ask_to_close_port(self.port, protos=["TCP"])
             # self.log.info('Closed port via upnp.')
         except (UpnpPunch.UpnpError, UpnpPunch.IGDError), err:
             pass
Example #8
0
    def openport(self, port=None, check=True):
        if not port:
            port = self.port
        if self.port_opened:
            return True  # Port already opened
        if check:  # Check first if its already opened
            time.sleep(1)  # Wait for port open
            if self.testOpenport(port, use_alternative=False)["result"] is True:
                return True  # Port already opened

        if config.tor == "always":  # Port opening won't work in Tor mode
            return False

        self.log.info("Trying to open port using UpnpPunch...")
        try:
            UpnpPunch.ask_to_open_port(self.port, 'ZeroNet', retries=3, protos=["TCP"])
        except (UpnpPunch.UpnpError, UpnpPunch.IGDError, socket.error) as err:
            self.log.error("UpnpPunch run error: %s" %
                           Debug.formatException(err))
            return False

        if self.testOpenport(port)["result"] is True:
            self.upnp_port_opened = True
            return True

        self.log.info("Upnp mapping failed :( Please forward port %s on your router to your ipaddress" % port)
        return False
Example #9
0
    def test_send_requests_success(self):
        with mock.patch(
                'util.UpnpPunch._send_soap_request') as mock_send_request:
            mock_send_request.return_value = mock.MagicMock(status=200)
            upnp._send_requests(['msg'], None, None, None)

        assert mock_send_request.called
Example #10
0
    def openport(self, port=None, check=True):
        if not port:
            port = self.port
        if self.port_opened:
            return True  # Port already opened
        if check:  # Check first if its already opened
            time.sleep(1)  # Wait for port open
            if self.testOpenport(port,
                                 use_alternative=False)["result"] is True:
                return True  # Port already opened

        if config.tor == "always":  # Port opening won't work in Tor mode
            return False

        self.log.info("Trying to open port using UpnpPunch...")
        try:
            UpnpPunch.ask_to_open_port(self.port,
                                       'ZeroNet',
                                       retries=3,
                                       protos=["TCP"])
        except (UpnpPunch.UpnpError, UpnpPunch.IGDError, socket.error) as err:
            self.log.error("UpnpPunch run error: %s" %
                           Debug.formatException(err))
            return False

        if self.testOpenport(port)["result"] is True:
            self.upnp_port_opened = True
            return True

        self.log.info(
            "Upnp mapping failed :( Please forward port %s on your router to your ipaddress"
            % port)
        return False
Example #11
0
 def test_communicate_with_igd_succeed_despite_single_failure(
         self, mock_orchestrate, mock_get_local_ips):
     mock_get_local_ips.return_value = ['192.168.0.12']
     mock_orchestrate.side_effect = [upnp.UpnpError, None]
     upnp._communicate_with_igd(retries=2)
     assert mock_get_local_ips.called
     assert mock_orchestrate.called
Example #12
0
    def test_ask_to_open_port_failure(self, mock_send_requests,
                                      mock_collect_idg, mock_local_ips):
        mock_local_ips.return_value = ['192.168.0.12']
        mock_collect_idg.return_value = {'upnp_schema': 'schema-yo'}
        mock_send_requests.side_effect = upnp.UpnpError()

        with pytest.raises(upnp.UpnpError):
            upnp.ask_to_open_port()
Example #13
0
 def stop(self):
     if self.running and self.upnp_port_opened:
         self.log.debug('Closing port %d' % self.port)
         try:
             UpnpPunch.ask_to_close_port(self.port, protos=["TCP"])
             self.log.info('Closed port via upnp.')
         except (UpnpPunch.UpnpError, UpnpPunch.IGDError), err:
             self.log.info("Failed at attempt to use upnp to close port: %s" % err)
Example #14
0
 def stop(self):
     if self.running and self.upnp_port_opened:
         self.log.debug('Closing port %d' % self.port)
         try:
             UpnpPunch.ask_to_close_port(self.port, protos=["TCP"])
             self.log.info('Closed port via upnp.')
         except (UpnpPunch.UpnpError, UpnpPunch.IGDError), err:
             self.log.info("Failed at attempt to use upnp to close port: %s" % err)
Example #15
0
    def test_send_requests_failed(self):
        with mock.patch(
                'util.UpnpPunch._send_soap_request') as mock_send_request:
            mock_send_request.return_value = mock.MagicMock(status=500)
            with pytest.raises(upnp.UpnpError):
                upnp._send_requests(['msg'], None, None, None)

        assert mock_send_request.called
Example #16
0
    def test_ask_to_open_port_failure(self, mock_send_requests,
                                      mock_collect_idg, mock_local_ips):
        mock_local_ips.return_value = ['192.168.0.12']
        mock_collect_idg.return_value = {'upnp_schema': 'schema-yo'}
        mock_send_requests.side_effect = upnp.UpnpError()

        with pytest.raises(upnp.UpnpError):
            upnp.ask_to_open_port()
Example #17
0
 def test_communicate_with_igd_total_failure(self, mock_orchestrate,
                                             mock_get_local_ips):
     mock_get_local_ips.return_value = ['192.168.0.12']
     mock_orchestrate.side_effect = [upnp.UpnpError, upnp.IGDError]
     with pytest.raises(upnp.UpnpError):
         upnp._communicate_with_igd(retries=2)
     assert mock_get_local_ips.called
     assert mock_orchestrate.called
Example #18
0
    def test_send_requests_failed(self):
        with mock.patch(
                'util.UpnpPunch._send_soap_request') as mock_send_request:
            mock_send_request.return_value = mock.MagicMock(status=500)
            with pytest.raises(upnp.UpnpError):
                upnp._send_requests(['msg'], None, None, None)

        assert mock_send_request.called
Example #19
0
 def test_communicate_with_igd_total_failure(self, mock_orchestrate,
                                             mock_get_local_ips):
     mock_get_local_ips.return_value = ['192.168.0.12']
     mock_orchestrate.side_effect = [upnp.UpnpError, upnp.IGDError]
     with pytest.raises(upnp.UpnpError):
         upnp._communicate_with_igd(retries=2)
     assert mock_get_local_ips.called
     assert mock_orchestrate.called
Example #20
0
 def test_parse_for_errors_error(self, httplib_response):
     soap_error = ('<document>'
                   '<errorCode>500</errorCode>'
                   '<errorDescription>Bad request</errorDescription>'
                   '</document>')
     rsp = httplib_response(status=500, body=soap_error)
     with pytest.raises(upnp.IGDError) as exc:
         upnp._parse_for_errors(rsp)
     assert 'SOAP request error' in exc.value.message
Example #21
0
 def test_parse_for_errors_error(self, httplib_response):
     soap_error = ('<document>'
                   '<errorCode>500</errorCode>'
                   '<errorDescription>Bad request</errorDescription>'
                   '</document>')
     rsp = httplib_response(status=500, body=soap_error)
     with pytest.raises(upnp.IGDError) as exc:
         upnp._parse_for_errors(rsp)
     assert 'SOAP request error' in exc.value.message
Example #22
0
    def test_orchestrate_soap_request_without_desc(self, mock_send_requests,
                                                   mock_collect_idg):
        soap_mock = mock.MagicMock()
        args = ['127.0.0.1', 31337, soap_mock, {'upnp_schema': 'schema-yo'}]
        mock_collect_idg.return_value = args[-1]

        upnp._orchestrate_soap_request(*args[:-1])

        assert mock_collect_idg.called
        soap_mock.assert_called_with(*args[:2] + [None, 'UDP', 'schema-yo'])
        assert mock_send_requests.called
Example #23
0
    def test_orchestrate_soap_request_without_desc(self, mock_send_requests,
                                                   mock_collect_idg):
        soap_mock = mock.MagicMock()
        args = ['127.0.0.1', 31337, soap_mock, {'upnp_schema': 'schema-yo'}]
        mock_collect_idg.return_value = args[-1]

        upnp._orchestrate_soap_request(*args[:-1])

        assert mock_collect_idg.called
        soap_mock.assert_called_with(*args[:2] + [None, 'UDP', 'schema-yo'])
        assert mock_send_requests.called
Example #24
0
    def portOpen(self, port):
        self.log.info("Trying to open port using UpnpPunch...")

        try:
            UpnpPunch.ask_to_open_port(port, 'Ainkuraddo', retries=3, protos=["TCP"])
            self.upnp_port_opened = True
        except Exception as err:
            self.log.warning("UpnpPunch run error: %s" % Debug.formatException(err))
            return False

        return True
Example #25
0
 def test_parse_igd_profile_service_type(self, igd_profile):
     control_path, upnp_schema = upnp._parse_igd_profile(igd_profile)
     assert control_path == '/upnp/control/wanpppcpppoa'
     assert upnp_schema in (
         'WANPPPConnection',
         'WANIPConnection',
     )
Example #26
0
 def test_retrieve_location_from_ssdp(self, url_obj):
     ctrl_location = url_obj.geturl()
     parsed_location = urlparse(ctrl_location)
     rsp = ('auth: gibberish\r\nlocation: {0}\r\n'
            'Content-Type: text/html\r\n\r\n').format(ctrl_location)
     result = upnp._retrieve_location_from_ssdp(rsp)
     assert result == parsed_location
Example #27
0
 def test_retrieve_location_from_ssdp(self, url_obj):
     ctrl_location = url_obj.geturl()
     parsed_location = urlparse(ctrl_location)
     rsp = ('auth: gibberish\r\nlocation: {0}\r\n'
            'Content-Type: text/html\r\n\r\n').format(ctrl_location)
     result = upnp._retrieve_location_from_ssdp(rsp)
     assert result == parsed_location
Example #28
0
 def test_create_close_message_contains_right_stuff(self):
     settings = {'protocol': 'test proto', 'upnp_schema': 'test schema'}
     msg, fn_name = upnp._create_close_message('127.0.0.1', 8888,
                                               **settings)
     assert fn_name == 'DeletePortMapping'
     assert '8888' in msg
     assert settings['protocol'] in msg
     assert settings['upnp_schema'] in msg
Example #29
0
 def test_create_close_message_contains_right_stuff(self):
     settings = {'protocol': 'test proto',
                 'upnp_schema': 'test schema'}
     msg, fn_name = upnp._create_close_message('127.0.0.1', 8888, **
                                               settings)
     assert fn_name == 'DeletePortMapping'
     assert '8888' in msg
     assert settings['protocol'] in msg
     assert settings['upnp_schema'] in msg
Example #30
0
    def test_perform_m_search(self, mock_socket):
        local_ip = '127.0.0.1'

        with mock.patch('util.UpnpPunch.socket.socket',
                        return_value=mock_socket):
            result = upnp.perform_m_search(local_ip)
            assert result == 'Hello'
            assert local_ip == mock_socket.bind.call_args_list[0][0][0][0]
            assert ('239.255.255.250',
                    1900) == mock_socket.sendto.call_args_list[0][0][1]
Example #31
0
    def test_perform_m_search(self, mock_socket):
        local_ip = '127.0.0.1'

        with mock.patch('util.UpnpPunch.socket.socket',
                        return_value=mock_socket):
            result = upnp.perform_m_search(local_ip)
            assert result == 'Hello'
            assert local_ip == mock_socket.bind.call_args_list[0][0][0][0]
            assert ('239.255.255.250',
                    1900) == mock_socket.sendto.call_args_list[0][0][1]
Example #32
0
 def test_create_open_message_contains_right_stuff(self):
     settings = {'description': 'test desc',
                 'protocol': 'test proto',
                 'upnp_schema': 'test schema'}
     msg, fn_name = upnp._create_open_message('127.0.0.1', 8888, **settings)
     assert fn_name == 'AddPortMapping'
     assert '127.0.0.1' in msg
     assert '8888' in msg
     assert settings['description'] in msg
     assert settings['protocol'] in msg
     assert settings['upnp_schema'] in msg
Example #33
0
    def portOpen(self, port):
        self.log.info("Trying to open port using UpnpPunch...")

        try:
            UpnpPunch.ask_to_open_port(port,
                                       'ZeroNet',
                                       retries=3,
                                       protos=["TCP"])
            self.upnp_port_opened = True
        except Exception as err:
            self.log.warning("UpnpPunch run error: %s" %
                             Debug.formatException(err))
            return False

        if self.portCheck(port)["opened"]:
            return True
        else:
            self.log.info(
                "Upnp mapping failed, please forward port %s on your router to your ipaddress"
                % port)
            return False
Example #34
0
 def test_create_open_message_contains_right_stuff(self):
     settings = {
         'description': 'test desc',
         'protocol': 'test proto',
         'upnp_schema': 'test schema'
     }
     msg, fn_name = upnp._create_open_message('127.0.0.1', 8888, **settings)
     assert fn_name == 'AddPortMapping'
     assert '127.0.0.1' in msg
     assert '8888' in msg
     assert settings['description'] in msg
     assert settings['protocol'] in msg
     assert settings['upnp_schema'] in msg
Example #35
0
	def openport(self, port=None, check=True):
		if not port: port = self.port
		if self.port_opened: return True # Port already opened
		if check: # Check first if its already opened
			if self.testOpenport(port)["result"] == True:
				return True # Port already opened

		self.log.info("Trying to open port using UpnpPunch...")
		try:
			upnp_punch = UpnpPunch.open_port(self.port, 'ZeroNet')
			upnp_punch = True
		except Exception, err:
			self.log.error("UpnpPunch run error: %s" % Debug.formatException(err))
			upnp_punch = False
Example #36
0
    def test_ask_to_open_port_success(self, mock_send_requests,
                                      mock_collect_idg, mock_local_ips):
        mock_collect_idg.return_value = {'upnp_schema': 'schema-yo'}
        mock_local_ips.return_value = ['192.168.0.12']

        result = upnp.ask_to_open_port(retries=5)

        soap_msg = mock_send_requests.call_args[0][0][0][0]

        assert result is None

        assert mock_collect_idg.called
        assert '192.168.0.12' in soap_msg
        assert '15441' in soap_msg
        assert 'schema-yo' in soap_msg
Example #37
0
    def test_ask_to_open_port_success(self, mock_send_requests,
                                      mock_collect_idg, mock_local_ips):
        mock_collect_idg.return_value = {'upnp_schema': 'schema-yo'}
        mock_local_ips.return_value = ['192.168.0.12']

        result = upnp.ask_to_open_port(retries=5)

        soap_msg = mock_send_requests.call_args[0][0][0][0]

        assert result is None

        assert mock_collect_idg.called
        assert '192.168.0.12' in soap_msg
        assert '15441' in soap_msg
        assert 'schema-yo' in soap_msg
Example #38
0
    def openport(self, port=None, check=True):
        if not port:
            port = self.port
        if self.port_opened:
            return True  # Port already opened
        if check:  # Check first if its already opened
            time.sleep(1)  # Wait for port open
            if self.testOpenport(port, use_alternative=False)["result"] is True:
                return True  # Port already opened

        if config.tor == "always":  # Port opening won't work in Tor mode
            return False

        self.log.info("Trying to open port using UpnpPunch...")
        try:
            upnp_punch = UpnpPunch.open_port(self.port, 'Phantom')
            upnp_punch = True
        except Exception, err:
            upnp_punch = False
Example #39
0
    def openport(self, port=None, check=True):
        if not port:
            port = self.port
        if self.port_opened:
            return True  # Port already opened
        if check:  # Check first if its already opened
            time.sleep(1)  # Wait for port open
            if self.testOpenport(port, use_alternative=False)["result"] is True:
                return True  # Port already opened

        if config.tor == "always":  # Port opening won't work in Tor mode
            return False

        self.log.info("Trying to open port using UpnpPunch...")
        try:
            upnp_punch = UpnpPunch.open_port(self.port, 'ZeroNet')
            upnp_punch = True
        except Exception, err:
            self.log.error("UpnpPunch run error: %s" % Debug.formatException(err))
            upnp_punch = False
Example #40
0
 def getMyIps(self):
     return UpnpPunch._get_local_ips()
Example #41
0
 def getMyIps(self):
     return UpnpPunch._get_local_ips()
Example #42
0
 def test_parse_for_errors_bad_rsp(self, httplib_response):
     rsp = httplib_response(status=500)
     with pytest.raises(upnp.IGDError) as exc:
         upnp._parse_for_errors(rsp)
     assert 'Unable to parse' in exc.value.message
Example #43
0
 def test_parse_for_errors_bad_rsp(self, httplib_response):
     rsp = httplib_response(status=500)
     with pytest.raises(upnp.IGDError) as exc:
         upnp._parse_for_errors(rsp)
     assert 'Unable to parse' in exc.value.message
Example #44
0
 def test_parse_for_errors_good_rsp(self, httplib_response):
     rsp = httplib_response(status=200)
     assert rsp == upnp._parse_for_errors(rsp)
Example #45
0
 def test_retrieve_igd_profile_timeout(self, url_obj):
     with mock.patch('urllib2.urlopen') as mock_urlopen:
         mock_urlopen.side_effect = socket.error('Timeout error')
         with pytest.raises(upnp.IGDError):
             upnp._retrieve_igd_profile(url_obj)
Example #46
0
 def test_communicate_with_igd_success(self, mock_orchestrate,
                                       mock_get_local_ips):
     mock_get_local_ips.return_value = ['192.168.0.12']
     upnp._communicate_with_igd()
     assert mock_get_local_ips.called
     assert mock_orchestrate.called
Example #47
0
 def test_communicate_with_igd_success(self, mock_orchestrate,
                                       mock_get_local_ips):
     mock_get_local_ips.return_value = ['192.168.0.12']
     upnp._communicate_with_igd()
     assert mock_get_local_ips.called
     assert mock_orchestrate.called
Example #48
0
 def portClose(self, port):
     return UpnpPunch.ask_to_close_port(port, protos=["TCP"])
Example #49
0
 def test_retrieve_igd_profile(self, url_obj):
     with mock.patch('urllib2.urlopen') as mock_urlopen:
         upnp._retrieve_igd_profile(url_obj)
         mock_urlopen.assert_called_with(url_obj.geturl(), timeout=5)
Example #50
0
 def test_parse_for_errors_good_rsp(self, httplib_response):
     rsp = httplib_response(status=200)
     assert rsp == upnp._parse_for_errors(rsp)
Example #51
0
 def test_retrieve_location_from_ssdp_no_header(self):
     rsp = 'auth: gibberish\r\nContent-Type: application/json\r\n\r\n'
     with pytest.raises(upnp.IGDError):
         upnp._retrieve_location_from_ssdp(rsp)
Example #52
0
 def test_retrieve_location_from_ssdp_no_header(self):
     rsp = 'auth: gibberish\r\nContent-Type: application/json\r\n\r\n'
     with pytest.raises(upnp.IGDError):
         upnp._retrieve_location_from_ssdp(rsp)
Example #53
0
 def test_retrieve_igd_profile(self, url_obj):
     with mock.patch('urllib2.urlopen') as mock_urlopen:
         upnp._retrieve_igd_profile(url_obj)
         mock_urlopen.assert_called_with(url_obj.geturl(), timeout=5)
Example #54
0
 def test_parse_igd_profile_no_schema(self, igd_profile):
     igd_profile = igd_profile.replace('Connection', 'nope')
     with pytest.raises(upnp.IGDError):
         control_path, upnp_schema = upnp._parse_igd_profile(igd_profile)
Example #55
0
 def test_parse_igd_profile_no_ctrlurl(self, igd_profile):
     igd_profile = igd_profile.replace('controlURL', 'nope')
     with pytest.raises(upnp.IGDError):
         control_path, upnp_schema = upnp._parse_igd_profile(igd_profile)
Example #56
0
 def test_retrieve_igd_profile_timeout(self, url_obj):
     with mock.patch('urllib2.urlopen') as mock_urlopen:
         mock_urlopen.side_effect = socket.error('Timeout error')
         with pytest.raises(upnp.IGDError):
             upnp._retrieve_igd_profile(url_obj)
Example #57
0
 def test_parse_igd_profile_service_type(self, igd_profile):
     control_path, upnp_schema = upnp._parse_igd_profile(igd_profile)
     assert control_path == '/upnp/control/wanpppcpppoa'
     assert upnp_schema in ('WANPPPConnection', 'WANIPConnection',)