SocketTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. // Windows doesn't return the previous exception for some reason
  260. if (DS !== '\\') {
  261. $this->assertInstanceOf('Exception', $e->getPrevious());
  262. }
  263. }
  264. /**
  265. * testEnableCryptoSocketExceptionNoTls
  266. */
  267. public function testEnableCryptoSocketExceptionNoTls(): void
  268. {
  269. $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 1];
  270. // testing exception on no ssl socket server for ssl and tls methods
  271. $this->Socket = new Socket($configNoSslOrTls);
  272. try {
  273. $this->Socket->connect();
  274. } catch (SocketException $e) {
  275. $this->markTestSkipped('Cannot test network, skipping.');
  276. }
  277. $e = null;
  278. try {
  279. $this->Socket->enableCrypto('tls', 'client');
  280. } catch (SocketException $e) {
  281. }
  282. $this->assertNotNull($e);
  283. // Windows doesn't return the previous exception for some reason
  284. if (DS !== '\\') {
  285. $this->assertInstanceOf('Exception', $e->getPrevious());
  286. }
  287. }
  288. /**
  289. * Test that protocol in the host doesn't cause cert errors.
  290. */
  291. public function testConnectProtocolInHost(): void
  292. {
  293. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  294. $configSslTls = ['host' => 'ssl://smtp.gmail.com', 'port' => 465, 'timeout' => 5];
  295. $socket = new Socket($configSslTls);
  296. try {
  297. $socket->connect();
  298. $this->assertSame('smtp.gmail.com', $socket->getConfig('host'));
  299. $this->assertSame('ssl', $socket->getConfig('protocol'));
  300. } catch (SocketException $e) {
  301. $this->markTestSkipped('Cannot test network, skipping.');
  302. }
  303. }
  304. /**
  305. * _connectSocketToSslTls
  306. */
  307. protected function _connectSocketToSslTls(): void
  308. {
  309. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  310. $configSslTls = ['host' => 'smtp.gmail.com', 'port' => 465, 'timeout' => 5];
  311. $this->Socket = new Socket($configSslTls);
  312. try {
  313. $this->Socket->connect();
  314. } catch (SocketException $e) {
  315. $this->markTestSkipped('Cannot test network, skipping.');
  316. }
  317. }
  318. /**
  319. * testEnableCryptoBadMode
  320. */
  321. public function testEnableCryptoBadMode(): void
  322. {
  323. $this->expectException(InvalidArgumentException::class);
  324. // testing wrong encryption mode
  325. $this->_connectSocketToSslTls();
  326. $this->Socket->enableCrypto('doesntExistMode', 'server');
  327. $this->Socket->disconnect();
  328. }
  329. /**
  330. * testEnableCrypto
  331. */
  332. public function testEnableCrypto(): void
  333. {
  334. $this->_connectSocketToSslTls();
  335. $this->Socket->enableCrypto('tls', 'client');
  336. $result = $this->Socket->disconnect();
  337. $this->assertTrue($result);
  338. }
  339. /**
  340. * testEnableCryptoExceptionEnableTwice
  341. */
  342. public function testEnableCryptoExceptionEnableTwice(): void
  343. {
  344. $this->expectException(SocketException::class);
  345. // testing on tls server
  346. $this->_connectSocketToSslTls();
  347. $this->Socket->enableCrypto('tls', 'client');
  348. $this->Socket->enableCrypto('tls', 'client');
  349. }
  350. /**
  351. * testEnableCryptoExceptionDisableTwice
  352. */
  353. public function testEnableCryptoExceptionDisableTwice(): void
  354. {
  355. $this->expectException(SocketException::class);
  356. $this->_connectSocketToSslTls();
  357. $this->Socket->enableCrypto('tls', 'client', false);
  358. }
  359. /**
  360. * testEnableCryptoEnableStatus
  361. */
  362. public function testEnableCryptoEnableTls12(): void
  363. {
  364. $this->_connectSocketToSslTls();
  365. $this->assertFalse($this->Socket->isEncrypted());
  366. $this->Socket->enableCrypto('tlsv12', 'client', true);
  367. $this->assertTrue($this->Socket->isEncrypted());
  368. }
  369. /**
  370. * testEnableCryptoEnableStatus
  371. */
  372. public function testEnableCryptoEnableStatus(): void
  373. {
  374. $this->_connectSocketToSslTls();
  375. $this->assertFalse($this->Socket->isEncrypted());
  376. $this->Socket->enableCrypto('tls', 'client', true);
  377. $this->assertTrue($this->Socket->isEncrypted());
  378. }
  379. /**
  380. * test getting the context for a socket.
  381. */
  382. public function testGetContext(): void
  383. {
  384. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  385. $config = [
  386. 'host' => 'smtp.gmail.com',
  387. 'port' => 465,
  388. 'timeout' => 5,
  389. 'context' => [
  390. 'ssl' => ['capture_peer' => true],
  391. ],
  392. ];
  393. try {
  394. $this->Socket = new Socket($config);
  395. $this->Socket->connect();
  396. } catch (SocketException $e) {
  397. $this->markTestSkipped('No network, skipping test.');
  398. }
  399. $result = $this->Socket->context();
  400. $this->assertTrue($result['ssl']['capture_peer']);
  401. }
  402. /**
  403. * test configuring the context from the flat keys.
  404. */
  405. public function testConfigContext(): void
  406. {
  407. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  408. $this->skipIf(!empty(getenv('http_proxy')) || !empty(getenv('https_proxy')), 'Proxy detected and cannot test SSL.');
  409. $config = [
  410. 'host' => 'smtp.gmail.com',
  411. 'port' => 465,
  412. 'timeout' => 5,
  413. 'ssl_verify_peer' => true,
  414. 'ssl_allow_self_signed' => false,
  415. 'ssl_verify_depth' => 5,
  416. 'ssl_verify_host' => true,
  417. ];
  418. $socket = new Socket($config);
  419. $socket->connect();
  420. $result = $socket->context();
  421. $this->assertTrue($result['ssl']['verify_peer']);
  422. $this->assertFalse($result['ssl']['allow_self_signed']);
  423. $this->assertSame(5, $result['ssl']['verify_depth']);
  424. $this->assertSame('smtp.gmail.com', $result['ssl']['CN_match']);
  425. $this->assertArrayNotHasKey('ssl_verify_peer', $socket->getConfig());
  426. $this->assertArrayNotHasKey('ssl_allow_self_signed', $socket->getConfig());
  427. $this->assertArrayNotHasKey('ssl_verify_host', $socket->getConfig());
  428. $this->assertArrayNotHasKey('ssl_verify_depth', $socket->getConfig());
  429. }
  430. /**
  431. * test connect to a unix file socket
  432. */
  433. public function testConnectToUnixFileSocket(): void
  434. {
  435. $socketName = 'unix:///tmp/test.socket';
  436. $socket = $this->getMockBuilder(Socket::class)
  437. ->onlyMethods(['_getStreamSocketClient'])
  438. ->getMock();
  439. $socket->expects($this->once())
  440. ->method('_getStreamSocketClient')
  441. ->with('unix:///tmp/test.socket', null, null, 1)
  442. ->willReturn(false);
  443. $socket->setConfig([
  444. 'host' => $socketName,
  445. 'port' => null,
  446. 'timeout' => 1,
  447. 'persistent' => true,
  448. ]);
  449. $socket->connect();
  450. }
  451. }