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