-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathFilesToJSON.php
393 lines (344 loc) · 10.9 KB
/
FilesToJSON.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2018 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*
* PHP version 7
*
* @category Inventory
* @package Glpi
* @author Johan Cwiklinski <[email protected]>
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
* @link https://glpi-project.org
*/
namespace Glpi\Inventory;
use RuntimeException;
/**
* Converts old FusionInventory XML format to new JSON schema
* for automatic inventory.
*
* @category Inventory
* @package Glpi
* @author Johan Cwiklinski <[email protected]>
* @copyright 2018-2023 GLPI Team and Contributors
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
* @link https://glpi-project.org
*/
final class FilesToJSON
{
public const TYPE_PCI = 'pciid';
public const TYPE_USB = 'usbid';
public const TYPE_OUI = 'ouis';
public const TYPE_IFTYPE = 'iftype';
private const SOURCES_URLS = [
self::TYPE_PCI => 'https://pci-ids.ucw.cz/v2.2/pci.ids',
self::TYPE_USB => 'http://www.linux-usb.org/usb.ids',
self::TYPE_OUI => 'https://standards-oui.ieee.org/oui/oui.txt',
self::TYPE_IFTYPE => 'https://www.iana.org/assignments/smi-numbers/smi-numbers-5.csv',
];
/**
* @var string
*/
private string $path = __DIR__ . '/../../data';
/**
* Get JSON file path
*
* @param string $type Type (either 'pci', 'usb' or 'oui')
*
* @return string
*/
public function getJsonFilePath(string $type): string
{
return $this->path . '/' . $type . '.json';
}
/**
* Download new sources
*
* @throws RuntimeException
* @return void
*/
public function refreshSources()
{
foreach (self::SOURCES_URLS as $type => $uri) {
$path = $this->getSourceFilePath($type);
$contents = $this->callCurl($uri);
if (file_put_contents($path, $contents) !== strlen($contents)) {
throw new RuntimeException(sprintf('Unable to write content in %s.', $path));
}
}
}
/**
* Runs all conversions
*
* @throws RuntimeException
* @return void
*/
public function run(): void
{
$this->convertPciFile();
$this->convertUsbFile();
$this->convertOUIFile();
$this->convertIftypeFile();
}
/**
* Return source file name for given type.
*
* @param string $type
* @return string
*/
private function getSourceFilename(string $type): string
{
$basename = null;
switch ($type) {
case self::TYPE_PCI:
$basename = 'pci.ids';
break;
case self::TYPE_USB:
$basename = 'usb.ids';
break;
case self::TYPE_OUI:
$basename = 'oui.txt';
break;
case self::TYPE_IFTYPE:
$basename = 'iftype.csv';
break;
default:
throw new RuntimeException('Unknown type ' . $type);
}
return $basename;
}
/**
* Get source file path
*
* @param string $type File type
*
* @return string
*/
private function getSourceFilePath(string $type): string
{
return $this->path . '/' . $this->getSourceFilename($type);
}
/**
* Get file for type
*
* @param string $type Type
* @throws RuntimeException
* @return resource
*/
private function getSourceFile(string $type)
{
$path = $this->getSourceFilePath($type);
if (!file_exists($path)) {
// Fallback to default source file
$path = __DIR__ . '/../../source_files/' . $this->getSourceFilename($type);
if (!file_exists($path)) {
throw new RuntimeException(sprintf('Source file %s not found.', $this->getSourceFilename($type)));
}
}
$file = fopen($path, 'r');
if ($file === false) {
throw new RuntimeException(sprintf('Unable to open source file %s.', $path));
}
return $file;
}
/**
* Convert PCI file from IDS to JSON
*
* @throws RuntimeException
* @return void
*/
private function convertPciFile(): void
{
$pciFile = $this->getSourceFile(self::TYPE_PCI);
$pci_ids = [];
$vendorId = null;
while ($buffer = fgets($pciFile)) {
$stack = [];
if (preg_match("/^(\w+)\s*(.+)/i", $buffer, $stack)) {
$vendorId = $stack[1];
$pci_ids[$vendorId] = $stack[2];
}
$stack = [];
if (preg_match("/^\t(\w+)\s*(.+)/i", $buffer, $stack)) {
$deviceId = $stack[1];
$pci_ids[$vendorId . '::' . $deviceId] = $stack[2];
}
}
if (!feof($pciFile)) {
// Ensure source file reading reach end of file.
throw new RuntimeException('Error while reading PCI source file.');
}
$this->writeJsonFile(self::TYPE_PCI, $pci_ids);
}
/**
* Convert USB file from IDS to JSON
*
* @throws RuntimeException
* @return void
*/
private function convertUsbFile(): void
{
$usbFile = $this->getSourceFile(self::TYPE_USB);
$usb_ids = [];
$vendorId = null;
while ($buffer = fgets($usbFile)) {
$stack = [];
if (preg_match("/^(\w+)\s*(.+)/i", $buffer, $stack)) {
$vendorId = $stack[1];
$usb_ids[$vendorId] = $stack[2];
}
$stack = [];
if (preg_match("/^\t(\w+)\s*(.+)/i", $buffer, $stack)) {
$deviceId = $stack[1];
$usb_ids[$vendorId . '::' . $deviceId] = $stack[2];
}
}
if (!feof($usbFile)) {
// Ensure source file reading reach end of file.
throw new RuntimeException('Error while reading USB source file.');
}
$this->writeJsonFile(self::TYPE_USB, $usb_ids);
}
/**
* Convert OUI file from TXT to JSON
*
* @throws RuntimeException
* @return void
*/
private function convertOUIFile(): void
{
$ouiFile = $this->getSourceFile(self::TYPE_OUI);
$ouis = [];
while ($buffer = fgets($ouiFile)) {
$stack = [];
if (preg_match("/^(\S+)\s*\(hex\)\t{2}(.+)/i", $buffer, $stack)) {
$mac = strtr($stack[1], '-', ':');
$ouis[$mac] = trim($stack[2]);
}
}
if (!feof($ouiFile)) {
// Ensure source file reading reach end of file.
throw new RuntimeException('Error while reading OUI source file.');
}
$this->writeJsonFile(self::TYPE_OUI, $ouis);
}
/**
* Convert iftype file from CSV to JSON
*
* @throws RuntimeException
* @return void
*/
private function convertIftypeFile(): void
{
$iftypeFile = $this->getSourceFile(self::TYPE_IFTYPE);
$iftypes = [];
while ($line = fgetcsv($iftypeFile)) {
$iftypes[] = [
'decimal' => $line[0],
'name' => $line[1],
'description' => $line[2] ?? '',
'references' => $line[3] ?? ''
];
}
if (!feof($iftypeFile)) {
// Ensure source file reading reach end of file.
throw new RuntimeException('Error while reading IFtype source file.');
}
$this->writeJsonFile(self::TYPE_IFTYPE, $iftypes);
}
/**
* Write converted source into corresponding file.
*
* @param string $type
* @param array<string|int, mixed> $data
* @throws RuntimeException
* @return void
*/
private function writeJsonFile(string $type, array $data): void
{
$path = $this->getJsonFilePath($type);
$contents = json_encode($data, JSON_PRETTY_PRINT);
if ($contents === false) {
throw new RuntimeException(sprintf('Error while encoding "%s" data to JSON.', $type));
}
if (file_put_contents($path, $contents) !== strlen($contents)) {
throw new RuntimeException(sprintf('Unable to write "%s" JSON into "%s".', $type, $path));
}
}
/**
* Executes a curl call
*
* @param string $url URL to retrieve
* @throws RuntimeException
* @return string
*/
private function callCurl(string $url): string
{
$ch = curl_init($url);
if ($ch === false) {
throw new RuntimeException(
sprintf(
'Unable to initialize curl for %s',
$url
)
);
}
$opts = [
CURLOPT_URL => $url,
CURLOPT_USERAGENT => "GLPI/Inventory format 1.0",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
];
curl_setopt_array($ch, $opts);
$content = curl_exec($ch);
$curl_error = curl_error($ch) ?: null;
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$msgerr = null;
if ($curl_error !== null) {
$msgerr = $curl_error;
} elseif ($status_code !== 200) {
$msgerr = sprintf(
'HTTP code %s received from %s',
$status_code,
$url
);
} elseif (empty($content)) {
$msgerr = sprintf(
'No data available on %s',
$url
);
}
if ($msgerr !== null) {
throw new RuntimeException($msgerr);
}
//force cast to made phpstan happy, but return is always string here
return (string)$content;
}
}