1
0

api.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. <?php
  2. require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.utils.php");
  3. login($db_link);
  4. //error_log("GET: " . json_encode($_GET));
  5. //error_log("POST: " . json_encode($_POST));
  6. // Получаем параметры через безопасные функции
  7. $action_get = getParam('get', null, null);
  8. $action_send = getParam('send', null, null);
  9. $ip = getParam('ip', null, null, FILTER_VALIDATE_IP, ['flags' => FILTER_FLAG_IPV4]);
  10. $mac_raw = getParam('mac', null, null);
  11. $rec_id = getParam('id', null, null, FILTER_VALIDATE_INT);
  12. $f_subnet = getParam('subnet', null, null);
  13. // Преобразуем IP в BIGINT
  14. $ip_aton = null;
  15. if (!empty($ip)) {
  16. $ip_aton = sprintf('%u', ip2long($ip));
  17. }
  18. // Новые параметры для универсальных методов
  19. $table = getParam('table', null, null);
  20. $filter = getParam('filter', null, null); // JSON-строка для кастомного фильтра
  21. $update_data = null;
  22. $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
  23. if (stripos($content_type, 'application/json') !== false) {
  24. $raw_input = file_get_contents('php://input');
  25. if ($raw_input) {
  26. $json_data = json_decode($raw_input, true);
  27. if (json_last_error() === JSON_ERROR_NONE) {
  28. $update_data = $raw_input; // Передаём как строку для дальнейшей обработки
  29. }
  30. }
  31. }
  32. // Если не получили из тела запроса, пытаемся получить из параметров
  33. if ($update_data === null) {
  34. $update_data = getParam('data', null, null);
  35. }
  36. // Параметры пагинации
  37. $limit_param = getParam('limit', null, null, FILTER_VALIDATE_INT);
  38. $offset_param = getParam('offset', null, null, FILTER_VALIDATE_INT);
  39. $limit = ($limit_param !== null && $limit_param > 0) ? min((int)$limit_param, 1000) : 1000;
  40. $offset = ($offset_param !== null && $offset_param >= 0) ? (int)$offset_param : 0;
  41. if (needs_decoding($f_subnet)) { $f_subnet = rawurldecode($f_subnet); }
  42. // Обработка MAC-адреса
  43. $mac = '';
  44. if (!empty($mac_raw) && checkValidMac($mac_raw)) {
  45. $mac = mac_dotted(trim($mac_raw));
  46. }
  47. // Определяем действие
  48. $action = '';
  49. if (!empty($action_get)) { $action = 'get_' . $action_get; }
  50. if (!empty($action_send)) { $action = 'send_' . $action_send; }
  51. // Дополнительные параметры для send_dhcp
  52. $dhcp_hostname = getParam('hostname', null, '');
  53. $dhcp_action = getParam('action', null, 1, FILTER_VALIDATE_INT);
  54. // === Список разрешённых таблиц ===
  55. $allowed_tables = [
  56. 'building',
  57. 'devices',
  58. 'device_models',
  59. 'device_ports',
  60. 'connections',
  61. 'ou',
  62. 'queue_list',
  63. 'group_list',
  64. 'subnets',
  65. 'config',
  66. 'user_auth',
  67. 'user_list',
  68. 'vendors'
  69. ];
  70. function log_api_call($action, $params = []) {
  71. global $db_link;
  72. $log_data = [
  73. 'action' => $action,
  74. 'params' => $params,
  75. 'timestamp' => date('Y-m-d H:i:s'),
  76. 'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
  77. 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
  78. ];
  79. LOG_DEBUG($db_link, "API CALL: " . json_encode($log_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  80. }
  81. function do_exit() {
  82. exit;
  83. }
  84. // === Валидация таблицы ===
  85. function validate_table($table_name, $allowed) {
  86. return in_array($table_name, $allowed) ? $table_name : null;
  87. }
  88. // === Безопасное получение данных из таблицы ===
  89. function safe_get_records($db, $table, $filter = null, $limit = 1000, $offset = 0) {
  90. global $allowed_tables;
  91. if (!validate_table($table, $allowed_tables)) {
  92. return ['error' => 'Invalid table name'];
  93. }
  94. $sql = "SELECT * FROM " . $table;
  95. $params = [];
  96. if ($filter) {
  97. // Фильтр в формате: {"field":"value","field2":"value2"}
  98. $filter_arr = json_decode($filter, true);
  99. if (is_array($filter_arr) && !empty($filter_arr)) {
  100. $conditions = [];
  101. foreach ($filter_arr as $field => $value) {
  102. // Защита от SQL-инъекции: проверяем имя поля
  103. if (!preg_match('/^[a-z_][a-z0-9_]*$/i', $field)) {
  104. continue;
  105. }
  106. $conditions[] = "$field = ?";
  107. $params[] = $value;
  108. }
  109. if (!empty($conditions)) {
  110. $sql .= " WHERE " . implode(" AND ", $conditions);
  111. }
  112. }
  113. }
  114. $sql .= " LIMIT " . (int)$limit;
  115. if ($offset > 0) {
  116. $sql .= " OFFSET " . (int)$offset;
  117. }
  118. $result = get_records_sql($db, $sql, $params);
  119. return $result;
  120. }
  121. // === Безопасное получение одной записи ===
  122. function safe_get_record($db, $table, $id) {
  123. global $allowed_tables;
  124. if (!validate_table($table, $allowed_tables)) {
  125. return ['error' => 'Invalid table name'];
  126. }
  127. if (!is_numeric($id) || $id <= 0) {
  128. return ['error' => 'Invalid ID'];
  129. }
  130. $pk_field = 'id'; // Все таблицы используют 'id' как первичный ключ
  131. $result = get_record_sql($db, "SELECT * FROM $table WHERE $pk_field = ?", [(int)$id]);
  132. # error_log("SELECT * FROM $table WHERE $pk_field = $id ::". $result);
  133. return $result;
  134. }
  135. if (!empty($action)) {
  136. // === УНИВЕРСАЛЬНЫЙ МЕТОД: get_table_record ===
  137. if ($action === 'get_table_record' && !empty($table)) {
  138. log_api_call($action, [
  139. 'table' => $table,
  140. 'filter' => $filter,
  141. 'limit' => $limit,
  142. 'offset' => $offset,
  143. 'id' => $rec_id
  144. ]);
  145. if ($rec_id>0) {
  146. $result = safe_get_record($db_link, $table, $rec_id);
  147. } elseif (!empty($filter)) {
  148. $result_arr = safe_get_records($db_link, $table, $filter, 1);
  149. if (!empty($result_arr)) { $result = $result_arr[0]; }
  150. } else {
  151. do_exit();
  152. }
  153. if (isset($result['error'])) {
  154. http_response_code(400);
  155. echo json_encode($result);
  156. do_exit();
  157. }
  158. if ($result) {
  159. header('Content-Type: application/json; charset=utf-8');
  160. echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  161. } else {
  162. http_response_code(404);
  163. echo json_encode(['error' => 'Record not found']);
  164. }
  165. do_exit();
  166. }
  167. // === УНИВЕРСАЛЬНЫЙ МЕТОД: get_table_list ===
  168. if ($action === 'get_table_list' && !empty($table)) {
  169. log_api_call($action, [
  170. 'table' => $table,
  171. 'filter' => $filter,
  172. 'limit' => $limit,
  173. 'offset' => $offset,
  174. ]);
  175. $result = safe_get_records($db_link, $table, $filter, $limit, $offset);
  176. if (isset($result['error'])) {
  177. http_response_code(400);
  178. echo json_encode($result);
  179. do_exit();
  180. }
  181. header('Content-Type: application/json; charset=utf-8');
  182. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  183. do_exit();
  184. }
  185. // === ОБНОВЛЕНИЕ USER_LIST ===
  186. if ($action === 'send_update_user' && $rec_id > 0 && !empty($update_data)) {
  187. log_api_call($action, [
  188. 'rec_id' => $rec_id,
  189. 'update_data' => $update_data,
  190. ]);
  191. $data = json_decode($update_data, true);
  192. if (!is_array($data)) {
  193. http_response_code(400);
  194. echo json_encode(['error' => 'Invalid data format']);
  195. do_exit();
  196. }
  197. // Разрешённые поля для обновления
  198. $allowed_fields = [
  199. 'login', 'description', 'enabled', 'blocked', 'ou_id',
  200. 'filter_group_id', 'queue_id', 'day_quota', 'month_quota', 'permanent'
  201. ];
  202. $update_fields = [];
  203. foreach ($data as $key => $value) {
  204. if (in_array($key, $allowed_fields)) {
  205. $update_fields[$key] = $value;
  206. }
  207. }
  208. if (empty($update_fields)) {
  209. http_response_code(400);
  210. echo json_encode(['error' => 'No valid fields to update']);
  211. do_exit();
  212. }
  213. // Проверяем существование пользователя
  214. $existing = get_record_sql($db_link, "SELECT id FROM user_list WHERE id = ?", [$rec_id]);
  215. if (!$existing) {
  216. http_response_code(404);
  217. echo json_encode(['error' => 'User not found']);
  218. do_exit();
  219. }
  220. // Выполняем обновление
  221. if (update_record($db_link, 'user_list', 'id = ?', $update_fields, [$rec_id])) {
  222. LOG_VERBOSE($db_link, "API: User $rec_id updated successfully");
  223. http_response_code(200);
  224. echo json_encode(['status' => 'updated', 'id' => $rec_id]);
  225. } else {
  226. LOG_ERROR($db_link, "API: Failed to update user $rec_id");
  227. http_response_code(500);
  228. echo json_encode(['error' => 'Update failed']);
  229. }
  230. do_exit();
  231. }
  232. // === ОБНОВЛЕНИЕ USER_AUTH ===
  233. if ($action === 'send_update_user_auth' && $rec_id > 0 && !empty($update_data)) {
  234. log_api_call($action, [
  235. 'rec_id' => $rec_id,
  236. 'update_data' => $update_data,
  237. ]);
  238. $data = json_decode($update_data, true);
  239. if (!is_array($data)) {
  240. http_response_code(400);
  241. echo json_encode(['error' => 'Invalid data format']);
  242. do_exit();
  243. }
  244. // Разрешённые поля для обновления
  245. $allowed_fields = ['mac', 'ip', 'ip_int', 'wikiname', 'description', 'dns_name'];
  246. $update_fields = [];
  247. foreach ($data as $key => $value) {
  248. $db_key = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $key)); // WikiName -> wiki_name
  249. if (in_array($db_key, $allowed_fields)) {
  250. $update_fields[$db_key] = $value;
  251. }
  252. }
  253. if (empty($update_fields)) {
  254. http_response_code(400);
  255. echo json_encode(['error' => 'No valid fields to update']);
  256. do_exit();
  257. }
  258. if (update_record($db_link, 'user_auth', 'id = ?', $update_fields, [$rec_id])) {
  259. LOG_VERBOSE($db_link, "API: User_auth $rec_id updated via API", $rec_id);
  260. http_response_code(200);
  261. echo json_encode(['status' => 'updated', 'id' => $rec_id]);
  262. } else {
  263. LOG_ERROR($db_link, "API: Failed to update user_auth $rec_id", $rec_id);
  264. http_response_code(500);
  265. echo json_encode(['error' => 'Update failed']);
  266. }
  267. do_exit();
  268. }
  269. // === get_user_auth ===
  270. if ($action === 'get_user_auth') {
  271. LOG_VERBOSE($db_link, "API: Get User Auth record with ip: $ip mac: $mac id: $rec_id");
  272. log_api_call($action, [
  273. 'ip' => $ip,
  274. 'ip_aton' => $ip_aton,
  275. 'mac' => $mac,
  276. 'rec_id' => $rec_id,
  277. ]);
  278. $result = null;
  279. $sql = "";
  280. $params = [];
  281. if ($rec_id > 0) {
  282. $sql = "SELECT * FROM user_auth WHERE id = ?";
  283. $params = [$rec_id];
  284. } elseif ($ip_aton !== null && !empty($mac)) {
  285. $sql = "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0";
  286. $params = [$ip_aton, $mac];
  287. } elseif ($ip_aton !== null) {
  288. $sql = "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0";
  289. $params = [$ip_aton];
  290. } elseif (!empty($mac)) {
  291. $sql = "SELECT * FROM user_auth WHERE mac = ? AND deleted = 0";
  292. $params = [$mac];
  293. }
  294. if ($sql) {
  295. $result = get_record_sql($db_link, $sql, $params);
  296. if ($result) {
  297. LOG_VERBOSE($db_link, "API: Record found.");
  298. header('Content-Type: application/json; charset=utf-8');
  299. echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  300. } else {
  301. LOG_VERBOSE($db_link, "API: Record not found.");
  302. http_response_code(404);
  303. echo json_encode(['error' => 'Not found']);
  304. }
  305. } else {
  306. LOG_DEBUG($db_link, "API: not enough parameters | GET: " . json_encode($_GET, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . " | POST: " . json_encode($_POST, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  307. http_response_code(400);
  308. echo json_encode(['error' => 'Missing parameters']);
  309. }
  310. do_exit();
  311. }
  312. // === get_user ===
  313. if ($action === 'get_user') {
  314. LOG_VERBOSE($db_link, "API: Get User record with id: $rec_id");
  315. log_api_call($action, [
  316. 'rec_id' => $rec_id,
  317. ]);
  318. if ($rec_id > 0) {
  319. $user = get_record_sql($db_link, "SELECT * FROM user_list WHERE deleted = 0 AND id = ?", [$rec_id]);
  320. if ($user) {
  321. $auth_records = get_records_sql($db_link,
  322. "SELECT * FROM user_auth WHERE deleted = 0 AND user_id = ? ORDER BY id LIMIT 100",
  323. [$rec_id]
  324. );
  325. $user['auth'] = $auth_records ?: [];
  326. LOG_VERBOSE($db_link, "API: User record found.");
  327. header('Content-Type: application/json; charset=utf-8');
  328. echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  329. } else {
  330. LOG_VERBOSE($db_link, "API: User not found.");
  331. http_response_code(404);
  332. echo json_encode(['error' => 'User not found']);
  333. }
  334. } else {
  335. LOG_VERBOSE($db_link, "API: not enough parameters");
  336. http_response_code(400);
  337. echo json_encode(['error' => 'Missing user ID']);
  338. }
  339. do_exit();
  340. }
  341. // === get_dhcp_all ===
  342. if ($action === 'get_dhcp_all') {
  343. LOG_VERBOSE($db_link, "API: Get all dhcp records");
  344. $result = get_records_sql($db_link, "
  345. SELECT
  346. ua.id, ua.ip, ua.ip_int, ua.mac, ua.description,
  347. ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id,
  348. SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base
  349. FROM user_auth ua
  350. JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
  351. WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1
  352. ORDER BY ua.ip_int
  353. LIMIT ? OFFSET ?
  354. ", [$limit, $offset]);
  355. LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
  356. header('Content-Type: application/json; charset=utf-8');
  357. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  358. do_exit();
  359. }
  360. // === get_dhcp_subnet ===
  361. if ($action === 'get_dhcp_subnet' && !empty($f_subnet)) {
  362. log_api_call($action, [
  363. 'subnet' => $f_subnet,
  364. ]);
  365. $subnet = cidrToRange($f_subnet);
  366. if (empty($subnet)) {
  367. http_response_code(400);
  368. echo json_encode(['error' => 'Invalid subnet format']);
  369. do_exit();
  370. }
  371. LOG_VERBOSE($db_link, "API: Get dhcp records for subnet " . $f_subnet);
  372. $result = get_records_sql($db_link, "
  373. SELECT
  374. ua.id, ua.ip, ua.ip_int, ua.mac, ua.description,
  375. ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id,
  376. SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base
  377. FROM user_auth ua
  378. JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
  379. WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1
  380. AND SUBSTRING_INDEX(s.subnet, '/', 1) = ?
  381. ORDER BY ua.ip_int
  382. LIMIT ? OFFSET ?
  383. ", [$f_subnet, $limit, $offset]);
  384. LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
  385. header('Content-Type: application/json; charset=utf-8');
  386. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  387. do_exit();
  388. }
  389. // === get_user_subnet ===
  390. if ($action === 'get_user_subnet' && !empty($f_subnet)) {
  391. LOG_VERBOSE($db_link, "API: Get ip records for subnet " . $f_subnet);
  392. log_api_call($action, [
  393. 'subnet' => $f_subnet,
  394. ]);
  395. $subnet = cidrToRange($f_subnet);
  396. if (empty($subnet)) {
  397. http_response_code(400);
  398. echo json_encode(['error' => 'Invalid subnet format']);
  399. do_exit();
  400. }
  401. $first_ip = ip2long($subnet[0]);
  402. $last_ip = ip2long($subnet[1]);
  403. $result = get_records_sql($db_link, "
  404. SELECT id, ip, ip_int, mac, description, dns_name, dhcp_hostname, ou_id
  405. FROM user_auth
  406. WHERE deleted=0 AND ip_int BETWEEN ? AND ? ORDER BY ip_int
  407. LIMIT ? OFFSET ?
  408. ", [ $first_ip, $last_ip, $limit, $offset]);
  409. LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
  410. header('Content-Type: application/json; charset=utf-8');
  411. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  412. do_exit();
  413. }
  414. // === send_dhcp ===
  415. if ($action === 'send_dhcp') {
  416. log_api_call($action, [
  417. 'ip' => $ip,
  418. 'mac' => $mac,
  419. 'action' => $dhcp_action,
  420. ]);
  421. if ($ip && $mac) {
  422. $faction = $dhcp_action !== null ? (int)$dhcp_action : 1;
  423. $action_str = ($faction === 0) ? 'del' : 'add';
  424. LOG_VERBOSE($db_link, "API: external dhcp request for $ip [$mac] $action_str");
  425. if (is_our_network($db_link, $ip)) {
  426. $dhcp_record = [
  427. 'action' => $action_str,
  428. 'mac' => $mac,
  429. 'ip' => $ip,
  430. 'dhcp_hostname' => $dhcp_hostname
  431. ];
  432. $insert_id = insert_record($db_link, "dhcp_queue", $dhcp_record);
  433. if ($insert_id !== false && $insert_id > 0) {
  434. LOG_VERBOSE($db_link, "API: DHCP record queued successfully. ID: $insert_id, IP: $ip, MAC: $mac, Action: $action_str");
  435. http_response_code(201);
  436. echo json_encode([
  437. 'status' => 'queued',
  438. 'id' => (int)$insert_id,
  439. 'ip' => $ip,
  440. 'mac' => $mac,
  441. 'action' => $action_str
  442. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  443. } else {
  444. $error_msg = "Failed to insert DHCP record into queue";
  445. LOG_ERROR($db_link, "API: $error_msg. IP: $ip, MAC: $mac, Action: $action_str");
  446. http_response_code(500);
  447. echo json_encode([
  448. 'error' => $error_msg,
  449. 'ip' => $ip,
  450. 'mac' => $mac
  451. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  452. }
  453. } else {
  454. $error_msg = "IP not in allowed network";
  455. LOG_ERROR($db_link, "API: $error_msg - $ip [$mac]");
  456. http_response_code(400);
  457. echo json_encode([
  458. 'error' => $error_msg,
  459. 'ip' => $ip
  460. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  461. }
  462. } else {
  463. $missing_params = [];
  464. if (!$ip) $missing_params[] = 'ip';
  465. if (!$mac) $missing_params[] = 'mac';
  466. $error_msg = 'Missing required parameters: ' . implode(', ', $missing_params);
  467. LOG_WARNING($db_link, "API: send_dhcp called with missing parameters. Missing: " . implode(', ', $missing_params));
  468. http_response_code(400);
  469. echo json_encode([
  470. 'error' => $error_msg
  471. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  472. }
  473. do_exit();
  474. }
  475. } else {
  476. LOG_WARNING($db_link, "API: Unknown request");
  477. http_response_code(400);
  478. echo json_encode(['error' => 'Unknown action']);
  479. }
  480. do_exit();
  481. ?>