summaryrefslogtreecommitdiff
path: root/includes/SquidPurgeClient.php
blob: 824dd06b987a5a41085feb5f8a1177ae3f76c038 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
<?php
/**
 * Squid and Varnish cache purging.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * An HTTP 1.0 client built for the purposes of purging Squid and Varnish.
 * Uses asynchronous I/O, allowing purges to be done in a highly parallel
 * manner.
 *
 * Could be replaced by curl_multi_exec() or some such.
 */
class SquidPurgeClient {
	/** @var string */
	protected $host;

	/** @var int */
	protected $port;

	/** @var string|bool */
	protected $ip;

	/** @var string */
	protected $readState = 'idle';

	/** @var string */
	protected $writeBuffer = '';

	/** @var array */
	protected $requests = array();

	/** @var mixed */
	protected $currentRequestIndex;

	const EINTR = 4;
	const EAGAIN = 11;
	const EINPROGRESS = 115;
	const BUFFER_SIZE = 8192;

	/**
	 * @var resource|null The socket resource, or null for unconnected, or false
	 *   for disabled due to error.
	 */
	protected $socket;

	/** @var string */
	protected $readBuffer;

	/** @var int */
	protected $bodyRemaining;

	/**
	 * @param string $server
	 * @param array $options
	 */
	public function __construct( $server, $options = array() ) {
		$parts = explode( ':', $server, 2 );
		$this->host = $parts[0];
		$this->port = isset( $parts[1] ) ? $parts[1] : 80;
	}

	/**
	 * Open a socket if there isn't one open already, return it.
	 * Returns false on error.
	 *
	 * @return bool|resource
	 */
	protected function getSocket() {
		if ( $this->socket !== null ) {
			return $this->socket;
		}

		$ip = $this->getIP();
		if ( !$ip ) {
			$this->log( "DNS error" );
			$this->markDown();
			return false;
		}
		$this->socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
		socket_set_nonblock( $this->socket );
		wfSuppressWarnings();
		$ok = socket_connect( $this->socket, $ip, $this->port );
		wfRestoreWarnings();
		if ( !$ok ) {
			$error = socket_last_error( $this->socket );
			if ( $error !== self::EINPROGRESS ) {
				$this->log( "connection error: " . socket_strerror( $error ) );
				$this->markDown();
				return false;
			}
		}

		return $this->socket;
	}

	/**
	 * Get read socket array for select()
	 * @return array
	 */
	public function getReadSocketsForSelect() {
		if ( $this->readState == 'idle' ) {
			return array();
		}
		$socket = $this->getSocket();
		if ( $socket === false ) {
			return array();
		}
		return array( $socket );
	}

	/**
	 * Get write socket array for select()
	 * @return array
	 */
	public function getWriteSocketsForSelect() {
		if ( !strlen( $this->writeBuffer ) ) {
			return array();
		}
		$socket = $this->getSocket();
		if ( $socket === false ) {
			return array();
		}
		return array( $socket );
	}

	/**
	 * Get the host's IP address.
	 * Does not support IPv6 at present due to the lack of a convenient interface in PHP.
	 * @throws MWException
	 * @return string
	 */
	protected function getIP() {
		if ( $this->ip === null ) {
			if ( IP::isIPv4( $this->host ) ) {
				$this->ip = $this->host;
			} elseif ( IP::isIPv6( $this->host ) ) {
				throw new MWException( '$wgSquidServers does not support IPv6' );
			} else {
				wfSuppressWarnings();
				$this->ip = gethostbyname( $this->host );
				if ( $this->ip === $this->host ) {
					$this->ip = false;
				}
				wfRestoreWarnings();
			}
		}
		return $this->ip;
	}

	/**
	 * Close the socket and ignore any future purge requests.
	 * This is called if there is a protocol error.
	 */
	protected function markDown() {
		$this->close();
		$this->socket = false;
	}

	/**
	 * Close the socket but allow it to be reopened for future purge requests
	 */
	public function close() {
		if ( $this->socket ) {
			wfSuppressWarnings();
			socket_set_block( $this->socket );
			socket_shutdown( $this->socket );
			socket_close( $this->socket );
			wfRestoreWarnings();
		}
		$this->socket = null;
		$this->readBuffer = '';
		// Write buffer is kept since it may contain a request for the next socket
	}

	/**
	 * Queue a purge operation
	 *
	 * @param string $url
	 */
	public function queuePurge( $url ) {
		global $wgSquidPurgeUseHostHeader;
		$url = SquidUpdate::expand( str_replace( "\n", '', $url ) );
		$request = array();
		if ( $wgSquidPurgeUseHostHeader ) {
			$url = wfParseUrl( $url );
			$host = $url['host'];
			if ( isset( $url['port'] ) && strlen( $url['port'] ) > 0 ) {
				$host .= ":" . $url['port'];
			}
			$path = $url['path'];
			if ( isset( $url['query'] ) && is_string( $url['query'] ) ) {
				$path = wfAppendQuery( $path, $url['query'] );
			}
			$request[] = "PURGE $path HTTP/1.1";
			$request[] = "Host: $host";
		} else {
			$request[] = "PURGE $url HTTP/1.0";
		}
		$request[] = "Connection: Keep-Alive";
		$request[] = "Proxy-Connection: Keep-Alive";
		$request[] = "User-Agent: " . Http::userAgent() . ' ' . __CLASS__;
		// Two ''s to create \r\n\r\n
		$request[] = '';
		$request[] = '';

		$this->requests[] = implode( "\r\n", $request );
		if ( $this->currentRequestIndex === null ) {
			$this->nextRequest();
		}
	}

	/**
	 * @return bool
	 */
	public function isIdle() {
		return strlen( $this->writeBuffer ) == 0 && $this->readState == 'idle';
	}

	/**
	 * Perform pending writes. Call this when socket_select() indicates that writing will not block.
	 */
	public function doWrites() {
		if ( !strlen( $this->writeBuffer ) ) {
			return;
		}
		$socket = $this->getSocket();
		if ( !$socket ) {
			return;
		}

		if ( strlen( $this->writeBuffer ) <= self::BUFFER_SIZE ) {
			$buf = $this->writeBuffer;
			$flags = MSG_EOR;
		} else {
			$buf = substr( $this->writeBuffer, 0, self::BUFFER_SIZE );
			$flags = 0;
		}
		wfSuppressWarnings();
		$bytesSent = socket_send( $socket, $buf, strlen( $buf ), $flags );
		wfRestoreWarnings();

		if ( $bytesSent === false ) {
			$error = socket_last_error( $socket );
			if ( $error != self::EAGAIN && $error != self::EINTR ) {
				$this->log( 'write error: ' . socket_strerror( $error ) );
				$this->markDown();
			}
			return;
		}

		$this->writeBuffer = substr( $this->writeBuffer, $bytesSent );
	}

	/**
	 * Read some data. Call this when socket_select() indicates that the read buffer is non-empty.
	 */
	public function doReads() {
		$socket = $this->getSocket();
		if ( !$socket ) {
			return;
		}

		$buf = '';
		wfSuppressWarnings();
		$bytesRead = socket_recv( $socket, $buf, self::BUFFER_SIZE, 0 );
		wfRestoreWarnings();
		if ( $bytesRead === false ) {
			$error = socket_last_error( $socket );
			if ( $error != self::EAGAIN && $error != self::EINTR ) {
				$this->log( 'read error: ' . socket_strerror( $error ) );
				$this->markDown();
				return;
			}
		} elseif ( $bytesRead === 0 ) {
			// Assume EOF
			$this->close();
			return;
		}

		$this->readBuffer .= $buf;
		while ( $this->socket && $this->processReadBuffer() === 'continue' );
	}

	/**
	 * @throws MWException
	 * @return string
	 */
	protected function processReadBuffer() {
		switch ( $this->readState ) {
		case 'idle':
			return 'done';
		case 'status':
		case 'header':
			$lines = explode( "\r\n", $this->readBuffer, 2 );
			if ( count( $lines ) < 2 ) {
				return 'done';
			}
			if ( $this->readState == 'status' ) {
				$this->processStatusLine( $lines[0] );
			} else { // header
				$this->processHeaderLine( $lines[0] );
			}
			$this->readBuffer = $lines[1];
			return 'continue';
		case 'body':
			if ( $this->bodyRemaining !== null ) {
				if ( $this->bodyRemaining > strlen( $this->readBuffer ) ) {
					$this->bodyRemaining -= strlen( $this->readBuffer );
					$this->readBuffer = '';
					return 'done';
				} else {
					$this->readBuffer = substr( $this->readBuffer, $this->bodyRemaining );
					$this->bodyRemaining = 0;
					$this->nextRequest();
					return 'continue';
				}
			} else {
				// No content length, read all data to EOF
				$this->readBuffer = '';
				return 'done';
			}
		default:
			throw new MWException( __METHOD__ . ': unexpected state' );
		}
	}

	/**
	 * @param string $line
	 */
	protected function processStatusLine( $line ) {
		if ( !preg_match( '!^HTTP/(\d+)\.(\d+) (\d{3}) (.*)$!', $line, $m ) ) {
			$this->log( 'invalid status line' );
			$this->markDown();
			return;
		}
		list( , , , $status, $reason ) = $m;
		$status = intval( $status );
		if ( $status !== 200 && $status !== 404 ) {
			$this->log( "unexpected status code: $status $reason" );
			$this->markDown();
			return;
		}
		$this->readState = 'header';
	}

	/**
	 * @param string $line
	 */
	protected function processHeaderLine( $line ) {
		if ( preg_match( '/^Content-Length: (\d+)$/i', $line, $m ) ) {
			$this->bodyRemaining = intval( $m[1] );
		} elseif ( $line === '' ) {
			$this->readState = 'body';
		}
	}

	protected function nextRequest() {
		if ( $this->currentRequestIndex !== null ) {
			unset( $this->requests[$this->currentRequestIndex] );
		}
		if ( count( $this->requests ) ) {
			$this->readState = 'status';
			$this->currentRequestIndex = key( $this->requests );
			$this->writeBuffer = $this->requests[$this->currentRequestIndex];
		} else {
			$this->readState = 'idle';
			$this->currentRequestIndex = null;
			$this->writeBuffer = '';
		}
		$this->bodyRemaining = null;
	}

	/**
	 * @param string $msg
	 */
	protected function log( $msg ) {
		wfDebugLog( 'squid', __CLASS__ . " ($this->host): $msg" );
	}
}

class SquidPurgeClientPool {
	/** @var array Array of SquidPurgeClient */
	protected $clients = array();

	/** @var int */
	protected $timeout = 5;

	/**
	 * @param array $options
	 */
	function __construct( $options = array() ) {
		if ( isset( $options['timeout'] ) ) {
			$this->timeout = $options['timeout'];
		}
	}

	/**
	 * @param SquidPurgeClient $client
	 * @return void
	 */
	public function addClient( $client ) {
		$this->clients[] = $client;
	}

	public function run() {
		$done = false;
		$startTime = microtime( true );
		while ( !$done ) {
			$readSockets = $writeSockets = array();
			/**
			 * @var $client SquidPurgeClient
			 */
			foreach ( $this->clients as $clientIndex => $client ) {
				$sockets = $client->getReadSocketsForSelect();
				foreach ( $sockets as $i => $socket ) {
					$readSockets["$clientIndex/$i"] = $socket;
				}
				$sockets = $client->getWriteSocketsForSelect();
				foreach ( $sockets as $i => $socket ) {
					$writeSockets["$clientIndex/$i"] = $socket;
				}
			}
			if ( !count( $readSockets ) && !count( $writeSockets ) ) {
				break;
			}
			$exceptSockets = null;
			$timeout = min( $startTime + $this->timeout - microtime( true ), 1 );
			wfSuppressWarnings();
			$numReady = socket_select( $readSockets, $writeSockets, $exceptSockets, $timeout );
			wfRestoreWarnings();
			if ( $numReady === false ) {
				wfDebugLog( 'squid', __METHOD__ . ': Error in stream_select: ' .
					socket_strerror( socket_last_error() ) . "\n" );
				break;
			}
			// Check for timeout, use 1% tolerance since we aimed at having socket_select()
			// exit at precisely the overall timeout
			if ( microtime( true ) - $startTime > $this->timeout * 0.99 ) {
				wfDebugLog( 'squid', __CLASS__ . ": timeout ({$this->timeout}s)\n" );
				break;
			} elseif ( !$numReady ) {
				continue;
			}

			foreach ( $readSockets as $key => $socket ) {
				list( $clientIndex, ) = explode( '/', $key );
				$client = $this->clients[$clientIndex];
				$client->doReads();
			}
			foreach ( $writeSockets as $key => $socket ) {
				list( $clientIndex, ) = explode( '/', $key );
				$client = $this->clients[$clientIndex];
				$client->doWrites();
			}

			$done = true;
			foreach ( $this->clients as $client ) {
				if ( !$client->isIdle() ) {
					$done = false;
				}
			}
		}
		foreach ( $this->clients as $client ) {
			$client->close();
		}
	}
}