1#!/usr/bin/python 2# 3# Copyright 2016 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17from errno import * # pylint: disable=wildcard-import 18from socket import * # pylint: disable=wildcard-import 19import threading 20import time 21import unittest 22 23import csocket 24import net_test 25 26 27class LeakTest(net_test.NetworkTest): 28 29 def testRecvfromLeak(self): 30 s = socket(AF_INET6, SOCK_DGRAM, 0) 31 s.bind(("::1", 0)) 32 33 # Call shutdown on another thread while a recvfrom is in progress. 34 csocket.SetSocketTimeout(s, 2000) 35 def ShutdownSocket(): 36 time.sleep(0.5) 37 self.assertRaisesErrno(ENOTCONN, s.shutdown, SHUT_RDWR) 38 39 t = threading.Thread(target=ShutdownSocket) 40 t.start() 41 42 # This could have been written with just "s.recvfrom", but because we're 43 # testing for a bug where the kernel returns garbage, it's probably safer 44 # to call the syscall directly. 45 data, addr = csocket.Recvfrom(s, 4096) 46 self.assertEqual("", data) 47 self.assertEqual(None, addr) 48 49 50class ForceSocketBufferOptionTest(net_test.NetworkTest): 51 52 SO_SNDBUFFORCE = 32 53 SO_RCVBUFFORCE = 33 54 55 def CheckForceSocketBufferOption(self, option, force_option): 56 s = socket(AF_INET6, SOCK_DGRAM, 0) 57 58 # Find the minimum buffer value. 59 s.setsockopt(SOL_SOCKET, option, 0) 60 minbuf = s.getsockopt(SOL_SOCKET, option) 61 62 # Check that the force option works to set reasonable values. 63 val = 4097 64 self.assertGreater(2 * val, minbuf) 65 s.setsockopt(SOL_SOCKET, force_option, val) 66 self.assertEquals(2 * val, s.getsockopt(SOL_SOCKET, option)) 67 68 # Check that the force option sets the minimum value instead of a negative 69 # value on integer overflow. Because the kernel multiplies passed-in values 70 # by 2, pick a value that becomes a small negative number if treated as 71 # unsigned. 72 bogusval = 2 ** 31 - val 73 s.setsockopt(SOL_SOCKET, force_option, bogusval) 74 self.assertEquals(minbuf, s.getsockopt(SOL_SOCKET, option)) 75 76 def testRcvBufForce(self): 77 self.CheckForceSocketBufferOption(SO_RCVBUF, self.SO_RCVBUFFORCE) 78 79 def testRcvBufForce(self): 80 self.CheckForceSocketBufferOption(SO_SNDBUF, self.SO_SNDBUFFORCE) 81 82 83if __name__ == "__main__": 84 unittest.main() 85