source: admin/WebConsole/rest/ogagent.php @ 7e8132af

Last change on this file since 7e8132af was e98bdbc, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#992: Release a reserved client if a user logs in a local session.

  • Property mode set to 100644
File size: 10.4 KB
Line 
1<?php
2/**
3 * @file    ogagent.php
4 * @brief   OpenGnsys REST routes for OGAgent communications.
5 * @warning All input and output messages are formatted in JSON.
6 * @note    Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx.
7 * @license GNU GPLv3+
8 * @author  Ramón M. Gómez, ETSII Univ. Sevilla
9 * @version 1.1.0 - First version
10 * @date    2016-10-03
11 */
12
13
14// OGAgent sessions log file.
15define('LOG_FILE', '/opt/opengnsys/log/ogagent.log');
16
17// Function to write a line into log file.
18function writeLog($message = "") {
19        file_put_contents(LOG_FILE, date(DATE_ISO8601).": $message\n", FILE_APPEND);
20}
21
22/**
23 * @brief    OGAgent notifies that its service is started on a client.
24 * @note     Route: /ogagent/started, Method: POST, Format: JSON
25 * @param    string ip         IP address
26 * @param    string mac        MAC (Ethernet) address
27 * @param    string ostype     OS type (Linux, Windows, macOS)
28 * @param    string osversion  OS version
29 * @param    string secret     random secret key to access client's REST API
30 * @return   Null string if OK, else error message.
31 */
32$app->post('/ogagent/started',
33    function() use ($app) {
34        global $cmd;
35        $secret = "";
36        $osType = $osVersion = "none";
37        try {
38                // Reading POST parameters in JSON format.
39                $input = json_decode($app->request()->getBody());
40                $ip = htmlspecialchars($input->ip);
41                $mac = htmlspecialchars($input->mac);
42                if (isset($input->ostype))  $osType = htmlspecialchars($input->ostype);
43                if (isset($input->osversion))  $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion));
44                // Check sender agent type and IP address consistency (same as parameter value).
45                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
46                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
47                }
48                // Client secret key for secure communications.
49                if (isset($input->secret)) {
50                    // Check if secret key is valid (32 alphanumeric characters).
51                    if (! ctype_alnum($input->secret) or strlen($input->secret) !== 32) {
52                        throw new Exception("Bad secret key: ip=$ip, mac=$mac, os=$osType:$osVersion.");
53                    }
54                    // Store secret key in DB.
55                    if (isset($input->secret))  $secret = htmlspecialchars($input->secret);
56                    $cmd->texto = <<<EOD
57UPDATE ordenadores
58   SET agentkey='$secret'
59 WHERE ip='$ip' AND mac=UPPER(REPLACE('$mac', ':', ''))
60 LIMIT 1;
61EOD;
62                    if ($cmd->Ejecutar() !== true or mysqli_affected_rows($cmd->Conexion->controlador) !== 1) {
63                        // DB access error or not updated.
64                        throw new Exception("Cannot store new secret key: ip=$ip, mac=$mac, os=$osType:$osVersion.");
65                    }
66                } else {
67                    // Insecure agent exception.
68                    throw new Exception("Insecure OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion.");
69                }
70                // Default processing: log activity.
71                writeLog("OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion.");
72                // Response.
73                $response = "";
74                jsonResponse(200, $response);
75        } catch (Exception $e) {
76                // Communication error.
77                $response["message"] = $e->getMessage();
78                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
79                jsonResponse(400, $response);
80        }
81    }
82);
83
84/**
85 * @brief    OGAgent notifies that its service is stopped on client.
86 * @note     Route: /ogagent/stopped, Method: POST, Format: JSON
87 * @param    string ip         IP address
88 * @param    string mac        MAC (Ethernet) address
89 * @param    string ostype     OS type (Linux, Windows, macOS)
90 * @param    string osversion  OS version
91 * @return   Null string if OK, else error message.
92 */
93$app->post('/ogagent/stopped',
94    function() use ($app) {
95        $osType = $osVersion = "none";
96        try {
97                // Reading POST parameters in JSON format.
98                $input = json_decode($app->request()->getBody());
99                $ip = htmlspecialchars($input->ip);
100                $mac = htmlspecialchars($input->mac);
101                if (isset($input->ostype))  $osType = htmlspecialchars($input->ostype);
102                if (isset($input->osversion))  $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion));
103                // Check sender agent type and IP address consistency (same as parameter value).
104                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
105                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
106                }
107                // May check if client is included in the server database?
108                // Default processing: log activity.
109                writeLog("OGAgent stopped: ip=$ip, mac=$mac, os=$osType:$osVersion.");
110                // Response.
111                $response = "";
112                jsonResponse(200, $response);
113        } catch (Exception $e) {
114                // Communication error.
115                $response["message"] = $e->getMessage();
116                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
117                jsonResponse(400, $response);
118        }
119    }
120);
121
122/**
123 * @brief    OGAgent notifies that an user logs in.
124 * @note     Route: /ogagent/loggedin, Method: POST, Format: JSON
125 * @param    string ip         IP address
126 * @param    string user       username
127 * @param    string language   session language
128 * @param    string ostype     OS type (Linux, Windows, macOS)
129 * @param    string osversion  OS version
130 * @return   Null string if OK, else error message.
131 */
132$app->post('/ogagent/loggedin',
133    function() use ($app) {
134        global $cmd;
135        $redirto = Array();
136        $result = Array();
137
138        try {
139                // Reading POST parameters in JSON format.
140                $input = json_decode($app->request()->getBody());
141                $ip = htmlspecialchars($input->ip);
142                $user = htmlspecialchars($input->user);
143                // Remote session contains "rdp", else it's local.
144                if (strpos($input->session ?? "", "rdp") !== false) {
145                        $session = "remote";
146                } else {
147                        $session = "local";
148                }
149                $language = strstr($input->language ?? "", "_", true);
150                $osType = htmlspecialchars($input->ostype ?? "none");
151                $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion ?? "none"));
152                // Check sender IP address consistency (same as parameter value).
153                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
154                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
155                }
156                // Check if client is included in the server database.
157                $cmd->CreaParametro("@ip", $ip, 0);
158                $cmd->texto = <<<EOD
159SELECT ordenadores.idordenador, ordenadores.nombreordenador, remotepc.urllogin,
160       remotepc.urlrelease, remotepc.reserved > NOW() AS reserved
161  FROM remotepc
162 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
163 WHERE ordenadores.ip=@ip
164 LIMIT 1;
165EOD;
166                $rs=new Recordset;
167                $rs->Comando=&$cmd;
168                if ($rs->Abrir()) {
169                        // Read query data.
170                        $rs->Primero();
171                        $id = $rs->campos['idordenador'];
172                        $sendlogin[0]['url'] = $rs->campos['urllogin'];
173                        $sendrel[0]['url'] = $rs->campos['urlrelease'];
174                        $reserved = $rs->campos['reserved'];
175                        $rs->Cerrar();
176                        if (!is_null($id)) {
177                                // Log activity, respond to client and continue processing.
178                                writeLog("User logged in: ip=$ip, user=$user, lang=$language, os=$osType:$osVersion.");
179                                $response = "";
180                                jsonResponseNow(200, $response);
181                        } else {
182                                throw new Exception("Client is not in the database: ip=$ip, user=$user");
183                        }
184                        // Redirect notification to UDS server, if needed.
185                        if ($reserved == 1 and !is_null($sendlogin[0]['url'])) {
186                                $sendlogin[0]['get'] = $app->request()->getBody();
187                                $result = multiRequest($sendlogin);
188                                // ... (check response)
189                                //if ($result[0]['code'] != 200) {
190                                // ...
191                                // Updating user's session language for messages.
192                                $cmd->texto = <<<EOD
193UPDATE remotepc
194   SET language = '$language'
195 WHERE id = '$id';
196EOD;
197                                $cmd->Ejecutar();
198                        }
199                        // Release a reserved client if a user opens a local session.
200                        if ($reserved == 1 and $session === "local" and ! is_null($sendrel[0]['url'])) {
201                                $result = multiRequest($sendrel);
202                        }
203                } else {
204                        throw new Exception("Database error");
205                }
206        } catch (Exception $e) {
207                // Communication error.
208                $response["message"] = $e->getMessage();
209                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
210                jsonResponse(400, $response);
211        }
212    }
213);
214
215/**
216 * @brief    OGAgent notifies that an user logs out.
217 * @note     Route: /ogagent/loggedout, Method: POST, Format: JSON
218 * @param    string ip         IP address
219 * @param    string user       username
220 * @return   Null string if OK, else error message.
221 */
222$app->post('/ogagent/loggedout',
223    function() use ($app) {
224        global $cmd;
225        $redirto = Array();
226        $result = Array();
227
228        try {
229                // Reading POST parameters in JSON format.
230                $input = json_decode($app->request()->getBody());
231                $ip = htmlspecialchars($input->ip);
232                $user = htmlspecialchars($input->user);
233                // Check sender agent type and IP address consistency (same as parameter value).
234                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
235                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
236                }
237                // Check if client is included in the server database.
238                $cmd->CreaParametro("@ip", $ip, 0);
239                $cmd->texto = <<<EOD
240SELECT ordenadores.idordenador, ordenadores.nombreordenador, remotepc.urllogout,
241       remotepc.reserved > NOW() AS reserved
242  FROM remotepc
243 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
244 WHERE ordenadores.ip=@ip
245 LIMIT 1;
246EOD;
247                $rs=new Recordset;
248                $rs->Comando=&$cmd;
249                if ($rs->Abrir()) {
250                        // Read query data.
251                        $rs->Primero();
252                        $id = $rs->campos['idordenador'];
253                        $url = $rs->campos['urllogout'];
254                        $reserved = $rs->campos['reserved'];
255                        $rs->Cerrar();
256                        if (!is_null($id)) {
257                                // Log activity, respond to client and continue processing.
258                                writeLog("User logged out: ip=$ip, user=$user.");
259                        } else {
260                                throw new Exception("Client is not in the database: ip=$ip, user=$user");
261                        }
262                        // Redirect notification to UDS server, if needed.
263                        if ($reserved == 1 and !is_null($url)) {
264                                $redirto[0]['url'] = $url;
265                                $redirto[0]['get'] = $app->request()->getBody();
266                                $result = multiRequest($redirto);
267                                // ... (check response)
268                                //if ($result[0]['code'] != 200) {
269                                // ...
270                        }
271                } else {
272                        throw new Exception("Database error");
273                }
274        } catch (Exception $e) {
275                // Communication error.
276                $response["message"] = $e->getMessage();
277                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
278                jsonResponse(400, $response);
279        }
280        $response = "";
281        jsonResponse(200, $response);
282    }
283);
284
285
Note: See TracBrowser for help on using the repository browser.