summaryrefslogtreecommitdiffstats
path: root/admin/WebConsole/rest/remotepc.php
blob: 5c9c7c3332e7a4c49cd3e1afae5e58deadea7bae (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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
<?php
/**
 * @file    remotepc.php
 * @brief   OpenGnsys Server REST API consumed by UDS Server for Remote PC implementation.
 * @warning All input and output messages are formatted in JSON.
 * @note    Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx.
 * @license GNU GPLv3+
 * @author  Ramón M. Gómez, ETSII Univ. Sevilla
 * @version 1.1.0 - First version
 * @date    2017-02-01
 */

// OGAgent sessions log file.
define('REMOTEPC_LOGFILE', '/opt/opengnsys/log/remotepc.log');

// Function to write a line into log file.
function writeRemotepcLog($message = "") {
        file_put_contents(REMOTEPC_LOGFILE, date(DATE_ISO8601).": $message\n", FILE_APPEND);
}


// REST routes.

/**
 * @brief    Reserve a client with an installed image and the older reservation time, then send a boot/reboot operation depending on its status.
 * @warning  If "lab" parameter is specified, then choose a client from this lab.
 * @note     Route: /ous/:ouid/images/:imageid/reserve, Method: POST
 * @param    integer ouid      OU identificator
 * @param    integer imageid   image identificator
 * @note     Input JSON message: {"labid":int_labid,"maxtime":int_hours}
 */
$app->post('/ous/:ouid/images/:imageid/reserve(/)', 'validateApiKey',
    function($ouid, $imageid) use ($app) {
	global $cmd;
	global $AMBITO_ORDENADORES;
	global $EJECUCION_COMANDO;
	global $ACCION_INICIADA;
	global $ACCION_FINALIZADA;
	global $ACCION_SINRESULTADO;
	global $ACCION_FALLIDA;
	global $userid;
	$response = [];
	$ogagent = [];
	$repo = [];

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
	// Checking parameters.
	try {
		if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
			throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
		}
		if (!checkIds($ouid, $imageid)) {
			throw new Exception("Ids. must be positive integers");
		}
		// Reading POST parameters in JSON format.
		$input = json_decode($app->request()->getBody());
		// Default: no lab. filter.
		if (isset($input->labid)) {
			$labid = $input->labid != "0" ? $input->labid : '%';
		} else {
			$labid = '%';
		}
		$maxtime = isset($input->maxtime) ? $input->maxtime : 24;	// Default: 24 h.
		$opts = Array('options' => Array('min_range' => 1));	// Check for int>0
		if (filter_var($labid, FILTER_VALIDATE_INT, $opts) === false and $labid !== '%') {
			throw new Exception("Lab id. must be positive integer");
		}
		if (filter_var($maxtime, FILTER_VALIDATE_INT, $opts) === false) {
			throw new Exception("Time must be positive integer (in hours)");
		}
	} catch (Exception $e) {
		// Communication error.
		$response["message"] = $e->getMessage();
		if ($app->settings['debug'])
			writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
		jsonResponse(400, $response);
		$app->stop();
	}

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: labid=$labid, maxtime=$maxtime");
	// Choose older not-reserved client with image installed and get ogAdmServer data.
	$cmd->texto = <<<EOD
SELECT adm.idusuario, ordenadores.idordenador, ordenadores.nombreordenador, ordenadores.ip,
       ordenadores.mac, ordenadores.mascara, ordenadores.agentkey, par.numdisk, par.numpar,
       aulas.idaula, aulas.idcentro, repo.ip AS repoip, repo.apikey AS repokey
  FROM ordenadores
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
 RIGHT JOIN ordenadores_particiones AS par USING(idordenador)
 RIGHT JOIN imagenes USING(idimagen)
 RIGHT JOIN repositorios AS repo ON repo.idrepositorio = ordenadores.idrepositorio
  LEFT JOIN remotepc ON remotepc.id=ordenadores.idordenador
 WHERE adm.idusuario = '$userid'
   AND aulas.idcentro = '$ouid' AND aulas.idaula LIKE '$labid' AND aulas.inremotepc = 1
   AND ordenadores.maintenance = 0
   AND imagenes.idimagen = '$imageid' AND imagenes.inremotepc = 1
   AND (remotepc.reserved < NOW() OR ISNULL(reserved))
 ORDER BY remotepc.reserved ASC LIMIT 1;
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);       // Error opening recordset.
	// Check if user is admin and client exists.
	$rs->Primero();
	if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
		// Read query data.
		$clntid = $rs->campos["idordenador"];
		$clntname = $rs->campos["nombreordenador"];
		$clntip = $rs->campos["ip"];
		$clntmac = $rs->campos["mac"];
		$clntnetmask = $rs->campos["mascara"];
		$agentkey = $rs->campos["agentkey"];
		$disk = $rs->campos["numdisk"];
		$part = $rs->campos["numpar"];
		$labid = $rs->campos["idaula"];
		$ouid = $rs->campos["idcentro"];
		$repoip = $rs->campos["repoip"];
		$repokey = $rs->campos["repokey"];
		// Check client's status.
		$ogagent = [['url' => "https://$clntip:8000/opengnsys/status"]];
		if ($app->settings['debug'])
			writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent status, url=".$ogagent[0]['url'].".");
		$result = multiRequest($ogagent);
		if (empty($result[0]['data'])) {
			// Client is off, send WOL command to ogAdmServer.
			// TODO: if client is busy?????
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": Send boot command through ogAdmServer: iph=$clntip,mac=$clntmac.");
			wol(1, [$clntip]);
			// Send WOL command to client repository.
			$repo = [['url' => "https://$repoip/opengnsys/rest/repository/poweron",
			          'header' => ["Authorization: $repokey"],
			          'post' => '{"macs": ["'.$clntmac.'"], "ips": ["'.$clntip.'"]}']];
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": Send Boot command through repo: repo=$repoip,ip=$clntip,mac=$clntmac.");
			$result = multiRequest($repo);
			// ... (check response)
			//if ($result[0]['code'] != 200) {
			// ...
		} else {
			// Client is on, send a reboot command to its OGAgent.
			$ogagent = [['url' => "https://$clntip:8000/opengnsys/reboot",
			             'header' => ["Authorization: ".$agentkey]]];
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent reboot, url=".$ogagent[0]['url'].".");
			$result = multiRequest($ogagent);
			// ... (check response)
			//if ($result[0]['code'] != 200) {
			// ...
		}
		// DB Transaction: mark choosed client as reserved and
		// create an init session command into client's actions queue.
		$cmd->texto = "START TRANSACTION;";
		$cmd->Ejecutar();
		$timestamp = time();
		$cmd->texto = <<<EOD
INSERT INTO remotepc
   SET id = '$clntid', reserved = NOW() + INTERVAL $maxtime HOUR,
       urllogin = NULL, urllogout = NULL, urlrelease = NULL
    ON DUPLICATE KEY UPDATE
       id = VALUES(id), reserved = VALUES(reserved),
       urllogin = VALUES(urllogin), urllogout = VALUES(urllogout),
       urlrelease = VALUES(urlrelease);
EOD;
		$t1 = $cmd->Ejecutar();
		$cmd->texto = <<<EOD
INSERT INTO acciones
   SET tipoaccion=$EJECUCION_COMANDO,
       idtipoaccion=9,
       idcomando=9,
       parametros='nfn=IniciarSesion\rdsk=$disk\rpar=$part',
       descriaccion='RemotePC Session',
       idordenador=$clntid,
       ip='$clntip',
       sesion=$timestamp,
       fechahorareg=NOW(),
       estado=$ACCION_INICIADA,
       resultado=$ACCION_SINRESULTADO,
       ambito=$AMBITO_ORDENADORES,
       idambito=$clntid,
       restrambito='$clntip',
       idcentro=$ouid;
EOD;
		$t2 = $cmd->Ejecutar();
		$id = $cmd->Autonumerico();
		create_schedule_now(strval($id),
				    $EJECUCION_COMANDO,
				    "auto-queue-remotepc-reserve-".$timestamp);
		// Create event to remove reservation on timeout (15 min.).
		$timeout = "15 MINUTE";
		$cmd->texto = <<<EOD
CREATE EVENT e_timeout_$clntid
       ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL $timeout DO
       BEGIN
	    SET @action_id = NULL;
	    UPDATE acciones
	       SET estado = $ACCION_FINALIZADA, resultado = $ACCION_FALLIDA,
		   descrinotificacion = 'Timeout'
	     WHERE descriaccion = 'RemotePC Session' AND estado = $ACCION_INICIADA
	       AND idordenador = '$clntid'
	       AND (SELECT @action_id := idaccion);
	    IF @action_id IS NOT NULL THEN
	       UPDATE remotepc
		  SET reserved = NOW() - INTERVAL 1 SECOND,
		      urllogin = NULL, urllogout = NULL, urlrelease = NULL
		WHERE id = '$clntid';
	       DELETE FROM acciones
		WHERE idaccion = @action_id;
	    END IF;
       END
EOD;
		// #839 Fixes problem of expulsion of the user from the session at 15min
		$t3=1; //$t3 = $cmd->Ejecutar();
		if ($t1 and $t2 and $t3) {
			// Commit transaction on success.
			$cmd->texto = "COMMIT;";
			$cmd->Ejecutar();
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": DB tables and events updated, clntid=$clntid.");
			// Send init session command if client is booted on ogLive.
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": Send Init Session command to ogAdmClient, ido=$clntid,iph=$clntip,dsk=$disk,par=$part.");
			session($clntip, "$disk\r$part");
			// Compose JSON response.
			$response['id'] = (int)$clntid;
			$response['name'] = $clntname;
			$response['ip'] = $clntip;
			$response['mac'] = $clntmac;
			$response['lab']['id'] = $labid;
			$response['ou']['id'] = (int)$ouid;
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": Response, ".var_export($response,true).".");
			jsonResponse(200, $response);
		} else {
			// Roll-back transaction on DB error.
			$cmd->texto = "ROLLBACK;";
			$cmd->Ejecutar();
			// Error message.
			$response["message"] = "Database error: $t1, $t2, $t3";
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
			jsonResponse(400, $response);
		}
       	} else {
		if ($app->settings['debug'])
			writeRemotepcLog($app->request()->getResourceUri(). ": UNASSIGNED");
       	}
	$rs->Cerrar();
	$app->stop();
    }
);


/**
 * @brief    Store UDS server URLs to resend some events recieved from OGAgent.
 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/events, Method: POST
 * @param    string urlLogin   URL to redirect login notification.
 * @param    string urlLogout  URL to redirect logout notification.
 * @param    string urlRelease URL to release a session
 * @warning  Events parameters will be stored in a new "remotepc" table.
 */
$app->post('/ous/:ouid/labs/:labid/clients/:clntid/events', 'validateApiKey',
    function($ouid, $labid, $clntid) use ($app) {
	global $cmd;
	global $userid;
	$response = Array();

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
	// Checking parameters.
	try {
		if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
			throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
		}
		if (!checkIds($ouid, $labid, $clntid)) {
			throw new Exception("Ids. must be positive integers");
		}
		// Reading JSON parameters.
		$input = json_decode($app->request()->getBody());
		$urlLogin = htmlspecialchars($input->urlLogin);
		$urlLogout = htmlspecialchars($input->urlLogout);
		$urlRelease = htmlspecialchars($input->urlRelease ?? "");
		if (filter_var($urlLogin, FILTER_VALIDATE_URL) === false) {
			throw new Exception("Must be a valid URL for login notification");
		}
		if (filter_var($urlLogout, FILTER_VALIDATE_URL) === false) {
			throw new Exception("Must be a valid URL for logout notification");
		}
	} catch (Exception $e) {
		// Error message.
		$response["message"] = $e->getMessage();
		if ($app->settings['debug'])
			writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
		jsonResponse(400, $response);
		$app->stop();
	}

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: urlLogin=$urlLogin, urlLogout=$urlLogout");
	// Select client data for UDS compatibility.
	$cmd->texto = <<<EOD
SELECT adm.idusuario, ordenadores.idordenador, remotepc.*
  FROM remotepc
 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
 WHERE adm.idusuario = '$userid'
   AND idcentro = '$ouid' AND aulas.idaula ='$labid'
   AND ordenadores.idordenador = '$clntid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);       // Error opening recordset.
	// Check if user is admin and client exists.
	$rs->Primero();
	if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
		// Check if client is reserved.
		if (! is_null($rs->campos["reserved"])) {
			// Updating DB if client is reserved.
			$cmd->CreaParametro("@urllogin", $urlLogin, 0);
			$cmd->CreaParametro("@urllogout", $urlLogout, 0);
			$cmd->CreaParametro("@urlrelease", $urlRelease, 0);
			$cmd->texto = <<<EOD
UPDATE remotepc
   SET urllogin = @urllogin, urllogout = @urllogout, urlrelease = NULLIF(@urlrelease, '')
 WHERE id='$clntid';
EOD;
			if ($cmd->Ejecutar()) {
				// Confirm operation.
				$response = "";
				jsonResponse(200, $response);
        		} else {
				// Error message.
				$response["message"] = "Database error";
				jsonResponse(400, $response);
			}
        	} else {
			// Error message.
			$response["message"] = "Client is not reserved";
			jsonResponse(400, $response);
        	}
        }
	$rs->Cerrar();
	$app->stop();
    }
);


/*
 * @brief    Store session time (in sec).
 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/session, Method: POST
 * @param    int    deadLine   maximum session time, in seconds (0 for unlimited)
 * @warning  Parameters will be stored in a new "remotepc" table.
 */
$app->post('/ous/:ouid/labs/:labid/clients/:clntid/session', 'validateApiKey',
    function($ouid, $labid, $clntid) use ($app) {
	global $cmd;
	global $userid;
	$response = Array();

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
	// Checking parameters.
	try {
		if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
			throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
		}
		if (!checkIds($ouid, $labid, $clntid)) {
			throw new Exception("Ids. must be positive integers");
		}
		// Reading JSON parameters.
		$input = json_decode($app->request()->getBody());
		$deadLine = $input->deadLine;
		if (filter_var($deadLine, FILTER_VALIDATE_INT) === false) {
			throw new Exception("Deadline must be integer");
		}
		if ($deadLine < 0) {
			throw new Exception("Resource unavailable");
		}
	} catch (Exception $e) {
		// Error message.
		$response["message"] = $e->getMessage();
		if ($app->settings['debug'])
			writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
		jsonResponse(400, $response);
		$app->stop();
	}

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: deadLine=$deadLine");
	// Get client's data.
	$cmd->texto = <<<EOD
SELECT adm.idusuario, ordenadores.idordenador, remotepc.*
  FROM remotepc
 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 WHERE adm.idusuario = '$userid'
   AND aulas.idcentro = '$ouid' AND aulas.idaula = '$labid'
   AND ordenadores.idordenador = '$clntid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);       // Error opening recordset.
	// Check if user is admin and client exists.
	$rs->Primero();
	if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
		// Check if client is reserved.
		if (! is_null($rs->campos["urllogin"])) {
			// Read query data.
			$clntid = $rs->campos["idordenador"];
			# Removing previous commands from OGAgent operations queue.
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": Updating database.");
			$cmd->texto = <<<EOD
DELETE FROM ogagent_queue
 WHERE clientid = '$clntid' AND operation IN ('popup-10', 'popup-5', 'poweroff');
EOD;
			$cmd->Ejecutar();
			# Add new commands to OGAgent operations queue.
			$cmd->texto = "INSERT INTO ogagent_queue (clientid, exectime, operation) VALUES";
			if ($deadLine > 600) {
				# Add reminder 10 min. before deadline.
				$cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 10 MINUTE, 'popup-10'),";
			}
			if ($deadLine > 300) {
				# Add reminder 5 min. before deadline.
				$cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 5 MINUTE, 'popup-5'),";
			}
			# Add power off command at deadline time.
			$cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND, 'poweroff');";
			if ($deadLine == 0 or $cmd->Ejecutar()) {
				// Confirm operation.
				$cmd->texto = "";
				$response = "";
				jsonResponse(200, $response);
			} else {
				// Error message.
				$response["message"] = "Database error";
				jsonResponse(400, $response);
			}
		} else {
			// Error message.
			$response["message"] = "Client is not reserved";
			jsonResponse(400, $response);
		}
	} else {
		// Error message.
		$response["message"] = "Client does not exist";
		jsonResponse(404, $response);
	}
	$rs->Cerrar();
    }
);


/**
 * @brief    Store UDS server URLs to resend some events recieved from OGAgent.
 * @brief    Unreserve a client and send a poweroff operation.
 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/unreserve, Method: DELETE
 */
$app->delete('/ous/:ouid/labs/:labid/clients/:clntid/unreserve', 'validateApiKey',
    function($ouid, $labid, $clntid) use ($app) {
	global $cmd;
	global $userid;
	global $ACCION_INICIADA;
	$response = [];
	$ogagent = [];

	if ($app->settings['debug'])
		writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
	// Checking parameters.
	try {
		if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
			throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
		}
		if (!checkIds($ouid, $labid, $clntid)) {
			throw new Exception("Ids. must be positive integers");
		}
	} catch (Exception $e) {
		// Error message.
		$response["message"] = $e->getMessage();
		if ($app->settings['debug'])
			writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
		jsonResponse(400, $response);
		$app->stop();
	}

	// Select client data for UDS compatibility.
	$cmd->texto = <<<EOD
SELECT adm.idusuario, ordenadores.idordenador, ordenadores.ip, ordenadores.agentkey, remotepc.reserved
  FROM remotepc
 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
 WHERE adm.idusuario = '$userid'
   AND idcentro = '$ouid' AND aulas.idaula ='$labid'
   AND ordenadores.idordenador = '$clntid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);       // Error opening recordset.
	// Check if user is admin and client exists.
	$rs->Primero();
	if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
		// Check if client is reserved.
		if (! is_null($rs->campos["reserved"])) {
			// Read query data.
			$clntip = $rs->campos["ip"];
			$agentkey = $rs->campos["agentkey"];
			// DB Transaction: set reservation time to the past, remove pending
			// boot commands from client's and agent's queues, and drop its event.
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": Updating database.");
			$cmd->texto = "START TRANSACTION;";
			$cmd->Ejecutar();
			$cmd->texto = <<<EOD
UPDATE remotepc
   SET reserved = NOW() - INTERVAL 1 SECOND,
       urllogin = NULL, urllogout = NULL, urlrelease = NULL
 WHERE id = '$clntid';
EOD;
			$cmd->Ejecutar();
			$cmd->texto = <<<EOD
DELETE FROM acciones
 WHERE idordenador = '$clntid'
   AND descriaccion = 'RemotePC Session';
EOD;
			$cmd->Ejecutar();
			$cmd->texto = <<<EOD
DELETE FROM ogagent_queue
 WHERE clientid = '$clntid' AND command IN ('popup-10', 'popup-5', 'poweroff');
EOD;
			$cmd->Ejecutar();
			$cmd->texto = "DROP EVENT IF EXISTS e_timeout_$clntid;";
			$cmd->Ejecutar();
			$cmd->texto = "COMMIT;";
			$cmd->Ejecutar();
			// Send a poweroff command to client's OGAgent.
			$ogagent = [['url' => "https://$clntip:8000/opengnsys/poweroff",
			             'header' => ["Authorization: ".$agentkey]]];
			if ($app->settings['debug'])
				writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent poweroff, url=".$ogagent[0]['url'].".");
			$result = multiRequest($ogagent);
			// ... (check response)
			//if ($result[0]['code'] != 200) {
			// ...
			// Confirm operation.
			$response = "";
			jsonResponse(200, $response);
		} else {
			// Error message.
			$response["message"] = "Client is not reserved";
			jsonResponse(400, $response);
		}
	} else {
		// Error message.
		$response["message"] = "Client does not exist";
		jsonResponse(404, $response);
	}
	$rs->Cerrar();
    }
);


/*
 * @brief    Send an init operation to a client with an image installed.
 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/init, Method: POST
 * @param    int    image   Image id.
 */
$app->post('/ous/:ouid/labs/:labid/clients/:clntid/init', 'validateApiKey',
    function($ouid, $labid, $clntid) use ($app) {
        global $cmd;
        global $userid;
        global $AMBITO_ORDENADORES;
        global $EJECUCION_COMANDO;
        global $ACCION_INICIADA;
        global $ACCION_FINALIZADA;
        global $ACCION_SINRESULTADO;
        global $ACCION_FALLIDA;

	if ($app->settings['debug'])
		writeRemotepcLog("{$app->request()->getResourceUri()}: Init.");
	// Checking parameters.
	try {
		if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
			throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
		}
		if (!checkIds($ouid, $labid, $clntid)) {
			throw new Exception("Ids. must be positive integers");
		}
		// Reading POST parameters in JSON format.
		$input = json_decode($app->request()->getBody());
		$imageid = $input->image ?? 0;
		$opts = Array('options' => Array('min_range' => 1));    // Check for int>0
		if (filter_var($imageid, FILTER_VALIDATE_INT, $opts) === false) {
			throw new Exception("Image id. must be positive integer");
		}
	} catch (Exception $e) {
		// Communication error.
		$response["message"] = $e->getMessage();
		if ($app->settings['debug'])
			writeRemotepcLog("{$app->request()->getResourceUri()}: ERROR: {$response["message"]}.");
		jsonResponse(400, $response);
		$app->stop();
	}

	// Select data to init a session.
	$cmd->texto = <<<EOD
SELECT adm.idusuario, ordenadores.idordenador, ordenadores.ip, ordenadores.mac, ordenadores.mascara, ordenadores.agentkey,
       par.numdisk, par.numpar, repo.ip AS repoip, repo.apikey AS repokey
  FROM ordenadores
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
 RIGHT JOIN ordenadores_particiones AS par USING(idordenador)
 RIGHT JOIN imagenes USING(idimagen)
 RIGHT JOIN repositorios AS repo ON repo.idrepositorio = ordenadores.idrepositorio
  LEFT JOIN remotepc ON remotepc.id=ordenadores.idordenador
 WHERE adm.idusuario = '$userid'
   AND aulas.idcentro = '$ouid' AND aulas.idaula LIKE '$labid'
   AND ordenadores.idordenador = '$clntid' AND ordenadores.maintenance = 0
   AND imagenes.idimagen = '$imageid'
 LIMIT 1;
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);       // Error opening recordset.
	// Check if user is admin and client exists.
	$rs->Primero();
	if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
		// Read query data.
		$clntip = $rs->campos["ip"];
		$clntmac = $rs->campos["mac"];
		$clntnetmask = $rs->campos["mascara"];
		$agentkey = $rs->campos["agentkey"];
		$disk = $rs->campos["numdisk"];
		$part = $rs->campos["numpar"];
		$repoip = $rs->campos["repoip"];
		$repokey = $rs->campos["repokey"];
		// Check client's status.
		$ogagent = [['url' => "https://$clntip:8000/opengnsys/status"]];
		if ($app->settings['debug'])
			writeRemotepcLog("{$app->request()->getResourceUri()}: OGAgent status, url={$ogagent[0]['url']}.");
		$result = multiRequest($ogagent);
		if (empty($result[0]['data'])) {
			// Client is off, send WOL command to ogAdmServer.
			// TODO: if client is busy?????
			if ($app->settings['debug'])
				writeRemotepcLog("{$app->request()->getResourceUri()}: Send boot command through ogAdmServer: iph=$clntip,mac=$clntmac.");
			wol(1, [$clntip]);
			// Send WOL command to client repository.
			$repo = [['url' => "https://$repoip/opengnsys/rest/repository/poweron",
			          'header' => ["Authorization: $repokey"],
			          'post' => '{"macs": ["'.$clntmac.'"], "ips": ["'.$clntip.'"]}']];
			if ($app->settings['debug'])
				writeRemotepcLog("{$app->request()->getResourceUri()}: Send Boot command through repo: repo=$repoip,ip=$clntip,mac=$clntmac.");
			$result = multiRequest($repo);
		}
		// Create an init session on opertions queue.
		$timestamp = time();
		$cmd->texto = <<<EOD
INSERT INTO acciones
   SET tipoaccion=$EJECUCION_COMANDO,
       idtipoaccion=9,
       idcomando=9,
       parametros='nfn=IniciarSesion\rdsk=$disk\rpar=$part',
       descriaccion='RemotePC Session',
       idordenador=$clntid,
       ip='$clntip',
       sesion=$timestamp,
       fechahorareg=NOW(),
       estado=$ACCION_INICIADA,
       resultado=$ACCION_SINRESULTADO,
       ambito=$AMBITO_ORDENADORES,
       idambito=$clntid,
       restrambito='$clntip',
       idcentro=$ouid;
EOD;
		$cmd->Ejecutar();
		$id = $cmd->Autonumerico();
		create_schedule_now(strval($id),
				    $EJECUCION_COMANDO,
				    "auto-queue-remotepc-init-".$timestamp);
		// Create event to remove the operation on timeout (15 min.).
		$timeout = "15 MINUTE";
		$cmd->texto = <<<EOD
CREATE EVENT IF NOT EXISTS e_timeout_$clntid
       ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL $timeout DO
       BEGIN
	    SET @action_id = NULL;
	    UPDATE acciones
	       SET estado = $ACCION_FINALIZADA, resultado = $ACCION_FALLIDA,
		   descrinotificacion = 'Timeout'
	     WHERE descriaccion = 'RemotePC Session' AND estado = $ACCION_INICIADA
	       AND idordenador = '$clntid'
	       AND (SELECT @action_id := idaccion);
	    IF @action_id IS NOT NULL THEN
	       DELETE FROM acciones
		WHERE idaccion = @action_id;
	    END IF;
       END
EOD;
		//$cmd->Ejecutar();
		if ($app->settings['debug'])
			writeRemotepcLog("{$app->request()->getResourceUri()}: DB tables and events updated, clntid=$clntid.");
		// Send init session command if client is booted on ogLive.
		if ($app->settings['debug'])
			writeRemotepcLog("{$app->request()->getResourceUri()}: Send Init Session command to ogAdmClient, ido=$clntid,iph=$clntip,dsk=$disk,par=$part.");
		session($clntip, "$disk\r$part");
		// Confirm operation.
		$response = [];
		jsonResponse(200, $response);
	} else {
		// Error message.
		$response["message"] = "Client with this image not found";
		jsonResponse(404, $response);
	}
	$rs->Cerrar();
    }
);