SocketTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. $this->Socket = new Socket($config);
  196. $this->assertNull($this->Socket->read(1024 * 1024));
  197. $this->assertSame('2: ' . 'Connection timed out', $this->Socket->lastError());
  198. } catch (SocketException $e) {
  199. $this->markTestSkipped('Cannot test network, skipping.');
  200. }
  201. }
  202. /**
  203. * testLastError method
  204. */
  205. public function testLastError(): void
  206. {
  207. $this->Socket = new Socket();
  208. $this->Socket->setLastError(4, 'some error here');
  209. $this->assertSame('4: some error here', $this->Socket->lastError());
  210. }
  211. /**
  212. * testReset method
  213. */
  214. public function testReset(): void
  215. {
  216. $config = [
  217. 'persistent' => true,
  218. 'host' => '127.0.0.1',
  219. 'protocol' => 'udp',
  220. 'port' => 80,
  221. 'timeout' => 20,
  222. ];
  223. $anotherSocket = new Socket($config);
  224. $anotherSocket->reset();
  225. $expected = [
  226. 'persistent' => false,
  227. 'host' => 'localhost',
  228. 'protocol' => 'tcp',
  229. 'port' => 80,
  230. 'timeout' => 30,
  231. ];
  232. $this->assertEquals(
  233. $expected,
  234. $anotherSocket->getConfig(),
  235. 'Reset should cause config to return the defaults defined in _defaultConfig'
  236. );
  237. }
  238. /**
  239. * testEncrypt
  240. */
  241. public function testEnableCryptoSocketExceptionNoSsl(): void
  242. {
  243. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  244. $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 1];
  245. // testing exception on no ssl socket server for ssl and tls methods
  246. $this->Socket = new Socket($configNoSslOrTls);
  247. try {
  248. $this->Socket->connect();
  249. } catch (SocketException $e) {
  250. $this->markTestSkipped('Cannot test network, skipping.');
  251. }
  252. $e = null;
  253. try {
  254. $this->Socket->enableCrypto('tlsv10', 'client');
  255. } catch (SocketException $e) {
  256. }
  257. $this->assertNotNull($e);
  258. // Windows doesn't return the previous exception for some reason
  259. if (DS !== '\\') {
  260. $this->assertInstanceOf('Exception', $e->getPrevious());
  261. }
  262. }
  263. /**
  264. * testEnableCryptoSocketExceptionNoTls
  265. */
  266. public function testEnableCryptoSocketExceptionNoTls(): void
  267. {
  268. $configNoSslOrTls = ['host' => 'localhost', 'port' => 80, 'timeout' => 1];
  269. // testing exception on no ssl socket server for ssl and tls methods
  270. $this->Socket = new Socket($configNoSslOrTls);
  271. try {
  272. $this->Socket->connect();
  273. } catch (SocketException $e) {
  274. $this->markTestSkipped('Cannot test network, skipping.');
  275. }
  276. $e = null;
  277. try {
  278. $this->Socket->enableCrypto('tls', 'client');
  279. } catch (SocketException $e) {
  280. }
  281. $this->assertNotNull($e);
  282. // Windows doesn't return the previous exception for some reason
  283. if (DS !== '\\') {
  284. $this->assertInstanceOf('Exception', $e->getPrevious());
  285. }
  286. }
  287. /**
  288. * Test that protocol in the host doesn't cause cert errors.
  289. */
  290. public function testConnectProtocolInHost(): void
  291. {
  292. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  293. $configSslTls = ['host' => 'ssl://smtp.gmail.com', 'port' => 465, 'timeout' => 5];
  294. $socket = new Socket($configSslTls);
  295. try {
  296. $socket->connect();
  297. $this->assertSame('smtp.gmail.com', $socket->getConfig('host'));
  298. $this->assertSame('ssl', $socket->getConfig('protocol'));
  299. } catch (SocketException $e) {
  300. $this->markTestSkipped('Cannot test network, skipping.');
  301. }
  302. }
  303. /**
  304. * _connectSocketToSslTls
  305. */
  306. protected function _connectSocketToSslTls(): void
  307. {
  308. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  309. $configSslTls = ['host' => 'smtp.gmail.com', 'port' => 465, 'timeout' => 5];
  310. $this->Socket = new Socket($configSslTls);
  311. try {
  312. $this->Socket->connect();
  313. } catch (SocketException $e) {
  314. $this->markTestSkipped('Cannot test network, skipping.');
  315. }
  316. }
  317. /**
  318. * testEnableCryptoBadMode
  319. */
  320. public function testEnableCryptoBadMode(): void
  321. {
  322. $this->expectException(InvalidArgumentException::class);
  323. // testing wrong encryption mode
  324. $this->_connectSocketToSslTls();
  325. $this->Socket->enableCrypto('doesntExistMode', 'server');
  326. $this->Socket->disconnect();
  327. }
  328. /**
  329. * testEnableCrypto
  330. */
  331. public function testEnableCrypto(): void
  332. {
  333. $this->_connectSocketToSslTls();
  334. $this->Socket->enableCrypto('tls', 'client');
  335. $result = $this->Socket->disconnect();
  336. $this->assertTrue($result);
  337. }
  338. /**
  339. * testEnableCryptoExceptionEnableTwice
  340. */
  341. public function testEnableCryptoExceptionEnableTwice(): void
  342. {
  343. $this->expectException(SocketException::class);
  344. // testing on tls server
  345. $this->_connectSocketToSslTls();
  346. $this->Socket->enableCrypto('tls', 'client');
  347. $this->Socket->enableCrypto('tls', 'client');
  348. }
  349. /**
  350. * testEnableCryptoExceptionDisableTwice
  351. */
  352. public function testEnableCryptoExceptionDisableTwice(): void
  353. {
  354. $this->expectException(SocketException::class);
  355. $this->_connectSocketToSslTls();
  356. $this->Socket->enableCrypto('tls', 'client', false);
  357. }
  358. /**
  359. * testEnableCryptoEnableStatus
  360. */
  361. public function testEnableCryptoEnableTls12(): void
  362. {
  363. $this->_connectSocketToSslTls();
  364. $this->assertFalse($this->Socket->isEncrypted());
  365. $this->Socket->enableCrypto('tlsv12', 'client', true);
  366. $this->assertTrue($this->Socket->isEncrypted());
  367. }
  368. /**
  369. * testEnableCryptoEnableStatus
  370. */
  371. public function testEnableCryptoEnableStatus(): void
  372. {
  373. $this->_connectSocketToSslTls();
  374. $this->assertFalse($this->Socket->isEncrypted());
  375. $this->Socket->enableCrypto('tls', 'client', true);
  376. $this->assertTrue($this->Socket->isEncrypted());
  377. }
  378. /**
  379. * test getting the context for a socket.
  380. */
  381. public function testGetContext(): void
  382. {
  383. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  384. $config = [
  385. 'host' => 'smtp.gmail.com',
  386. 'port' => 465,
  387. 'timeout' => 5,
  388. 'context' => [
  389. 'ssl' => ['capture_peer' => true],
  390. ],
  391. ];
  392. try {
  393. $this->Socket = new Socket($config);
  394. $this->Socket->connect();
  395. } catch (SocketException $e) {
  396. $this->markTestSkipped('No network, skipping test.');
  397. }
  398. $result = $this->Socket->context();
  399. $this->assertTrue($result['ssl']['capture_peer']);
  400. }
  401. /**
  402. * test configuring the context from the flat keys.
  403. */
  404. public function testConfigContext(): void
  405. {
  406. $this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
  407. $this->skipIf(!empty(getenv('http_proxy')) || !empty(getenv('https_proxy')), 'Proxy detected and cannot test SSL.');
  408. $config = [
  409. 'host' => 'smtp.gmail.com',
  410. 'port' => 465,
  411. 'timeout' => 5,
  412. 'ssl_verify_peer' => true,
  413. 'ssl_allow_self_signed' => false,
  414. 'ssl_verify_depth' => 5,
  415. 'ssl_verify_host' => true,
  416. ];
  417. $socket = new Socket($config);
  418. $socket->connect();
  419. $result = $socket->context();
  420. $this->assertTrue($result['ssl']['verify_peer']);
  421. $this->assertFalse($result['ssl']['allow_self_signed']);
  422. $this->assertSame(5, $result['ssl']['verify_depth']);
  423. $this->assertSame('smtp.gmail.com', $result['ssl']['CN_match']);
  424. $this->assertArrayNotHasKey('ssl_verify_peer', $socket->getConfig());
  425. $this->assertArrayNotHasKey('ssl_allow_self_signed', $socket->getConfig());
  426. $this->assertArrayNotHasKey('ssl_verify_host', $socket->getConfig());
  427. $this->assertArrayNotHasKey('ssl_verify_depth', $socket->getConfig());
  428. }
  429. /**
  430. * test connect to a unix file socket
  431. */
  432. public function testConnectToUnixFileSocket(): void
  433. {
  434. $socketName = 'unix:///tmp/test.socket';
  435. $socket = $this->getMockBuilder(Socket::class)
  436. ->onlyMethods(['_getStreamSocketClient'])
  437. ->getMock();
  438. $socket->expects($this->once())
  439. ->method('_getStreamSocketClient')
  440. ->with('unix:///tmp/test.socket', null, null, 1)
  441. ->willReturn(false);
  442. $socket->setConfig([
  443. 'host' => $socketName,
  444. 'port' => null,
  445. 'timeout' => 1,
  446. 'persistent' => true,
  447. ]);
  448. $socket->connect();
  449. }
  450. }