source: admin/WebConsole/rest/ogagent.php @ 43b6d0b

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 43b6d0b was b942930, checked in by ramon <ramongomez@…>, 8 years ago

#708: Redirigir operación de logout a servidor UDS y dejar de usar reintentos de conexión (Slim espera hasta el final para enviar la respuesta).

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5188 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100644
File size: 8.6 KB
RevLine 
[b1735a7]1<?php
[8f3c218]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 */
[b1735a7]12
13
14// OGAgent sessions log file.
15define('LOG_FILE', '/opt/opengnsys/log/ogagent.log');
16
[8f3c218]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
[a9140b0]22/**
23 * @brief    OGAgent notifies that its service is started on a client.
[21e5ee3]24 * @note     Route: /ogagent/started, Method: POST, Format: JSON
[a9140b0]25 * @param    string ip         IP address
26 * @param    string mac        MAC (Ethernet) address
27 * @param    string ostype     OS type (Linux, Windows)
[21e5ee3]28 * @param    string osversion  OS version
[a9140b0]29 * @param    string secret     random secret key to access client's REST API
30 * @return   Null string if OK, else error message.
31 */
[b1735a7]32$app->post('/ogagent/started',
33    function() use ($app) {
[2913439]34        global $cmd;
35        $osType = $osVersion = "none";
[b1735a7]36        try {
37                // Reading POST parameters in JSON format.
38                $input = json_decode($app->request()->getBody());
39                $ip = htmlspecialchars($input->ip);
40                $mac = htmlspecialchars($input->mac);
[31970a0]41                if (isset($input->ostype))  $osType = htmlspecialchars($input->ostype);
42                if (isset($input->osversion))  $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion));
[21e5ee3]43                // Check sender agent type and IP address consistency (same as parameter value).
44                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
45                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
[a9140b0]46                }
[210ee85]47                // Client secret key for secure communications.
48                if (isset($input->secret)) {
[a9140b0]49                    // Check if secret key is valid (32 alphanumeric characters).
50                    if (! ctype_alnum($input->secret) or strlen($input->secret) !== 32) {
51                        throw new Exception("Bad secret key: ip=$ip, mac=$mac, os=$osType:$osVersion.");
52                    }
[210ee85]53                    // Store secret key in DB.
[f6045a5]54                    if (isset($input->secret))  $secret = htmlspecialchars($input->secret);
[2913439]55                    $cmd->texto = "UPDATE ordenadores
56                                      SET agentkey='$secret'
[a9140b0]57                                    WHERE ip='$ip' AND mac=UPPER(REPLACE('$mac',':',''))
58                                    LIMIT 1";
59                    if ($cmd->Ejecutar() !== true or mysql_affected_rows() !== 1) {
60                        // DB access error or not updated.
61                        throw new Exception("Cannot store new secret key: ip=$ip, mac=$mac, os=$osType:$osVersion.");
[2913439]62                    }
[210ee85]63                } else {
64                    // Insecure agent exception.
[31970a0]65                    throw new Exception("Insecure OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion.");
[210ee85]66                }
[b1735a7]67                // Default processing: log activity.
[8f3c218]68                writeLog("OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion.");
[b1735a7]69                // Response.
[d98bc86]70                $response = "";
[b1735a7]71                jsonResponse(200, $response);
72        } catch (Exception $e) {
73                // Comunication error.
74                $response["message"] = $e->getMessage();
[8f3c218]75                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
[b1735a7]76                jsonResponse(400, $response);
77        }
78    }
79);
80
[21e5ee3]81/**
82 * @brief    OGAgent notifies that its service is stopped on client.
83 * @note     Route: /ogagent/stopped, Method: POST, Format: JSON
84 * @param    string ip         IP address
85 * @param    string mac        MAC (Ethernet) address
86 * @param    string ostype     OS type (Linux, Windows)
87 * @param    string osversion  OS version
88 * @return   Null string if OK, else error message.
89 */
[b1735a7]90$app->post('/ogagent/stopped',
91    function() use ($app) {
[2913439]92        $osType = $osVersion = "none";
[b1735a7]93        try {
94                // Reading POST parameters in JSON format.
95                $input = json_decode($app->request()->getBody());
96                $ip = htmlspecialchars($input->ip);
97                $mac = htmlspecialchars($input->mac);
[31970a0]98                if (isset($input->ostype))  $osType = htmlspecialchars($input->ostype);
99                if (isset($input->osversion))  $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion));
[21e5ee3]100                // Check sender agent type and IP address consistency (same as parameter value).
101                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
102                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
[a9140b0]103                }
104                // May check if client is included in the server database?
[b1735a7]105                // Default processing: log activity.
[8f3c218]106                writeLog("OGAgent stopped: ip=$ip, mac=$mac, os=$osType:$osVersion.");
[b1735a7]107                // Response.
[d98bc86]108                $response = "";
[b1735a7]109                jsonResponse(200, $response);
110        } catch (Exception $e) {
111                // Comunication error.
112                $response["message"] = $e->getMessage();
[8f3c218]113                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
[b1735a7]114                jsonResponse(400, $response);
115        }
116    }
117);
118
[21e5ee3]119/**
120 * @brief    OGAgent notifies that an user logs in.
121 * @note     Route: /ogagent/loggedin, Method: POST, Format: JSON
122 * @param    string ip         IP address
123 * @param    string user       username
124 * @return   Null string if OK, else error message.
125 */
[b1735a7]126$app->post('/ogagent/loggedin',
127    function() use ($app) {
[8f3c218]128        global $cmd;
129        $redirto = Array();
130        $result = Array();
131
[b1735a7]132        try {
133                // Reading POST parameters in JSON format.
134                $input = json_decode($app->request()->getBody());
135                $ip = htmlspecialchars($input->ip);
136                $user = htmlspecialchars($input->user);
[a9140b0]137                // Check sender IP address consistency (same as parameter value).
[21e5ee3]138                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
139                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
[a9140b0]140                }
[8f3c218]141                // Log activity and respond to client.
142                writeLog("User logged in: ip=$ip, user=$user.");
[d98bc86]143                $response = "";
[b1735a7]144                jsonResponse(200, $response);
[8f3c218]145                // Check if client is included in the server database.
146                $cmd->texto = <<<EOD
147SELECT ordenadores.idordenador, ordenadores.ip, remotepc.urllogin
148  FROM remotepc
149 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
150 WHERE ordenadores.ip = '$ip'
151 LIMIT 1;
152EOD;
153                $rs=new Recordset;
154                $rs->Comando=&$cmd;
155                if ($rs->Abrir()) {
156                        // Read query data.
157                        $rs->Primero();
158                        $redirto[0]['url'] = $rs->campos['urllogin'];
159                        $rs->Cerrar();
160                        if (!is_null($redirto[0]['url'])) {
161                                // Redirect notification to UDS server, if needed.
162                                $redirto[0]['post'] = $app->request()->getBody();
163                                $result = multiRequest($redirto);
[b942930]164                                // ... (check response)
165                                //if ($result[0]['code'] != 200) {
166                                // ...
[8f3c218]167                        }
168                }
[b1735a7]169        } catch (Exception $e) {
170                // Comunication error.
171                $response["message"] = $e->getMessage();
[8f3c218]172                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
[b1735a7]173                jsonResponse(400, $response);
174        }
175    }
176);
177
[21e5ee3]178/**
179 * @brief    OGAgent notifies that an user logs out.
180 * @note     Route: /ogagent/loggedout, Method: POST, Format: JSON
181 * @param    string ip         IP address
182 * @param    string user       username
183 * @return   Null string if OK, else error message.
184 */
[b1735a7]185$app->post('/ogagent/loggedout',
186    function() use ($app) {
[b942930]187        global $cmd;
188        $redirto = Array();
189        $result = Array();
190
[b1735a7]191        try {
192                // Reading POST parameters in JSON format.
193                $input = json_decode($app->request()->getBody());
194                $ip = htmlspecialchars($input->ip);
195                $user = htmlspecialchars($input->user);
[21e5ee3]196                // Check sender agent type and IP address consistency (same as parameter value).
197                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) {
198                    throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
[a9140b0]199                }
[b942930]200                // Log activity and respond to client.
[8f3c218]201                writeLog("User logged out: ip=$ip, user=$user.");
[d98bc86]202                $response = "";
[b1735a7]203                jsonResponse(200, $response);
[b942930]204                // Check if client is included in the server database.
205                $cmd->texto = <<<EOD
206SELECT ordenadores.idordenador, ordenadores.ip, remotepc.urllogin
207  FROM remotepc
208 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
209 WHERE ordenadores.ip = '$ip'
210 LIMIT 1;
211EOD;
212                $rs=new Recordset;
213                $rs->Comando=&$cmd;
214                if ($rs->Abrir()) {
215                        // Read query data.
216                        $rs->Primero();
217                        $redirto[0]['url'] = $rs->campos['urllogout'];
218                        $rs->Cerrar();
219                        if (!is_null($redirto[0]['url'])) {
220                                // Redirect notification to UDS server, if needed.
221                                $redirto[0]['post'] = $app->request()->getBody();
222                                $result = multiRequest($redirto);
223                                // ... (check response)
224                                //if ($result[0]['code'] != 200) {
225                                // ...
226                        }
227                }
[b1735a7]228        } catch (Exception $e) {
229                // Comunication error.
230                $response["message"] = $e->getMessage();
[8f3c218]231                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
[b1735a7]232                jsonResponse(400, $response);
233        }
234    }
235);
236
237?>
Note: See TracBrowser for help on using the repository browser.