SocketTest.php 16 KB

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