SocketTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Network;
  17. use Cake\Network\Exception\SocketException;
  18. use Cake\Network\Socket;
  19. use Cake\TestSuite\TestCase;
  20. use InvalidArgumentException;
  21. /**
  22. * SocketTest class
  23. */
  24. class SocketTest extends TestCase
  25. {
  26. /**
  27. * @var \Cake\Network\Socket
  28. */
  29. protected $Socket;
  30. /**
  31. * setUp method
  32. */
  33. public function setUp(): void
  34. {
  35. parent::setUp();
  36. $this->Socket = new Socket(['timeout' => 1]);
  37. }
  38. /**
  39. * tearDown method
  40. */
  41. public function tearDown(): void
  42. {
  43. parent::tearDown();
  44. unset($this->Socket);
  45. }
  46. /**
  47. * testConstruct method
  48. */
  49. public function testConstruct(): void
  50. {
  51. $this->Socket = new Socket();
  52. $config = $this->Socket->getConfig();
  53. $this->assertSame($config, [
  54. 'persistent' => false,
  55. 'host' => 'localhost',
  56. 'protocol' => 'tcp',
  57. 'port' => 80,
  58. 'timeout' => 30,
  59. ]);
  60. $this->Socket->reset();
  61. $this->Socket->__construct(['host' => 'foo-bar']);
  62. $config['host'] = 'foo-bar';
  63. $this->assertSame($this->Socket->getConfig(), $config);
  64. $this->Socket = new Socket(['host' => 'www.cakephp.org', 'port' => 23, 'protocol' => 'udp']);
  65. $config = $this->Socket->getConfig();
  66. $config['host'] = 'www.cakephp.org';
  67. $config['port'] = 23;
  68. $config['protocol'] = 'udp';
  69. $this->assertSame($this->Socket->getConfig(), $config);
  70. }
  71. /**
  72. * test host() method
  73. */
  74. public function testHost(): void
  75. {
  76. $this->Socket = new Socket(['host' => '8.8.8.8']);
  77. $this->assertSame('dns.google', $this->Socket->host());
  78. }
  79. /**
  80. * test addresses() method
  81. */
  82. public function testAddresses(): void
  83. {
  84. $this->Socket = new Socket();
  85. $this->assertContainsEquals('127.0.0.1', $this->Socket->addresses());
  86. $this->Socket = new Socket(['host' => '8.8.8.8']);
  87. $this->assertSame(['8.8.8.8'], $this->Socket->addresses());
  88. }
  89. /**
  90. * testSocketConnection method
  91. */
  92. public function testSocketConnection(): void
  93. {
  94. $this->assertFalse($this->Socket->isConnected());
  95. $this->Socket->disconnect();
  96. $this->assertFalse($this->Socket->isConnected());
  97. try {
  98. $this->Socket->connect();
  99. $this->assertTrue($this->Socket->isConnected());
  100. $this->Socket->connect();
  101. $this->assertTrue($this->Socket->isConnected());
  102. $this->Socket->disconnect();
  103. $config = ['persistent' => true];
  104. $this->Socket = new Socket($config);
  105. $this->Socket->connect();
  106. $this->assertTrue($this->Socket->isConnected());
  107. } catch (SocketException $e) {
  108. $this->markTestSkipped('Cannot test network, skipping.');
  109. }
  110. }
  111. /**
  112. * data provider function for testInvalidConnection
  113. *
  114. * @return array
  115. */
  116. public static function invalidConnections(): array
  117. {
  118. return [
  119. [['host' => 'invalid.host', 'port' => 9999, 'timeout' => 1]],
  120. [['host' => '127.0.0.1', 'port' => '70000', 'timeout' => 1]],
  121. ];
  122. }
  123. /**
  124. * testInvalidConnection method
  125. *
  126. * @dataProvider invalidConnections
  127. */
  128. public function testInvalidConnection(array $data): void
  129. {
  130. $this->expectException(SocketException::class);
  131. $this->Socket->setConfig($data);
  132. $this->Socket->connect();
  133. }
  134. /**
  135. * testSocketHost method
  136. */
  137. public function testSocketHost(): void
  138. {
  139. try {
  140. $this->Socket = new Socket();
  141. $this->Socket->connect();
  142. $this->assertSame('127.0.0.1', $this->Socket->address());
  143. $this->assertEquals(gethostbyaddr('127.0.0.1'), $this->Socket->host());
  144. $this->assertNull($this->Socket->lastError());
  145. $this->assertContains('127.0.0.1', $this->Socket->addresses());
  146. $this->Socket = new Socket(['host' => '127.0.0.1']);
  147. $this->Socket->connect();
  148. $this->assertSame('127.0.0.1', $this->Socket->address());
  149. $this->assertEquals(gethostbyaddr('127.0.0.1'), $this->Socket->host());
  150. $this->assertNull($this->Socket->lastError());
  151. $this->assertContains('127.0.0.1', $this->Socket->addresses());
  152. } catch (SocketException $e) {
  153. $this->markTestSkipped('Cannot test network, skipping.');
  154. }
  155. }
  156. /**
  157. * testSocketWriting method
  158. */
  159. public function testSocketWriting(): void
  160. {
  161. try {
  162. $request = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
  163. $this->assertTrue((bool)$this->Socket->write($request));
  164. } catch (SocketException $e) {
  165. $this->markTestSkipped('Cannot test network, skipping.');
  166. }
  167. }
  168. /**
  169. * testSocketReading method
  170. */
  171. public function testSocketReading(): void
  172. {
  173. $this->Socket = new Socket(['timeout' => 5]);
  174. try {
  175. $this->Socket->connect();
  176. $this->assertNull($this->Socket->read(26));
  177. $config = ['host' => 'google.com', 'port' => 80, 'timeout' => 1];
  178. $this->Socket = new Socket($config);
  179. $this->assertTrue($this->Socket->connect());
  180. $this->assertNull($this->Socket->read(26));
  181. $this->assertSame('2: ' . 'Connection timed out', $this->Socket->lastError());
  182. } catch (SocketException $e) {
  183. $this->markTestSkipped('Cannot test network, skipping.');
  184. }
  185. }
  186. /**
  187. * testTimeOutConnection method
  188. */
  189. public function testTimeOutConnection(): void
  190. {
  191. $config = ['host' => '127.0.0.1', 'timeout' => 1];
  192. $this->Socket = new Socket($config);
  193. try {
  194. $this->assertTrue($this->Socket->connect());
  195. $config = ['host' => '127.0.0.1', 'timeout' => 1];
  196. $this->Socket = new Socket($config);
  197. $this->assertNull($this->Socket->read(1024 * 1024));
  198. $this->assertSame('2: ' . 'Connection timed out', $this->Socket->lastError());
  199. } catch (SocketException $e) {
  200. $this->markTestSkipped('Cannot test network, skipping.');
  201. }
  202. }
  203. /**
  204. * testLastError method
  205. */
  206. public function testLastError(): void
  207. {
  208. $this->Socket = new Socket();
  209. $this->Socket->setLastError(4, 'some error here');
  210. $this->assertSame('4: some error here', $this->Socket->lastError());
  211. }
  212. /**
  213. * testReset method
  214. */
  215. public function testReset(): void
  216. {
  217. $config = [
  218. 'persistent' => true,
  219. 'host' => '127.0.0.1',
  220. 'protocol' => 'udp',
  221. 'port' => 80,
  222. 'timeout' => 20,
  223. ];
  224. $anotherSocket = new Socket($config);
  225. $anotherSocket->reset();
  226. $expected = [
  227. 'persistent' => false,
  228. 'host' => 'localhost',
  229. 'protocol' => 'tcp',
  230. 'port' => 80,
  231. 'timeout' => 30,
  232. ];
  233. $this->assertEquals(
  234. $expected,
  235. $anotherSocket->getConfig(),
  236. 'Reset should cause config to return the defaults defined in _defaultConfig'
  237. );
  238. }
  239. /**
  240. * testEncrypt
  241. */
  242. public function testEnableCryptoSocketExceptionNoSsl(): void
  243. {
  244. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  245. $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 1];
  246. // testing exception on no ssl socket server for ssl and tls methods
  247. $this->Socket = new Socket($configNoSslOrTls);
  248. try {
  249. $this->Socket->connect();
  250. } catch (SocketException $e) {
  251. $this->markTestSkipped('Cannot test network, skipping.');
  252. }
  253. $e = null;
  254. try {
  255. $this->Socket->enableCrypto('tlsv10', 'client');
  256. } catch (SocketException $e) {
  257. }
  258. $this->assertNotNull($e);
  259. $this->assertInstanceOf('Exception', $e->getPrevious());
  260. }
  261. /**
  262. * testEnableCryptoSocketExceptionNoTls
  263. */
  264. public function testEnableCryptoSocketExceptionNoTls(): void
  265. {
  266. $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 1];
  267. // testing exception on no ssl socket server for ssl and tls methods
  268. $this->Socket = new Socket($configNoSslOrTls);
  269. try {
  270. $this->Socket->connect();
  271. } catch (SocketException $e) {
  272. $this->markTestSkipped('Cannot test network, skipping.');
  273. }
  274. $e = null;
  275. try {
  276. $this->Socket->enableCrypto('tls', 'client');
  277. } catch (SocketException $e) {
  278. }
  279. $this->assertNotNull($e);
  280. $this->assertInstanceOf('Exception', $e->getPrevious());
  281. }
  282. /**
  283. * Test that protocol in the host doesn't cause cert errors.
  284. */
  285. public function testConnectProtocolInHost(): void
  286. {
  287. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  288. $configSslTls = ['host' => 'ssl://smtp.gmail.com', 'port' => 465, 'timeout' => 5];
  289. $socket = new Socket($configSslTls);
  290. try {
  291. $socket->connect();
  292. $this->assertSame('smtp.gmail.com', $socket->getConfig('host'));
  293. $this->assertSame('ssl', $socket->getConfig('protocol'));
  294. } catch (SocketException $e) {
  295. $this->markTestSkipped('Cannot test network, skipping.');
  296. }
  297. }
  298. /**
  299. * _connectSocketToSslTls
  300. */
  301. protected function _connectSocketToSslTls(): void
  302. {
  303. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  304. $configSslTls = ['host' => 'smtp.gmail.com', 'port' => 465, 'timeout' => 5];
  305. $this->Socket = new Socket($configSslTls);
  306. try {
  307. $this->Socket->connect();
  308. } catch (SocketException $e) {
  309. $this->markTestSkipped('Cannot test network, skipping.');
  310. }
  311. }
  312. /**
  313. * testEnableCryptoBadMode
  314. */
  315. public function testEnableCryptoBadMode(): void
  316. {
  317. $this->expectException(InvalidArgumentException::class);
  318. // testing wrong encryption mode
  319. $this->_connectSocketToSslTls();
  320. $this->Socket->enableCrypto('doesntExistMode', 'server');
  321. $this->Socket->disconnect();
  322. }
  323. /**
  324. * testEnableCrypto
  325. */
  326. public function testEnableCrypto(): void
  327. {
  328. $this->_connectSocketToSslTls();
  329. $this->Socket->enableCrypto('tls', 'client');
  330. $result = $this->Socket->disconnect();
  331. $this->assertTrue($result);
  332. }
  333. /**
  334. * testEnableCryptoExceptionEnableTwice
  335. */
  336. public function testEnableCryptoExceptionEnableTwice(): void
  337. {
  338. $this->expectException(SocketException::class);
  339. // testing on tls server
  340. $this->_connectSocketToSslTls();
  341. $this->Socket->enableCrypto('tls', 'client');
  342. $this->Socket->enableCrypto('tls', 'client');
  343. }
  344. /**
  345. * testEnableCryptoExceptionDisableTwice
  346. */
  347. public function testEnableCryptoExceptionDisableTwice(): void
  348. {
  349. $this->expectException(SocketException::class);
  350. $this->_connectSocketToSslTls();
  351. $this->Socket->enableCrypto('tls', 'client', false);
  352. }
  353. /**
  354. * testEnableCryptoEnableStatus
  355. */
  356. public function testEnableCryptoEnableTls12(): void
  357. {
  358. $this->_connectSocketToSslTls();
  359. $this->assertFalse($this->Socket->isEncrypted());
  360. $this->Socket->enableCrypto('tlsv12', 'client', true);
  361. $this->assertTrue($this->Socket->isEncrypted());
  362. }
  363. /**
  364. * testEnableCryptoEnableStatus
  365. */
  366. public function testEnableCryptoEnableStatus(): void
  367. {
  368. $this->_connectSocketToSslTls();
  369. $this->assertFalse($this->Socket->isEncrypted());
  370. $this->Socket->enableCrypto('tls', 'client', true);
  371. $this->assertTrue($this->Socket->isEncrypted());
  372. }
  373. /**
  374. * test getting the context for a socket.
  375. */
  376. public function testGetContext(): void
  377. {
  378. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  379. $config = [
  380. 'host' => 'smtp.gmail.com',
  381. 'port' => 465,
  382. 'timeout' => 5,
  383. 'context' => [
  384. 'ssl' => ['capture_peer' => true],
  385. ],
  386. ];
  387. try {
  388. $this->Socket = new Socket($config);
  389. $this->Socket->connect();
  390. } catch (SocketException $e) {
  391. $this->markTestSkipped('No network, skipping test.');
  392. }
  393. $result = $this->Socket->context();
  394. $this->assertTrue($result['ssl']['capture_peer']);
  395. }
  396. /**
  397. * test configuring the context from the flat keys.
  398. */
  399. public function testConfigContext(): void
  400. {
  401. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  402. $this->skipIf(!empty(getenv('http_proxy')) || !empty(getenv('https_proxy')), 'Proxy detected and cannot test SSL.');
  403. $config = [
  404. 'host' => 'smtp.gmail.com',
  405. 'port' => 465,
  406. 'timeout' => 5,
  407. 'ssl_verify_peer' => true,
  408. 'ssl_allow_self_signed' => false,
  409. 'ssl_verify_depth' => 5,
  410. 'ssl_verify_host' => true,
  411. ];
  412. $socket = new Socket($config);
  413. $socket->connect();
  414. $result = $socket->context();
  415. $this->assertTrue($result['ssl']['verify_peer']);
  416. $this->assertFalse($result['ssl']['allow_self_signed']);
  417. $this->assertSame(5, $result['ssl']['verify_depth']);
  418. $this->assertSame('smtp.gmail.com', $result['ssl']['CN_match']);
  419. $this->assertArrayNotHasKey('ssl_verify_peer', $socket->getConfig());
  420. $this->assertArrayNotHasKey('ssl_allow_self_signed', $socket->getConfig());
  421. $this->assertArrayNotHasKey('ssl_verify_host', $socket->getConfig());
  422. $this->assertArrayNotHasKey('ssl_verify_depth', $socket->getConfig());
  423. }
  424. /**
  425. * test connect to a unix file socket
  426. */
  427. public function testConnectToUnixFileSocket(): void
  428. {
  429. $socketName = 'unix:///tmp/test.socket';
  430. $socket = $this->getMockBuilder(Socket::class)
  431. ->onlyMethods(['_getStreamSocketClient'])
  432. ->getMock();
  433. $socket->expects($this->once())
  434. ->method('_getStreamSocketClient')
  435. ->with('unix:///tmp/test.socket', null, null, 1)
  436. ->willReturn(false);
  437. $socket->setConfig([
  438. 'host' => $socketName,
  439. 'port' => null,
  440. 'timeout' => 1,
  441. 'persistent' => true,
  442. ]);
  443. $socket->connect();
  444. }
  445. }