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
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)
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        $osType = $osVersion = "none";
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);
41                if (isset($input->ostype))  $osType = htmlspecialchars($input->ostype);
42                if (isset($input->osversion))  $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion));
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']);
46                }
47                // Client secret key for secure communications.
48                if (isset($input->secret)) {
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                    }
53                    // Store secret key in DB.
54                    if (isset($input->secret))  $secret = htmlspecialchars($input->secret);
55                    $cmd->texto = "UPDATE ordenadores
56                                      SET agentkey='$secret'
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.");
62                    }
63                } else {
64                    // Insecure agent exception.
65                    throw new Exception("Insecure OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion.");
66                }
67                // Default processing: log activity.
68                writeLog("OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion.");
69                // Response.
70                $response = "";
71                jsonResponse(200, $response);
72        } catch (Exception $e) {
73                // Comunication error.
74                $response["message"] = $e->getMessage();
75                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
76                jsonResponse(400, $response);
77        }
78    }
79);
80
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 */
90$app->post('/ogagent/stopped',
91    function() use ($app) {
92        $osType = $osVersion = "none";
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);
98                if (isset($input->ostype))  $osType = htmlspecialchars($input->ostype);
99                if (isset($input->osversion))  $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion));
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']);
103                }
104                // May check if client is included in the server database?
105                // Default processing: log activity.
106                writeLog("OGAgent stopped: ip=$ip, mac=$mac, os=$osType:$osVersion.");
107                // Response.
108                $response = "";
109                jsonResponse(200, $response);
110        } catch (Exception $e) {
111                // Comunication error.
112                $response["message"] = $e->getMessage();
113                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
114                jsonResponse(400, $response);
115        }
116    }
117);
118
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 */
126$app->post('/ogagent/loggedin',
127    function() use ($app) {
128        global $cmd;
129        $redirto = Array();
130        $result = Array();
131
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);
137                // Check sender IP address consistency (same as parameter value).
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']);
140                }
141                // Log activity and respond to client.
142                writeLog("User logged in: ip=$ip, user=$user.");
143                $response = "";
144                jsonResponse(200, $response);
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);
164                                // ... (check response)
165                                //if ($result[0]['code'] != 200) {
166                                // ...
167                        }
168                }
169        } catch (Exception $e) {
170                // Comunication error.
171                $response["message"] = $e->getMessage();
172                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
173                jsonResponse(400, $response);
174        }
175    }
176);
177
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 */
185$app->post('/ogagent/loggedout',
186    function() use ($app) {
187        global $cmd;
188        $redirto = Array();
189        $result = Array();
190
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);
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']);
199                }
200                // Log activity and respond to client.
201                writeLog("User logged out: ip=$ip, user=$user.");
202                $response = "";
203                jsonResponse(200, $response);
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                }
228        } catch (Exception $e) {
229                // Comunication error.
230                $response["message"] = $e->getMessage();
231                writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]);
232                jsonResponse(400, $response);
233        }
234    }
235);
236
237?>
Note: See TracBrowser for help on using the repository browser.