1 | <?php |
---|
2 | /** |
---|
3 | * @file index.php |
---|
4 | * @brief OpenGnsys REST API: common functions and routes |
---|
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-11-17 |
---|
11 | */ |
---|
12 | |
---|
13 | |
---|
14 | // Common functions. |
---|
15 | |
---|
16 | /** |
---|
17 | * @brief Compose JSON response. |
---|
18 | * @param int status Status code for HTTP response. |
---|
19 | * @param array response Response data. |
---|
20 | * @param int opts Options to encode JSON data. |
---|
21 | * @return string JSON response. |
---|
22 | */ |
---|
23 | function jsonResponse($status, $response, $opts=0) { |
---|
24 | $app = \Slim\Slim::getInstance(); |
---|
25 | // HTTP status code. |
---|
26 | $app->status($status); |
---|
27 | // Content-type HTTP header. |
---|
28 | $app->contentType('application/json'); |
---|
29 | // JSON response. |
---|
30 | echo json_encode($response, $opts); |
---|
31 | } |
---|
32 | |
---|
33 | /** |
---|
34 | * @brief Validate API key included in "Authorization" HTTP header. |
---|
35 | * @return JSON response on error. |
---|
36 | */ |
---|
37 | function validateApiKey() { |
---|
38 | global $cmd; |
---|
39 | global $userid; |
---|
40 | $response = array(); |
---|
41 | $app = \Slim\Slim::getInstance(); |
---|
42 | // Read Authorization HTTP header. |
---|
43 | $headers = apache_request_headers(); |
---|
44 | if (! empty($headers['Authorization'])) { |
---|
45 | // Assign user id. that match this key to global variable. |
---|
46 | $apikey = htmlspecialchars($headers['Authorization']); |
---|
47 | $cmd->texto = "SELECT idusuario |
---|
48 | FROM usuarios |
---|
49 | WHERE apikey='$apikey' LIMIT 1"; |
---|
50 | $rs=new Recordset; |
---|
51 | $rs->Comando=&$cmd; |
---|
52 | if ($rs->Abrir()) { |
---|
53 | $rs->Primero(); |
---|
54 | if (!$rs->EOF){ |
---|
55 | // Fetch user id. |
---|
56 | $userid = $rs->campos["idusuario"]; |
---|
57 | } else { |
---|
58 | // Credentials error. |
---|
59 | $response['message'] = 'Login failed. Incorrect credentials'; |
---|
60 | jsonResponse(401, $response); |
---|
61 | $app->stop(); |
---|
62 | } |
---|
63 | $rs->Cerrar(); |
---|
64 | } else { |
---|
65 | // Access error. |
---|
66 | $response['message'] = "An error occurred, please try again"; |
---|
67 | jsonResponse(500, $response); |
---|
68 | } |
---|
69 | } else { |
---|
70 | // Error: missing API key. |
---|
71 | $response['message'] = 'Missing API key'; |
---|
72 | jsonResponse(400, $response); |
---|
73 | $app->stop(); |
---|
74 | } |
---|
75 | } |
---|
76 | |
---|
77 | /** |
---|
78 | * @brief Check if parameter is set and print error messages if empty. |
---|
79 | * @param string param Parameter to check. |
---|
80 | * @return boolean "false" if parameter is null, otherwise "true". |
---|
81 | */ |
---|
82 | function checkParameter($param) { |
---|
83 | if (isset($param)) { |
---|
84 | return true; |
---|
85 | } else { |
---|
86 | // Print error message. |
---|
87 | $response['message'] = 'Parameter not found'; |
---|
88 | jsonResponse(400, $response); |
---|
89 | return false; |
---|
90 | } |
---|
91 | } |
---|
92 | |
---|
93 | /** |
---|
94 | * @fn sendCommand($serverip, $serverport, $reqframe, &$values) |
---|
95 | * @brief Send a command to an OpenGnsys ogAdmServer and get request. |
---|
96 | * @param string serverip Server IP address. |
---|
97 | * @param string serverport Server port. |
---|
98 | * @param string reqframe Request frame (field's separator is "\r"). |
---|
99 | * @param array values Response values (out parameter). |
---|
100 | * @return boolean "true" if success, otherwise "false". |
---|
101 | */ |
---|
102 | function sendCommand($serverip, $serverport, $reqframe, &$values) { |
---|
103 | global $LONCABECERA; |
---|
104 | global $LONHEXPRM; |
---|
105 | |
---|
106 | // Connect to server. |
---|
107 | $respvalues = ""; |
---|
108 | $connect = new SockHidra($serverip, $serverport); |
---|
109 | if ($connect->conectar()) { |
---|
110 | // Send request frame to server. |
---|
111 | $result = $connect->envia_peticion($reqframe); |
---|
112 | if ($result) { |
---|
113 | // Parse request frame. |
---|
114 | $respframe = $connect->recibe_respuesta(); |
---|
115 | $connect->desconectar(); |
---|
116 | $paramlen = hexdec(substr($respframe, $LONCABECERA, $LONHEXPRM)); |
---|
117 | $params = substr($respframe, $LONCABECERA+$LONHEXPRM, $paramlen); |
---|
118 | // Fetch values and return result. |
---|
119 | $values = extrae_parametros($params, "\r", '='); |
---|
120 | return ($values); |
---|
121 | } else { |
---|
122 | // Return with error. |
---|
123 | return (false); |
---|
124 | } |
---|
125 | } else { |
---|
126 | // Return with error. |
---|
127 | return (false); |
---|
128 | } |
---|
129 | } |
---|
130 | |
---|
131 | /** |
---|
132 | * @brief Show custom message for "not found" error (404). |
---|
133 | */ |
---|
134 | $app->notFound(function() { |
---|
135 | echo "REST route not found."; |
---|
136 | } |
---|
137 | ); |
---|
138 | |
---|
139 | /** |
---|
140 | * @brief Hook to write an error log message. |
---|
141 | * @warning Message will be written in web server's error file. |
---|
142 | */ |
---|
143 | $app->hook('slim.after', function() use ($app) { |
---|
144 | if ($app->response->getStatus() != 200 ) { |
---|
145 | // Compose error message (truncating long lines). |
---|
146 | $app->log->error(date(DATE_ISO8601) . ': ' . |
---|
147 | $app->getName() . ' ' . |
---|
148 | $app->response->getStatus() . ': ' . |
---|
149 | $app->request->getMethod() . ' ' . |
---|
150 | $app->request->getPathInfo() . ': ' . |
---|
151 | substr($app->response->getBody(), 0, 100)); |
---|
152 | } |
---|
153 | } |
---|
154 | ); |
---|
155 | |
---|
156 | |
---|
157 | // Common routes. |
---|
158 | |
---|
159 | /** |
---|
160 | * @brief Get general server information |
---|
161 | * @note Route: /info, Method: GET |
---|
162 | * @param no |
---|
163 | * @return JSON object with basic server information (version, services, etc.) |
---|
164 | */ |
---|
165 | $app->get('/info', function() { |
---|
166 | // Reading version file. |
---|
167 | @list($project, $version, $release) = explode(' ', file_get_contents('/opt/opengnsys/doc/VERSION.txt')); |
---|
168 | $response['project'] = trim($project); |
---|
169 | $response['version'] = trim($version); |
---|
170 | $response['release'] = trim($release); |
---|
171 | // Getting actived services. |
---|
172 | @$services = parse_ini_file('/etc/default/opengnsys'); |
---|
173 | $response['services'] = Array(); |
---|
174 | if (@$services["RUN_OGADMSERVER"] === "yes") { |
---|
175 | array_push($response['services'], "server"); |
---|
176 | $hasOglive = true; |
---|
177 | } |
---|
178 | if (@$services["RUN_OGADMREPO"] === "yes") array_push($response['services'], "repository"); |
---|
179 | if (@$services["RUN_BTTRACKER"] === "yes") array_push($response['services'], "tracker"); |
---|
180 | // Reading installed ogLive information file. |
---|
181 | if ($hasOglive === true) { |
---|
182 | $data = json_decode(@file_get_contents('/opt/opengnsys/etc/ogliveinfo.json')); |
---|
183 | if (isset($data->oglive)) { |
---|
184 | $response['oglive'] = $data->oglive; |
---|
185 | } |
---|
186 | } |
---|
187 | jsonResponse(200, $response); |
---|
188 | } |
---|
189 | ); |
---|
190 | |
---|
191 | /** |
---|
192 | * @brief Get the server status |
---|
193 | * @note Route: /status, Method: GET |
---|
194 | * @param no |
---|
195 | * @return JSON object with all data collected from server status (RAM, %CPU, etc.). |
---|
196 | */ |
---|
197 | $app->get('/status', function() { |
---|
198 | // Getting memory and CPU information. |
---|
199 | exec("awk '$1~/Mem/ {print $2}' /proc/meminfo",$memInfo); |
---|
200 | $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]); |
---|
201 | $cpuInfo = exec("awk '$1==\"cpu\" {printf \"%.2f\",($2+$4)*100/($2+$4+$5)}' /proc/stat"); |
---|
202 | $cpuModel = exec("awk -F: '$1~/model name/ {print $2}' /proc/cpuinfo"); |
---|
203 | $response["memInfo"] = $memInfo; |
---|
204 | $response["cpu"] = array("model" => trim($cpuModel), "usage" => $cpuInfo); |
---|
205 | jsonResponse(200, $response); |
---|
206 | } |
---|
207 | ); |
---|
208 | ?> |
---|