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. |
---|
15 | define('LOG_FILE', '/opt/opengnsys/log/ogagent.log'); |
---|
16 | |
---|
17 | // Function to write a line into log file. |
---|
18 | function 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 = <<<EOD |
---|
56 | UPDATE ordenadores |
---|
57 | SET agentkey='$secret' |
---|
58 | WHERE ip='$ip' AND mac=UPPER(REPLACE('$mac', ':', '')) |
---|
59 | LIMIT 1; |
---|
60 | EOD; |
---|
61 | if ($cmd->Ejecutar() !== true or mysql_affected_rows() !== 1) { |
---|
62 | // DB access error or not updated. |
---|
63 | throw new Exception("Cannot store new secret key: ip=$ip, mac=$mac, os=$osType:$osVersion."); |
---|
64 | } |
---|
65 | } else { |
---|
66 | // Insecure agent exception. |
---|
67 | throw new Exception("Insecure OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion."); |
---|
68 | } |
---|
69 | // Default processing: log activity. |
---|
70 | writeLog("OGAgent started: ip=$ip, mac=$mac, os=$osType:$osVersion."); |
---|
71 | // Response. |
---|
72 | $response = ""; |
---|
73 | jsonResponse(200, $response); |
---|
74 | } catch (Exception $e) { |
---|
75 | // Communication error. |
---|
76 | $response["message"] = $e->getMessage(); |
---|
77 | writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); |
---|
78 | jsonResponse(400, $response); |
---|
79 | } |
---|
80 | } |
---|
81 | ); |
---|
82 | |
---|
83 | /** |
---|
84 | * @brief OGAgent notifies that its service is stopped on client. |
---|
85 | * @note Route: /ogagent/stopped, Method: POST, Format: JSON |
---|
86 | * @param string ip IP address |
---|
87 | * @param string mac MAC (Ethernet) address |
---|
88 | * @param string ostype OS type (Linux, Windows) |
---|
89 | * @param string osversion OS version |
---|
90 | * @return Null string if OK, else error message. |
---|
91 | */ |
---|
92 | $app->post('/ogagent/stopped', |
---|
93 | function() use ($app) { |
---|
94 | $osType = $osVersion = "none"; |
---|
95 | try { |
---|
96 | // Reading POST parameters in JSON format. |
---|
97 | $input = json_decode($app->request()->getBody()); |
---|
98 | $ip = htmlspecialchars($input->ip); |
---|
99 | $mac = htmlspecialchars($input->mac); |
---|
100 | if (isset($input->ostype)) $osType = htmlspecialchars($input->ostype); |
---|
101 | if (isset($input->osversion)) $osVersion = str_replace(",", ";", htmlspecialchars($input->osversion)); |
---|
102 | // Check sender agent type and IP address consistency (same as parameter value). |
---|
103 | if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { |
---|
104 | throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); |
---|
105 | } |
---|
106 | // May check if client is included in the server database? |
---|
107 | // Default processing: log activity. |
---|
108 | writeLog("OGAgent stopped: ip=$ip, mac=$mac, os=$osType:$osVersion."); |
---|
109 | // Response. |
---|
110 | $response = ""; |
---|
111 | jsonResponse(200, $response); |
---|
112 | } catch (Exception $e) { |
---|
113 | // Communication error. |
---|
114 | $response["message"] = $e->getMessage(); |
---|
115 | writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); |
---|
116 | jsonResponse(400, $response); |
---|
117 | } |
---|
118 | } |
---|
119 | ); |
---|
120 | |
---|
121 | /** |
---|
122 | * @brief OGAgent notifies that an user logs in. |
---|
123 | * @note Route: /ogagent/loggedin, Method: POST, Format: JSON |
---|
124 | * @param string ip IP address |
---|
125 | * @param string user username |
---|
126 | * @return Null string if OK, else error message. |
---|
127 | */ |
---|
128 | $app->post('/ogagent/loggedin', |
---|
129 | function() use ($app) { |
---|
130 | global $cmd; |
---|
131 | $redirto = Array(); |
---|
132 | $result = Array(); |
---|
133 | |
---|
134 | try { |
---|
135 | // Reading POST parameters in JSON format. |
---|
136 | $input = json_decode($app->request()->getBody()); |
---|
137 | $ip = htmlspecialchars($input->ip); |
---|
138 | $user = htmlspecialchars($input->user); |
---|
139 | // Check sender IP address consistency (same as parameter value). |
---|
140 | if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { |
---|
141 | throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); |
---|
142 | } |
---|
143 | // Check if client is included in the server database. |
---|
144 | $cmd->CreaParametro("@ip", $ip, 0); |
---|
145 | $cmd->texto = <<<EOD |
---|
146 | SELECT ordenadores.idordenador, ordenadores.nombreordenador, remotepc.urllogin, |
---|
147 | remotepc.reserved > NOW() AS reserved |
---|
148 | FROM remotepc |
---|
149 | RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador |
---|
150 | WHERE ordenadores.ip=@ip |
---|
151 | LIMIT 1; |
---|
152 | EOD; |
---|
153 | $rs=new Recordset; |
---|
154 | $rs->Comando=&$cmd; |
---|
155 | if ($rs->Abrir()) { |
---|
156 | // Read query data. |
---|
157 | $rs->Primero(); |
---|
158 | $id = $rs->campos['idordenador']; |
---|
159 | $redirto[0]['url'] = $rs->campos['urllogin']; |
---|
160 | $reserved = $rs->campos['reserved']; |
---|
161 | $rs->Cerrar(); |
---|
162 | if (!is_null($id)) { |
---|
163 | // Log activity, respond to client and continue processing. |
---|
164 | writeLog("User logged in: ip=$ip, user=$user."); |
---|
165 | $response = ""; |
---|
166 | jsonResponseNow(200, $response); |
---|
167 | } else { |
---|
168 | throw new Exception("Client is not in the database: ip=$ip, user=$user"); |
---|
169 | } |
---|
170 | // Redirect notification to UDS server, if needed. |
---|
171 | if ($reserved == 1 and !is_null($redirto[0]['url'])) { |
---|
172 | $redirto[0]['get'] = $app->request()->getBody(); |
---|
173 | $result = multiRequest($redirto); |
---|
174 | // ... (check response) |
---|
175 | //if ($result[0]['code'] != 200) { |
---|
176 | // ... |
---|
177 | } |
---|
178 | } else { |
---|
179 | throw new Exception("Database error"); |
---|
180 | } |
---|
181 | } catch (Exception $e) { |
---|
182 | // Communication error. |
---|
183 | $response["message"] = $e->getMessage(); |
---|
184 | writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); |
---|
185 | jsonResponse(400, $response); |
---|
186 | } |
---|
187 | } |
---|
188 | ); |
---|
189 | |
---|
190 | /** |
---|
191 | * @brief OGAgent notifies that an user logs out. |
---|
192 | * @note Route: /ogagent/loggedout, Method: POST, Format: JSON |
---|
193 | * @param string ip IP address |
---|
194 | * @param string user username |
---|
195 | * @return Null string if OK, else error message. |
---|
196 | */ |
---|
197 | $app->post('/ogagent/loggedout', |
---|
198 | function() use ($app) { |
---|
199 | global $cmd; |
---|
200 | $redirto = Array(); |
---|
201 | $result = Array(); |
---|
202 | |
---|
203 | try { |
---|
204 | // Reading POST parameters in JSON format. |
---|
205 | $input = json_decode($app->request()->getBody()); |
---|
206 | $ip = htmlspecialchars($input->ip); |
---|
207 | $user = htmlspecialchars($input->user); |
---|
208 | // Check sender agent type and IP address consistency (same as parameter value). |
---|
209 | if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT'])) or $ip !== $_SERVER['REMOTE_ADDR']) { |
---|
210 | throw new Exception("Bad OGAgent: ip=$ip, sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']); |
---|
211 | } |
---|
212 | // Check if client is included in the server database. |
---|
213 | $cmd->CreaParametro("@ip", $ip, 0); |
---|
214 | $cmd->texto = <<<EOD |
---|
215 | SELECT ordenadores.idordenador, ordenadores.nombreordenador, remotepc.urllogout, |
---|
216 | remotepc.reserved > NOW() AS reserved |
---|
217 | FROM remotepc |
---|
218 | RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador |
---|
219 | WHERE ordenadores.ip=@ip |
---|
220 | LIMIT 1; |
---|
221 | EOD; |
---|
222 | $rs=new Recordset; |
---|
223 | $rs->Comando=&$cmd; |
---|
224 | if ($rs->Abrir()) { |
---|
225 | // Read query data. |
---|
226 | $rs->Primero(); |
---|
227 | $id = $rs->campos['idordenador']; |
---|
228 | $redirto[0]['url'] = $rs->campos['urllogout']; |
---|
229 | $reserved = $rs->campos['reserved']; |
---|
230 | $rs->Cerrar(); |
---|
231 | if (!is_null($id)) { |
---|
232 | // Log activity, respond to client and continue processing. |
---|
233 | writeLog("User logged out: ip=$ip, user=$user."); |
---|
234 | $response = ""; |
---|
235 | jsonResponseNow(200, $response); |
---|
236 | } else { |
---|
237 | throw new Exception("Client is not in the database: ip=$ip, user=$user"); |
---|
238 | } |
---|
239 | // Redirect notification to UDS server, if needed. |
---|
240 | if ($reserved == 1 and !is_null($redirto[0]['url'])) { |
---|
241 | $redirto[0]['get'] = $app->request()->getBody(); |
---|
242 | $result = multiRequest($redirto); |
---|
243 | // ... (check response) |
---|
244 | //if ($result[0]['code'] != 200) { |
---|
245 | // ... |
---|
246 | } |
---|
247 | } else { |
---|
248 | throw new Exception("Database error"); |
---|
249 | } |
---|
250 | } catch (Exception $e) { |
---|
251 | // Communication error. |
---|
252 | $response["message"] = $e->getMessage(); |
---|
253 | writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); |
---|
254 | jsonResponse(400, $response); |
---|
255 | } |
---|
256 | } |
---|
257 | ); |
---|
258 | |
---|
259 | ?> |
---|