Example #1
0
func TestEnsureRegistered(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	u := getUtil()
	// Test with no existing record
	name, ip := "cfl-test-entry", "127.0.0.1"
	rec, proxying, err := u.EnsureRegistered(name, ip, nil)
	if assert.NoError(t, err, "Should be able to register with no record") {
		assert.NotNil(t, rec, "A new record should have been returned")
		assert.True(t, proxying, "Proxying (orange cloud) should be on")
	}

	// Test with existing record, but not passing it in
	rec, proxying, err = u.EnsureRegistered(name, ip, nil)
	if assert.NoError(t, err, "Should be able to register with unspecified existing record") {
		assert.NotNil(t, rec, "Existing record should have been returned")
		assert.True(t, proxying, "Proxying (orange cloud) should be on")

		// Test with existing record, passing it in
		rec, proxying, err = u.EnsureRegistered(name, ip, rec)
		if assert.NoError(t, err, "Should be able to register with specified existing record") {
			assert.NotNil(t, rec, "Existing record should have been returned")
			assert.True(t, proxying, "Proxying (orange cloud) should be on")
		}
	}

	if rec != nil {
		err := u.DestroyRecord(rec)
		assert.NoError(t, err, "Should be able to destroy record")
	}

	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Example #2
0
func doTestTLS(buffered bool, t *testing.T) {
	startServers(t, false)

	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get fdcount: %v", err)
	}

	conn, err := prepareConn(httpsAddr, buffered, false, t, nil)
	if err != nil {
		t.Fatalf("Unable to prepareConn: %s", err)
	}

	tlsConn := tls.Client(conn, &tls.Config{
		ServerName: "localhost",
		RootCAs:    cert.PoolContainingCert(),
	})
	defer func() {
		err := conn.Close()
		assert.Nil(t, err, "Closing conn should succeed")
		if !assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed") {
			DumpConnTrace()
		}
	}()

	err = tlsConn.Handshake()
	if err != nil {
		t.Fatalf("Unable to handshake: %s", err)
	}

	doRequests(tlsConn, t)

	assert.True(t, destsSent[httpsAddr], "https address wasn't recorded as sent destination")
	assert.True(t, destsReceived[httpsAddr], "https address wasn't recorded as received destination")
}
Example #3
0
func TestTCP(t *testing.T) {
	// Lower maxAssertAttempts to keep this test from running too long
	maxAssertAttempts = 2

	l0, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := l0.Close(); err != nil {
			t.Fatalf("Unable to close listener: %v", err)
		}
	}()

	start, fdc, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 1, start, "Starting count should have been 1")

	err = fdc.AssertDelta(0)
	if err != nil {
		t.Fatal(err)
	}
	assert.NoError(t, err, "Initial TCP count should be 0")

	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	_, middle, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.True(t, len(err.Error()) > 100)
	}
	err = fdc.AssertDelta(1)
	assert.NoError(t, err, "Ending TCP count should be 1")

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.Contains(t, err.Error(), "New")
		assert.True(t, len(err.Error()) > 100)
	}

	if err := l.Close(); err != nil {
		t.Fatalf("Unable to close listener: %v", err)
	}
	err = middle.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have -1")
		assert.Contains(t, err.Error(), "Removed")
		assert.True(t, len(err.Error()) > 100)
	}
}
Example #4
0
func doTestPlainText(buffered bool, useHostFn bool, t *testing.T) {
	var counter *fdcount.Counter
	var err error

	startServers(t, useHostFn)

	err = fdcount.WaitUntilNoneMatch("CLOSE_WAIT", 5*time.Second)
	if err != nil {
		t.Fatalf("Unable to wait until no more connections are in CLOSE_WAIT: %v", err)
	}

	_, counter, err = fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get fdcount: %v", err)
	}

	var reportedHost string
	var reportedHostMutex sync.Mutex
	onResponse := func(resp *http.Response) {
		reportedHostMutex.Lock()
		reportedHost = resp.Header.Get(X_ENPROXY_PROXY_HOST)
		reportedHostMutex.Unlock()
	}

	conn, err := prepareConn(httpAddr, buffered, false, t, onResponse)
	if err != nil {
		t.Fatalf("Unable to prepareConn: %s", err)
	}
	defer func() {
		err := conn.Close()
		assert.Nil(t, err, "Closing conn should succeed")
		if !assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed") {
			DumpConnTrace()
		}
	}()

	doRequests(conn, t)

	assert.Equal(t, 208, bytesReceived, "Wrong number of bytes received")
	assert.Equal(t, 284, bytesSent, "Wrong number of bytes sent")
	assert.True(t, destsSent[httpAddr], "http address wasn't recorded as sent destination")
	assert.True(t, destsReceived[httpAddr], "http address wasn't recorded as received destination")

	reportedHostMutex.Lock()
	rh := reportedHost
	reportedHostMutex.Unlock()
	assert.Equal(t, "localhost", rh, "Didn't get correct reported host")
}
Example #5
0
func TestConcurrent(t *testing.T) {
	v := NewValue()

	var sets int32 = 0

	go func() {
		var wg sync.WaitGroup
		wg.Add(1)
		// Do some concurrent setting to make sure that it works
		for i := 0; i < concurrency; i++ {
			go func() {
				// Wait for waitGroup so that all goroutines run at basically the same
				// time.
				wg.Wait()
				v.Set("hi")
				atomic.AddInt32(&sets, 1)
			}()
		}
		wg.Done()
	}()

	time.Sleep(50 * time.Millisecond)
	r, ok := v.Get(20 * time.Millisecond)
	assert.True(t, ok, "Get should have succeed")
	assert.Equal(t, "hi", r, "Wrong result")
	assert.Equal(t, concurrency, atomic.LoadInt32(&sets), "Wrong number of successful Sets")
}
Example #6
0
func TestCreateAndRefresh(t *testing.T) {
	if true {
		t.Log("We don't currently use peerscanner, so this test is disabled. To reenable, we'll need to delete test distributions to avoid hitting our limit")
		return
	}
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	// Deleting cloudfront distributions is actually quite an involved process.
	// Fortunately, distributions per se cost us nothing.  A separate service
	// will be implemented to delete test and otherwise unused distributions.
	name := uuid.NewV4().String()
	dist, err := CreateDistribution(cfr, name, name+"-grey.flashlightproxy.org", COMMENT)
	assert.NoError(t, err, "Should be able to create distribution")
	assert.Equal(t, "InProgress", dist.Status, "New distribution should have Status: \"InProgress\"")
	assert.Equal(t, dist.Comment, COMMENT, "New distribution should have the comment we've set for it")
	assert.Equal(t, name, dist.InstanceId, "New distribution should have the right InstanceId")
	assert.True(t, strings.HasSuffix(dist.Domain, ".cloudfront.net"), "Domain should be a .cloudfront.net subdomain, not '"+dist.Domain+"'")
	dist.Status = "modified to check it really gets overwritten"
	err = RefreshStatus(cfr, dist)
	assert.NoError(t, err, "Should be able to refresh status")
	// Just check that Status stays a valid one.  Checking that it eventually
	// gets refreshed to "Deployed" would take a few minutes, and thus is out
	// of the scope of this unit test.
	assert.Equal(t, "InProgress", dist.Status, "New distribution should have Status: \"InProgress\" even after refreshing right away")
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Example #7
0
func TestEquals(t *testing.T) {
	a := csFor(&Config{
		Cloud: []string{"A", "B", "C"},
		Delta: &Delta{
			Additions: []string{"D"},
			Deletions: []string{"C"},
		},
	})
	b := csFor(&Config{
		Cloud: []string{"A", "B"},
		Delta: &Delta{
			Additions: []string{"D"},
			Deletions: []string{"C"},
		},
	})
	c := csFor(&Config{
		Cloud: []string{"A", "B", "C"},
		Delta: &Delta{
			Additions: []string{"D", "E"},
			Deletions: []string{"C"},
		},
	})
	d := csFor(&Config{
		Cloud: []string{"A", "B", "C"},
		Delta: &Delta{
			Additions: []string{"D"},
			Deletions: []string{"C", "E"},
		},
	})

	assert.True(t, a.equals(a), "a should equal itself")
	assert.False(t, a.equals(b), "a should not equal b")
	assert.False(t, a.equals(c), "a should not equal c")
	assert.False(t, a.equals(d), "a should not equal d")
}
Example #8
0
func TestWaitUntilNoneMatchOK(t *testing.T) {
	conn, err := net.Dial("tcp", "www.google.com:80")
	if err != nil {
		t.Fatalf("Unable to dial google: %v", err)
	}
	defer func() {
		if err := conn.Close(); err != nil {
			fmt.Println("Unable to close connection: %v", err)
		}
	}()

	wait := 250 * time.Millisecond
	start := time.Now()
	go func() {
		time.Sleep(wait)
		if err := conn.Close(); err != nil {
			t.Fatalf("Unable to close connection: %v", err)
		}
	}()

	err = WaitUntilNoneMatch("TCP", wait*2)
	elapsed := time.Now().Sub(start)
	assert.NoError(t, err, "Waiting should have succeeded")
	assert.True(t, elapsed >= wait, "Should have waited a while")
}
Example #9
0
func TestWaitUntilNoneMatchTimeout(t *testing.T) {
	conn, err := net.Dial("tcp", "www.google.com:80")
	if err != nil {
		t.Fatalf("Unable to dial google: %v", err)
	}
	defer func() {
		if err := conn.Close(); err != nil {
			fmt.Printf("Unable to close connection: %v", err)
		}
	}()

	wait := 200 * time.Millisecond
	start := time.Now()
	go func() {
		time.Sleep(wait)
		if err := conn.Close(); err != nil {
			t.Fatalf("Unable to close connection: %v", err)
		}
	}()

	err = WaitUntilNoneMatch("TCP", wait/4)
	elapsed := time.Now().Sub(start)
	assert.Error(t, err, "Waiting should have failed")
	assert.True(t, elapsed < wait, "Should have waited less than time to close conn")
}
Example #10
0
func TestBadMethodToServer(t *testing.T) {
	l := startServer(t)
	resp, err := http.Get("http://" + l.Addr().String() + "/")
	assert.NoError(t, err, "Making a Get request to the server should not have errored")
	if err == nil {
		assert.True(t, resp.StatusCode == 405, "Response should have indicated a bad method")
	}
}
Example #11
0
func assertTimeoutError(t *testing.T, err error) {
	switch e := err.(type) {
	case net.Error:
		assert.True(t, e.Timeout(), "Error should be timeout")
	default:
		assert.Fail(t, "Error should be net.Error")
	}
}
Example #12
0
func doTestTimeout(t *testing.T, timeout time.Duration) {
	_, err := DialWithDialer(&net.Dialer{
		Timeout: timeout,
	}, "tcp", ADDR, false, nil)
	assert.Error(t, err, "There should have been a problem dialing", timeout)
	if err != nil {
		assert.True(t, err.(net.Error).Timeout(), "Dial error should be timeout", timeout)
	}
}
Example #13
0
// TestIntegration tests against existing domain-fronted servers running on
// CloudFlare.
func TestIntegration(t *testing.T) {
	dialedDomain := ""
	dialedAddr := ""
	actualResolutionTime := time.Duration(0)
	actualConnectTime := time.Duration(0)
	actualHandshakeTime := time.Duration(0)
	var statsMutex sync.Mutex

	statsFunc := func(success bool, domain, addr string, resolutionTime, connectTime, handshakeTime time.Duration) {
		if success {
			statsMutex.Lock()
			defer statsMutex.Unlock()
			dialedDomain = domain
			dialedAddr = addr
			actualResolutionTime = resolutionTime
			actualConnectTime = connectTime
			actualHandshakeTime = handshakeTime
		}
	}

	d := integrationDialer(t, statsFunc)
	defer func() {
		if err := d.Close(); err != nil {
			t.Fatalf("Unable to close dialer: %v", err)
		}
	}()

	hc := &http.Client{
		Transport: &http.Transport{
			Dial: d.Dial,
		},
	}

	resp, err := hc.Get("https://www.google.com/humans.txt")
	if err != nil {
		t.Fatalf("Unable to fetch from Google: %s", err)
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			t.Fatalf("Unable to close response body: %v", err)
		}
	}()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Unable to read response from Google: %s", err)
	}
	assert.Equal(t, expectedGoogleResponse, string(b), "Didn't get expected response from Google")

	statsMutex.Lock()
	defer statsMutex.Unlock()
	assert.True(t, dialedDomain == "100partnerprogramme.de" || dialedDomain == "10minutemail.com", "Dialed domain didn't match one of the masquerade domains", dialedDomain)
	assert.NotEqual(t, "", dialedAddr, "Should have received an addr")
	assert.NotEqual(t, time.Duration(0), actualResolutionTime, "Should have received a resolutionTime")
	assert.NotEqual(t, time.Duration(0), actualConnectTime, "Should have received a connectTime")
	assert.NotEqual(t, time.Duration(0), actualHandshakeTime, "Should have received a handshakeTime")
}
Example #14
0
func TestTimeout(t *testing.T) {
	text, timedOut, err := Do(10*time.Millisecond, func() (interface{}, error) {
		time.Sleep(11 * time.Millisecond)
		return expectedText, expectedErr
	})
	assert.True(t, timedOut, "Should have timed out")
	assert.NotNil(t, err, "There should be an error")
	assert.Nil(t, text, "Text should be nil")
	assert.Equal(t, timeoutErrorString, err.Error(), "Error should contain correct string")
}
Example #15
0
func TestTampering(t *testing.T) {
	defer stopMockServers()
	proxiedURL, _ := newMockServer(detourMsg)

	client := newClient(proxiedURL, 100*time.Millisecond)
	resp, err := client.Get("http://255.0.0.1") // it's reserved for future use so will always time out
	if assert.NoError(t, err, "should have no error when dial a timeout host") {
		time.Sleep(50 * time.Millisecond)
		assert.True(t, wlTemporarily("255.0.0.1:80"), "should be added to whitelist if dialing times out")
		assertContent(t, resp, detourMsg, "should detour if dialing times out")
	}

	client = newClient(proxiedURL, 100*time.Millisecond)
	resp, err = client.Get("http://127.0.0.1:4325") // hopefully this port didn't open, so connection will be refused
	if assert.NoError(t, err, "should have no error if connection is refused") {
		time.Sleep(60 * time.Millisecond)
		assert.True(t, wlTemporarily("127.0.0.1:4325"), "should be added to whitelist if connection is refused")
		assertContent(t, resp, detourMsg, "should detour if connection is refused")
	}
}
Example #16
0
func TestDeadlineBeforeTimeout(t *testing.T) {
	fdStart := countTCPFiles()
	conn, err := DialWithDialer(&net.Dialer{
		Timeout:  500 * time.Second,
		Deadline: time.Now().Add(5 * time.Microsecond),
	}, "tcp", ADDR, false, nil)
	assert.Error(t, err, "There should have been a problem dialing")
	if err != nil {
		assert.True(t, err.(net.Error).Timeout(), "Dial error should be timeout")
	}
	closeAndCountFDs(t, conn, err, fdStart)
}
Example #17
0
func TestNonIdempotentOp(t *testing.T) {
	defer stopMockServers()
	proxiedURL, _ := newMockServer(detourMsg)
	mockURL, mock := newMockServer("")
	u, _ := url.Parse(mockURL)
	mock.Timeout(200*time.Millisecond, directMsg)
	client := newClient(proxiedURL, 100*time.Millisecond)
	_, err := client.PostForm(mockURL, url.Values{"key": []string{"value"}})
	if assert.Error(t, err, "Non-idempotent method should not be detoured in same connection") {
		time.Sleep(50 * time.Millisecond)
		assert.True(t, wlTemporarily(u.Host), "but should be added to whitelist so will detour next time")
	}
}
Example #18
0
func TestBlockedImmediately(t *testing.T) {
	defer stopMockServers()
	proxiedURL, _ := newMockServer(detourMsg)
	TimeoutToDetour = 50 * time.Millisecond
	mockURL, mock := newMockServer(directMsg)

	client := &http.Client{Timeout: 50 * time.Millisecond}
	mock.Timeout(200*time.Millisecond, directMsg)
	resp, err := client.Get(mockURL)
	assert.Error(t, err, "direct access to a timeout url should fail")

	client = newClient(proxiedURL, 100*time.Millisecond)
	resp, err = client.Get("http://255.0.0.1") // it's reserved for future use so will always time out
	if assert.NoError(t, err, "should have no error if dialing times out") {
		assert.True(t, wlTemporarily("255.0.0.1:80"), "should be added to whitelist if dialing times out")
		assertContent(t, resp, detourMsg, "should detour if dialing times out")
	}

	client = newClient(proxiedURL, 100*time.Millisecond)
	resp, err = client.Get("http://127.0.0.1:4325") // hopefully this port didn't open, so connection will be refused
	if assert.NoError(t, err, "should have no error if connection is refused") {
		assert.True(t, wlTemporarily("127.0.0.1:4325"), "should be added to whitelist if connection is refused")
		assertContent(t, resp, detourMsg, "should detour if connection is refused")
	}

	u, _ := url.Parse(mockURL)
	resp, err = client.Get(mockURL)
	if assert.NoError(t, err, "should have no error if reading times out") {
		assert.True(t, wlTemporarily(u.Host), "should be added to whitelist if reading times out")
		assertContent(t, resp, detourMsg, "should detour if reading times out")
	}

	client = newClient(proxiedURL, 100*time.Millisecond)
	RemoveFromWl(u.Host)
	resp, err = client.PostForm(mockURL, url.Values{"key": []string{"value"}})
	if assert.Error(t, err, "Non-idempotent method should not be detoured in same connection") {
		assert.True(t, wlTemporarily(u.Host), "but should be added to whitelist so will detour next time")
	}
}
Example #19
0
func TestSingle(t *testing.T) {
	v := NewValue()
	go func() {
		time.Sleep(20 * time.Millisecond)
		v.Set("hi")
	}()

	r, ok := v.Get(10 * time.Millisecond)
	assert.False(t, ok, "Get with short timeout should have timed out")

	r, ok = v.Get(20 * time.Millisecond)
	assert.True(t, ok, "Get with longer timeout should have succeed")
	assert.Equal(t, "hi", r, "Wrong result")
}
Example #20
0
func TestMaxConnections(t *testing.T) {
	connectReq := "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n"

	limitedServer, err := setupNewHTTPServer(5, 30*time.Second)
	if err != nil {
		assert.Fail(t, "Error starting proxy server")
	}

	//limitedServer.httpServer.SetKeepAlivesEnabled(false)
	okFn := func(conn net.Conn, proxy *server.Server, originURL *url.URL) {
		req := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)
		conn.Write([]byte(req))
		var buf [400]byte
		_, err = conn.Read(buf[:])

		assert.NoError(t, err)

		time.Sleep(time.Millisecond * 100)
	}

	waitFn := func(conn net.Conn, proxy *server.Server, originURL *url.URL) {
		conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond))

		req := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)
		conn.Write([]byte(req))
		var buf [400]byte
		_, err = conn.Read(buf[:])

		if assert.Error(t, err) {
			e, ok := err.(*net.OpError)
			assert.True(t, ok && e.Timeout(), "should be a time out error")
		}
	}

	for i := 0; i < 5; i++ {
		go testRoundTrip(t, limitedServer, httpOriginServer, okFn)
	}

	time.Sleep(time.Millisecond * 10)

	for i := 0; i < 5; i++ {
		go testRoundTrip(t, limitedServer, httpOriginServer, waitFn)
	}

	time.Sleep(time.Millisecond * 100)

	for i := 0; i < 5; i++ {
		go testRoundTrip(t, limitedServer, httpOriginServer, okFn)
	}
}
Example #21
0
func TestList(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	dists, err := ListDistributions(cfr)
	if assert.NoError(t, err, "Should be able to get all distributions") {
		for _, d := range dists {
			log.Tracef("%v : %v (%v)", d.InstanceId, d.Domain, d.Status)
		}
		assert.True(t, len(dists) > 0, "There should be some distributions")
	}
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Example #22
0
func TestVariableTimeouts(t *testing.T) {
	// Timeouts can happen in different places, run a bunch of randomized trials
	// to try to cover all of them.
	_, fdc, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	doTestTimeout := func(timeout time.Duration) (didTimeout bool) {
		_, err := DialWithDialer(&net.Dialer{
			Timeout: timeout,
		}, "tcp", ADDR, false, &tls.Config{
			RootCAs: cert.PoolContainingCert(),
		})

		if err == nil {
			return false
		} else {
			if neterr, isNetError := err.(net.Error); isNetError {
				assert.True(t, neterr.Timeout(), "Dial error should be timeout", timeout)
			} else {
				t.Fatal(err)
			}
			return true
		}
	}

	// The 1000-5000 microseconds limits are arbitrary. In some systems this may be too low/high.
	// The algorithm will try to adapt if connections succeed and will lower the current limit,
	// but it won't be allowed to timeout below the established lower boundary.
	timeoutMin := 1000
	timeoutMax := 5000
	for i := 0; i < 500; i++ {
		timeout := rand.Intn(timeoutMax) + 1
		didTimeout := doTestTimeout(time.Duration(timeout) * time.Microsecond)
		if !didTimeout {
			if timeout < timeoutMin {
				t.Fatalf("The connection succeeded in an unexpected short time: %d", timeout)
			}
			timeoutMax = int(float64(timeoutMax) * 0.75)
			i-- // repeat the test
		}
	}

	// Wait to give the sockets time to close
	time.Sleep(1 * time.Second)
	assert.NoError(t, fdc.AssertDelta(0), "Number of open files should be the same after test as before")
}
Example #23
0
func TestAll(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	u := getUtil()
	recs, err := u.GetAllRecords()
	if assert.NoError(t, err, "Should be able to get all records") {
		for _, r := range recs {
			log.Tracef("%v : %v", r.Name, r.Content)
		}
		assert.True(t, len(recs) > 0, "There should be some records")
	}

	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Example #24
0
func TestReadTimeout(t *testing.T) {
	defer stopMockServers()
	proxiedURL, _ := newMockServer(detourMsg)
	mockURL, mock := newMockServer("")
	mock.Timeout(200*time.Millisecond, directMsg)

	client := &http.Client{Timeout: 100 * time.Millisecond}
	resp, err := client.Get(mockURL)
	assert.Error(t, err, "direct access to a timeout url should fail")

	u, _ := url.Parse(mockURL)
	client = newClient(proxiedURL, 100*time.Millisecond)
	resp, err = client.Get(mockURL)
	if assert.NoError(t, err, "should have no error if reading times out") {
		time.Sleep(50 * time.Millisecond)
		assert.True(t, wlTemporarily(u.Host), "should be added to whitelist if reading times out")
		assertContent(t, resp, detourMsg, "should detour if reading times out")
	}
}
Example #25
0
func TestList(t *testing.T) {
	if true {
		t.Log("We don't currently use peerscanner, so this test is disabled")
		return
	}
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	dists, err := ListDistributions(cfr)
	if assert.NoError(t, err, "Should be able to get all distributions") {
		for _, d := range dists {
			log.Tracef("%v : %v (%v)\t\t%v", d.InstanceId, d.Domain, d.Status, d.Comment)
		}
		assert.True(t, len(dists) > 0, "There should be some distributions")
	}
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Example #26
0
func TestExec(t *testing.T) {
	data, err := Asset(program)
	if err != nil {
		t.Fatalf("Unable to read helloworld program: %s", err)
	}
	be := createByteExec(t, data)

	// Concurrently create some other BEs and make sure they don't get errors
	var wg sync.WaitGroup
	wg.Add(concurrency)
	for i := 0; i < concurrency; i++ {
		_, err := New(data, program)
		assert.NoError(t, err, "Concurrent New should have succeeded")
		wg.Done()
	}
	wg.Wait()

	originalInfo := testByteExec(t, be)

	// Recreate be and make sure file is reused
	be = createByteExec(t, data)
	updatedInfo := testByteExec(t, be)
	assert.Equal(t, originalInfo.ModTime(), updatedInfo.ModTime(), "File modification time should be unchanged after creating new ByteExec")

	// Now mess with the file permissions and make sure that we can still run
	err = os.Chmod(be.Filename, 0655)
	if err != nil {
		t.Fatalf("Unable to chmod test executable %s: %s", be.Filename, err)
	}
	be = createByteExec(t, data)
	updatedInfo = testByteExec(t, be)
	assert.True(t, fileMode == updatedInfo.Mode(), fmt.Sprintf("File mode was %v instead of %v", updatedInfo.Mode(), fileMode))

	// Now mess with the file contents and make sure it gets overwritten on next
	// ByteExec
	if err := ioutil.WriteFile(be.Filename, []byte("Junk"), 0755); err != nil {
		t.Fatalf("Unable to write file: %v", err)
	}
	be = createByteExec(t, data)
	updatedInfo = testByteExec(t, be)
	assert.NotEqual(t, originalInfo.ModTime(), updatedInfo.ModTime(), "File modification time should be changed after creating new ByteExec on bad data")
}
Example #27
0
func TestBlockedAfterwards(t *testing.T) {
	defer stopMockServers()
	proxiedURL, _ := newMockServer(detourMsg)
	mockURL, mock := newMockServer(directMsg)
	client := newClient(proxiedURL, 100*time.Millisecond)

	mock.Msg(directMsg)
	resp, err := client.Get(mockURL)
	if assert.NoError(t, err, "should have no error for normal response") {
		assertContent(t, resp, directMsg, "should access directly for normal response")
	}
	mock.Timeout(200*time.Millisecond, directMsg)
	_, err = client.Get(mockURL)
	assert.Error(t, err, "should have error if reading times out for a previously worked url")
	resp, err = client.Get(mockURL)
	if assert.NoError(t, err, "but should have no error for the second time") {
		u, _ := url.Parse(mockURL)
		time.Sleep(50 * time.Millisecond)
		assertContent(t, resp, detourMsg, "should detour if reading times out")
		assert.True(t, wlTemporarily(u.Host), "should be added to whitelist if reading times out")
	}
}
Example #28
0
func TestDeadlineBeforeTimeout(t *testing.T) {
	_, fdc, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	conn, err := DialWithDialer(&net.Dialer{
		Timeout:  500 * time.Second,
		Deadline: time.Now().Add(5 * time.Microsecond),
	}, "tcp", ADDR, false, nil)

	assert.Error(t, err, "There should have been a problem dialing")

	if err != nil {
		if neterr, isNetError := err.(net.Error); isNetError {
			assert.True(t, neterr.Timeout(), "Dial error should be timeout")
		} else {
			t.Fatal(err)
		}
	}

	closeAndCountFDs(t, conn, err, fdc)
}
Example #29
0
func TestRoundTrip(t *testing.T) {
	expectedA, err := ioutil.ReadFile("resources/a.txt")
	if err != nil {
		t.Fatalf("Unable to load expectedA: %v", err)
	}

	expectedB, err := ioutil.ReadFile("localresources/sub/b.txt")
	if err != nil {
		t.Fatalf("Unable to load expectedB: %v", err)
	}

	expectedC, err := ioutil.ReadFile("resources/sub/c.txt")
	if err != nil {
		t.Fatalf("Unable to load expectedC: %v", err)
	}

	tarString := bytes.NewBuffer(nil)
	err = EncodeToTarString("resources", tarString)
	if err != nil {
		t.Fatalf("Unable to encode to tar string: %v", err)
	}

	fs, err := New(tarStringToBytes(t, tarString), "localresources")
	if err != nil {
		t.Fatalf("Unable to open filesystem: %v", err)
	}

	a, err := fs.Get("a.txt")
	if assert.NoError(t, err, "a.txt should have loaded") {
		assert.Equal(t, string(expectedA), string(a), "A should have matched expected")
	}

	b, err := fs.Get("sub/b.txt")
	if assert.NoError(t, err, "b.txt should have loaded") {
		assert.Equal(t, string(expectedB), string(b), "B should have matched expected")
	}

	f, err := fs.Open("/nonexistentdirectory/")
	if assert.NoError(t, err, "Opening nonexistent directory should work") {
		fi, err := f.Stat()
		if assert.NoError(t, err, "Should be able to stat directory") {
			assert.True(t, fi.IsDir(), "Nonexistent directory should be a directory")
		}
	}

	f, err = fs.Open("/nonexistentfile")
	assert.Error(t, err, "Opening nonexistent file should fail")

	f, err = fs.Open("/sub//c.txt")
	if assert.NoError(t, err, "Opening existing file with double slash should work") {
		fi, err := f.Stat()
		if assert.NoError(t, err, "Should be able to stat file") {
			if assert.False(t, fi.IsDir(), "File should not be a directory") {
				if assert.Equal(t, len(expectedC), fi.Size(), "File info should report correct size") {
					a := bytes.NewBuffer(nil)
					_, err := io.Copy(a, f)
					if assert.NoError(t, err, "Should be able to read from file") {
						assert.Equal(t, expectedC, a.Bytes(), "Should have read correct data")
					}
				}
			}
		}
	}

	sub := fs.SubDir("sub")
	b, err = sub.Get("b.txt")
	if assert.NoError(t, err, "b.txt should have loaded from sub") {
		assert.Equal(t, string(expectedB), string(b), "B should have matched expected")
	}

	c, err := sub.Get("c.txt")
	if assert.NoError(t, err, "c.txt should have loaded from sub") {
		assert.Equal(t, string(expectedC), string(c), "C should have matched expected")
	}
}
Example #30
0
func TestCheckSubdomain(t *testing.T) {
	AddToWl("facebook.com:80", true)
	assert.True(t, whitelisted("www.facebook.com:80"), "should match subdomain")
	assert.True(t, whitelisted("sub2.facebook.com:80"), "should match all subdomains")
}