-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCgiRunner.php
More file actions
327 lines (297 loc) · 11.8 KB
/
CgiRunner.php
File metadata and controls
327 lines (297 loc) · 11.8 KB
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
<?php
declare(strict_types=1);
namespace PhpSchool\PhpWorkshop\ExerciseRunner;
use GuzzleHttp\Psr7\Message;
use PhpSchool\PhpWorkshop\Check\CodeExistsCheck;
use PhpSchool\PhpWorkshop\Check\CodeParseCheck;
use PhpSchool\PhpWorkshop\Check\FileExistsCheck;
use PhpSchool\PhpWorkshop\Check\PhpLintCheck;
use PhpSchool\PhpWorkshop\Event\CgiExecuteEvent;
use PhpSchool\PhpWorkshop\Event\CgiExerciseRunnerEvent;
use PhpSchool\PhpWorkshop\Event\Event;
use PhpSchool\PhpWorkshop\Event\EventDispatcher;
use PhpSchool\PhpWorkshop\Event\ExerciseRunnerEvent;
use PhpSchool\PhpWorkshop\Exception\CodeExecutionException;
use PhpSchool\PhpWorkshop\Exception\SolutionExecutionException;
use PhpSchool\PhpWorkshop\Exercise\CgiExercise;
use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
use PhpSchool\PhpWorkshop\Input\Input;
use PhpSchool\PhpWorkshop\Output\OutputInterface;
use PhpSchool\PhpWorkshop\Process\ProcessFactory;
use PhpSchool\PhpWorkshop\Process\ProcessInput;
use PhpSchool\PhpWorkshop\Result\Cgi\CgiResult;
use PhpSchool\PhpWorkshop\Result\Cgi\RequestFailure;
use PhpSchool\PhpWorkshop\Result\Cgi\GenericFailure;
use PhpSchool\PhpWorkshop\Result\Cgi\Success;
use PhpSchool\PhpWorkshop\Result\Cgi\ResultInterface as CgiResultInterface;
use PhpSchool\PhpWorkshop\Result\ResultInterface;
use PhpSchool\PhpWorkshop\Utils\RequestRenderer;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
use function PHPStan\dumpType;
/**
* The `CGI` runner. This runner executes solutions as if they were behind a web-server. They populate the `$_SERVER`,
* `$_GET` & `$_POST` super globals with information based of the request objects returned from the exercise.
*/
class CgiRunner implements ExerciseRunnerInterface
{
/**
* @var array<class-string>
*/
private static array $requiredChecks = [
FileExistsCheck::class,
CodeExistsCheck::class,
PhpLintCheck::class,
CodeParseCheck::class,
];
/**
* Requires the exercise instance and an event dispatcher. This runner requires the `php-cgi` binary to
* be available. It will check for it's existence in the system's $PATH variable or the same
* folder that the CLI php binary lives in.
*
* @param CgiExercise&ExerciseInterface $exercise The exercise to be invoked.
*/
public function __construct(
private CgiExercise $exercise,
private EventDispatcher $eventDispatcher,
private ProcessFactory $processFactory
) {
}
/**
* @return string
*/
public function getName(): string
{
return 'CGI Program Runner';
}
/**
* Get an array of the class names of the required checks this runner needs.
*
* @return array<class-string>
*/
public function getRequiredChecks(): array
{
return self::$requiredChecks;
}
/**
* Verifies a solution by invoking PHP via the `php-cgi` binary, populating all the super globals with
* the information from the request objects returned from the exercise. The exercise can return multiple
* requests so the solution will be invoked for however many requests there are.
*
* Events dispatched (for each request):
*
* * cgi.verify.reference-execute.pre
* * cgi.verify.reference.executing
* * cgi.verify.reference-execute.fail (if the reference solution fails to execute)
* * cgi.verify.student-execute.pre
* * cgi.verify.student.executing
* * cgi.verify.student-execute.fail (if the student's solution fails to execute)
*
* @param Input $input The command line arguments passed to the command.
* @return CgiResult The result of the check.
*/
public function verify(Input $input): ResultInterface
{
$this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.verify.start', $this->exercise, $input));
$result = new CgiResult(
array_map(
function (RequestInterface $request) use ($input) {
return $this->doVerify($request, $input);
},
$this->exercise->getRequests()
)
);
$this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.verify.finish', $this->exercise, $input));
return $result;
}
private function doVerify(RequestInterface $request, Input $input): CgiResultInterface
{
try {
/** @var CgiExecuteEvent $event */
$event = $this->eventDispatcher->dispatch(
new CgiExecuteEvent('cgi.verify.reference-execute.pre', $this->exercise, $input, $request)
);
$solutionResponse = $this->executePhpFile(
$input,
$this->exercise->getSolution()->getEntryPoint()->getAbsolutePath(),
$event->getRequest(),
'reference'
);
} catch (CodeExecutionException $e) {
$this->eventDispatcher->dispatch(
new CgiExecuteEvent(
'cgi.verify.reference-execute.fail',
$this->exercise,
$input,
$request,
['exception' => $e]
)
);
throw new SolutionExecutionException($e->getMessage());
}
try {
/** @var CgiExecuteEvent $event */
$event = $this->eventDispatcher->dispatch(
new CgiExecuteEvent('cgi.verify.student-execute.pre', $this->exercise, $input, $request)
);
$userResponse = $this->executePhpFile(
$input,
$input->getRequiredArgument('program'),
$event->getRequest(),
'student'
);
} catch (CodeExecutionException $e) {
$this->eventDispatcher->dispatch(
new CgiExecuteEvent(
'cgi.verify.student-execute.fail',
$this->exercise,
$input,
$request,
['exception' => $e]
)
);
return GenericFailure::fromRequestAndCodeExecutionFailure($request, $e);
}
$solutionBody = (string) $solutionResponse->getBody();
$userBody = (string) $userResponse->getBody();
$solutionHeaders = $this->getHeaders($solutionResponse);
$userHeaders = $this->getHeaders($userResponse);
if ($solutionBody !== $userBody || $solutionHeaders !== $userHeaders) {
return new RequestFailure($request, $solutionBody, $userBody, $solutionHeaders, $userHeaders);
}
return new Success($request);
}
/**
* @param ResponseInterface $response
* @return array<string,string>
*/
private function getHeaders(ResponseInterface $response): array
{
$headers = [];
foreach ($response->getHeaders() as $name => $values) {
$headers[$name] = implode(", ", $values);
}
return $headers;
}
/**
* @param string $fileName
* @param RequestInterface $request
* @param string $type
* @return ResponseInterface
*/
private function executePhpFile(
Input $input,
string $fileName,
RequestInterface $request,
string $type
): ResponseInterface {
$process = $this->getPhpProcess(dirname($fileName), basename($fileName), $request);
$process->start();
$this->eventDispatcher->dispatch(
new CgiExecuteEvent(sprintf('cgi.verify.%s.executing', $type), $this->exercise, $input, $request)
);
$process->wait();
if (!$process->isSuccessful()) {
throw CodeExecutionException::fromProcess($process);
}
//if no status line, pre-pend 200 OK
$output = $process->getOutput();
if (!preg_match('/^HTTP\/([1-9]\d*\.\d) ([1-5]\d{2})(\s+(.+))?\\r\\n/', $output)) {
$output = "HTTP/1.0 200 OK\r\n" . $output;
}
return Message::parseResponse($output);
}
/**
* @param string $fileName
* @param RequestInterface $request
* @return Process
*/
private function getPhpProcess(string $workingDirectory, string $fileName, RequestInterface $request): Process
{
$env = [
'REQUEST_METHOD' => $request->getMethod(),
'SCRIPT_FILENAME' => $fileName,
'REDIRECT_STATUS' => '302',
'QUERY_STRING' => $request->getUri()->getQuery(),
'REQUEST_URI' => $request->getUri()->getPath(),
'XDEBUG_MODE' => 'off',
];
$content = $request->getBody()->__toString();
$env['CONTENT_LENGTH'] = (string) $request->getBody()->getSize();
$env['CONTENT_TYPE'] = $request->getHeaderLine('Content-Type');
foreach ($request->getHeaders() as $name => $values) {
$env[sprintf('HTTP_%s', strtoupper($name))] = implode(", ", $values);
}
$processInput = new ProcessInput(
'php-cgi',
[
'-dalways_populate_raw_post_data=-1',
'-dhtml_errors=0',
'-dexpose_php=0',
],
$workingDirectory,
$env,
$content
);
return $this->processFactory->create($processInput);
}
/**
* Runs a student's solution by invoking PHP via the `php-cgi` binary, populating all the super globals with
* the information from the request objects returned from the exercise. The exercise can return multiple
* requests so the solution will be invoked for however many requests there are.
*
* Running only runs the student's solution, the reference solution is not run and no verification is performed,
* the output of the student's solution is written directly to the output.
*
* Events dispatched (for each request):
*
* * cgi.run.student-execute.pre
* * cgi.run.student.executing
*
* @param Input $input The command line arguments passed to the command.
* @param OutputInterface $output A wrapper around STDOUT.
* @return bool If the solution was successfully executed, eg. exit code was 0.
*/
public function run(Input $input, OutputInterface $output): bool
{
$this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.run.start', $this->exercise, $input));
$success = true;
foreach ($this->exercise->getRequests() as $i => $request) {
/** @var CgiExecuteEvent $event */
$event = $this->eventDispatcher->dispatch(
new CgiExecuteEvent('cgi.run.student-execute.pre', $this->exercise, $input, $request)
);
$process = $this->getPhpProcess(
dirname($input->getRequiredArgument('program')),
$input->getRequiredArgument('program'),
$event->getRequest()
);
$process->start();
$this->eventDispatcher->dispatch(
new CgiExecuteEvent(
'cgi.run.student.executing',
$this->exercise,
$input,
$request,
['output' => $output]
)
);
$process->wait(function ($outputType, $outputBuffer) use ($output) {
$output->write($outputBuffer);
});
$output->emptyLine();
if (!$process->isSuccessful()) {
$success = false;
}
$output->lineBreak();
$this->eventDispatcher->dispatch(
new CgiExecuteEvent('cgi.run.student-execute.post', $this->exercise, $input, $request)
);
}
$this->eventDispatcher->dispatch(new CgiExerciseRunnerEvent('cgi.run.finish', $this->exercise, $input));
return $success;
}
}