Commit Graph

318 Commits (41c8dec51c4717bdabd60486bd4df6cd999132cb)

Author SHA1 Message Date
Javier Hernandez 5e2b562330 rest: Add uri to update center
Add uri to allow the change of a center's properties such as 'name' or
'comment'

Refuse to update center's name if that name is already in use by another
center. This is because a center should not share name with another one.
2024-02-01 11:23:54 +01:00
Javier Hernandez 128bba364a rest: Check no client owns provided mac address
Reply with an error if user tries to create a client with a mac that is
already owned by another client

Write to syslog info about the client that owns the mac: client's name,
ip, mac address and room
2024-01-16 13:30:27 +01:00
Javier Hernandez 149d1af21a rest: Change room field 'group' to 'folder_id'
Change the name of variable 'group', in og_group struct, to 'folder_id'.

Change payload field to 'folder_id'

These changes are to make code easier to understand.
2024-01-11 13:35:41 +01:00
OpenGnSys Support Team 41ce640033 rest: update og_uri_handle with new folder commands
Add folder/add and folder/delete, otherwise logging shows "unknown"
2024-01-11 12:14:43 +01:00
Javier Hernandez 529d83b19e rest: Support adding clients inside folder
Add support for adding clients that are inside a folder.

Add new folder_id field, if zero it means computer is not in a folder.
2024-01-11 12:10:04 +01:00
Javier Hernandez bc787a9a68 rest: Add support for deleting folders
Add support for deleting folders containing rooms. Delete rooms that are
in folder.
Computers inside rooms are automatically deleted in cascade when room is
deleted (implemented in sql)

Add support for deleting folders containing clients. Delete clients that are
in folder.
2024-01-10 13:06:47 +01:00
Javier Hernandez 1fb425694c rest: Add support for adding folders
Add support for adding computer folders and room folders.
2024-01-09 12:57:28 +01:00
Javier Hernandez 28ab2aa9b0 rest: Use mask to differentiate folder types
marker tells us if this folder to group rooms or computers.

this is a woraround because the database has two tables to store room and
computer folders, there is no unique id.

the tables cannot be merged yet because of the legacy web console, to overcome
this limitation, add a marker that provides a unique id to differentiate room
and computer folder.

this assumes only 65535 room folders are possible because the marker is
0x000010000 (65536)
2024-01-08 13:08:55 +01:00
OpenGnSys Support Team a7727e40ea rest: allow to set boot mode in client/update
Allow to specify .boot field and call set_client_mode() to update
the boot mode.
2023-12-21 12:18:40 +01:00
OpenGnSys Support Team 3b3fc32999 rest: missing POST /image/update in syslog
Update it so it shows in syslog, instead of unknown:

Dec 19 18:31:18 ogserver ogserver[1133]: 127.0.0.1:36538 POST /unknown clients=150.128.34.25
2023-12-21 11:58:48 +01:00
OpenGnSys Support Team cdff83d091 rest: cannot fail with image/create if it exists
legacy web console uses this REST API to refresh an existing image.

Relax check not to break things.
2023-12-19 13:34:32 +01:00
OpenGnSys Support Team f64b1c2767 rest: add POST image/update
add explicit API to update an image
2023-12-19 12:42:32 +01:00
OpenGnSys Support Team 7292c30659 rest: no assumption on description field in create/image
do not use description field to decide if this is a new image or an update.

add og_dbi_get_image() to check if the image exists. If it is not found, then
add new image entry to database.

update og_dbi_add_image() to update the image.id field.
2023-12-19 12:20:34 +01:00
OpenGnSys Support Team bad351b1d7 rest: log failed to delete entry from table
add logging to report failure to remove entry.
2023-12-18 12:20:52 +01:00
OpenGnSys Support Team b100c570a0 rest: do not exit() if execlp() fails
execlp() should not ever fail, but if it ever happens, return -1 instead of
exitting this daemon.
2023-12-15 11:12:49 +01:00
OpenGnSys Support Team 5e8e1c6467 rest: do not report error when removing image file
this file might be in a different repository, this is best effort.
2023-12-15 11:12:46 +01:00
OpenGnSys Support Team ee09056908 client: parse permissions and lastupdate in /image/create response from client
Use permissions and last update from client.

update src/schema.c to add a new database version.
2023-12-12 17:02:44 +01:00
OpenGnSys Support Team e3b8f3d2f9 client: stub to parse size field in /image/create response from client
Still incomplete, src/schema.c needs to be update to add a new field to the
'imagenes' table in the database.
2023-12-12 11:30:31 +01:00
OpenGnSys Support Team 721ab28fdf rest: expose description in GET /images
add .description field to json.
2023-12-12 10:23:46 +01:00
OpenGnSys Support Team 16d7a18441 dbi: og_computer_get_info() uses netmask field in 'room' table
netmask field in 'computers' table is never used, but ogcli still
displays it through:

 # ogcli list client --client-ip 1.2.3.4

and it shows '0' or incorrect netmask (ogCP hardcodes this field).

Update SQL query to fetch the room.netmask instead.
2023-11-30 20:58:04 +01:00
OpenGnSys Support Team edac32bb98 rest: add GET /room/info
Add GET /room/info to obtain room information, this includes the name,
gateway and netmask.

curl -X GET -H "Authorization: $API_KEY" http://127.0.0.1:8888/room/info -d '{ "id" : 1 }
2023-11-30 20:20:07 +01:00
OpenGnSys Support Team 1ce5624032 rest: fix client/info maintenance field
Use computer.maintenance instead of computer.name.

Fixes: af47a082ad ("#1004 Add GET /client/info HTTP REST method")
2023-11-30 10:04:19 +01:00
Javier Hernandez 5ff92a826e rest: add POST repository/update
Add POST repository/update request to update repository. Repository is
identified by its id, that is provided in the payload.

This can be tested with curl like:
curl -X POST -H "Authorization: $API_KEY"
http://127.0.0.1:8888/repository/update -d '{ "repo_id" : 16, "center" :
3, "name": "newName", "ip":"127.0.0.1" }'
2023-11-24 11:02:52 +01:00
OpenGnSys Support Team 0ab4721714 core: remove useless log when ogClient connects to server
The following log message is display for each ogClient that is connected to
the ogServer:

 Sent refresh to: 192.168.2.200

this tells the ogClient to send his current partition table when the connection
between ogServer <-> ogClient starts. This is not very useful, remove it.
2023-11-23 22:08:49 +01:00
OpenGnSys Support Team 56e4a01af0 rest: revisit logging
Skip logging for the following REST API invocations:

- GET /scopes
- GET /clients
- POST /clients (for legacy web console only)

The web front-end generated very frequent requests for this.

Update logging format to:

 127.0.0.1:54637 POST /wol clients=192.168.2.130

to include client IP address.
2023-11-23 22:08:49 +01:00
OpenGnSys Support Team f8eca04841 rest: fix WoL handling
Valgrind reports a memleak because og_cmd_wol() overrides params->ips_array,
then it releases params->ips_array but og_cmd_free() already does this.

Use a new_params structure to store the IPs that has been filtered through the
database query and check that buffer overrun does not happen.

Fixes: e4cb91b5f6 ("#990 wol: migrate mac and netmask query to ogServer")
2023-11-23 22:08:41 +01:00
OpenGnSys Support Team 2140012535 rest: set center in /repository/add
Set it to 1, ogCP and ogCLI never use this, and this REST API is never
used by the old web console.
2023-11-23 12:48:08 +01:00
OpenGnSys Support Team 9c69f112de rest: remove dead code in /repository/add
Remove unused code in this request and do not assume center id.
2023-11-23 10:19:36 +01:00
Javier Hernandez fc0f19fe30 rest: add /client/update
Add POST client/update request to update client, this is identified by its ip
address, with the data provided in the payload.
2023-11-23 10:16:09 +01:00
OpenGnSys Support Team e7c4e16602 main: use etc folder instead of cfg to store .json configuration file
debian packages use etc, so update source code to use this folder too.
2023-11-14 11:26:19 +01:00
OpenGnSys Support Team 944fef7b04 core: restrict rest API to 127.0.0.1
Until there is TLS support for this, frontend and ogserver needs to be in the
same box by now.
2023-11-14 11:25:42 +01:00
Javier Hernandez 485bf92216 rest: Check valid bootmode
ogserver will check that the user provided a valid bootmode. It will go
through the list of all available boot modes and check that the bootmode
provided by the user is in said list; otherwise, it will not set it.
2023-11-06 11:42:50 +01:00
Javier Hernandez fa57af3c13 rest: extract og_get_boot_modes from og_cmd_get_modes()
og_cmd_get_modes() now uses a helper function that returns a list of all boot
modes, this is for a new API REST validate that boot mode is set to something
that exists in a follow up patch.
2023-11-06 10:11:44 +01:00
Javier Hernandez 4c1995d28f rest: Add error check to delete commands
Every time a delete operation is performed it needs to be checked that a row
has been deleted. If no rows are deleted, then ogserver reports an error.

Previous to this change, it only checks that the connection to db
was succesful. For example, previously, if a user deletes a client that did
not exist, ogserver responds with no errors.

After this change, it responds with an error.

This error check has been implemented when deleting:
- A client
- An image
- A center
- A repo
- A room
- A server
2023-11-06 10:11:44 +01:00
OpenGnSys Support Team d3ad9e13e0 rest: use method not found instead of bad request for /clients requests
/clients says bad request for unsupported method, use correct error
report.
2023-10-19 10:46:23 +02:00
Jose M. Guisado 4fca62a8ee rest: extend /repository/add
POST /repository/add checks validity of the repository ip address
specified in the request payload.

/repository/add can optionally receive a center id parameter inside its
request payload. For backward compatibility, the default center id (1)
is used if no center is received inside the request payload.

POST /repository/add returns a JSON response payload containing relevant
fields from the inserted repository.

$ curl 	-D-
	\ -X POST
	\ -H "Authorization: a0e9ab768cbe93dab5b1998e952bcdb7"
  	\ --json '{"name": "helloworld", "ip": "192.168.21.21a", "center": 2}'
	\ localhost:8888/repository/add
HTTP/1.1 400 Bad Request
Content-Length: 0

$ curl 	-D-
	\ -X POST
	\ -H "Authorization: a0e9ab768cbe93dab5b1998e952bcdb7"
  	\ --json '{"name": "helloworld", "ip": "192.168.21.21a", "center": 2}'
	\ localhost:8888/repository/add
HTTP/1.1 200 OK
Content-Length: 54

{"id": 7, "ip": "192.168.21.21", "name": "helloworld"}
2023-10-11 10:28:22 +02:00
Jose M. Guisado 6f6372d0e0 src: move og_repository to dbi.h
Move struct og_repository to dbi.h and use field max length for name and
ip.

Use og_json_parse_string_copy instead of og_json_parse_string to check
maximum length against the request payload.

Fixes: 86ccc3c2e8 ("#915 Add POST /repository/add")
2023-10-10 18:09:19 +02:00
Jose M. Guisado dc68d0f135 rest: add POST /client/repo
Set a client repository in the OpenGnsys database using the endpoint
POST /client/repo.

Expects "clients" and "id" parameters in the request payload.

    POST /client/repo
    {
      "clients": [...],
      "id": "2"
    }

    Response:
    200 OK
2023-10-10 18:09:19 +02:00
Jose M. Guisado 51b70966fc rest: fix sql typo in og_set_client_mode
Replace invalid variable @ipserveradm by @serverip in the SQL query of
og_set_client_mode.

@ipserveradm is a typo as this variable does not exists. This ends up
feeding a string to the legacy setclientmode code and crashes.

This bug also caused problems when adding clients via ogCP or any other
command that required running the set client mode logic.

Fixes: e080fd5526
(rest: add "server=" boot param in set client mode)
2023-09-29 14:53:12 +02:00
Jose M. Guisado 35a3b0a1a3 schema: fix bug when og_dbi_open cannot open a connection
When og_dbi_open cannot open a connection during schema update, then
ogServer crashes.

og_dbi_open returns NULL when it cannot open a DB connection.

Do not use dbi variable if og_dbi_open is unable to open a DB
connection.

Add syslog message when database schema couldn't be updated.
2023-09-28 10:07:07 +02:00
Jose M. Guisado e080fd5526 rest: add "server=" boot param in set client mode
Store a client associated ogserver ip address in "server=" boot param.

Use this boot param to lookup for network-specific ogClient
configuration when launching ogClient during ogLive booting process.
2023-08-28 12:29:33 +02:00
Jose M. Guisado 18eb19ab42 rest: return server_id in GET /client/info
struct og_computer holds the value of "identorno" column inside the
server_id field.

Extend GET /client/info payload with server_id. This way clients can
get the associated server id when requesting client information.

{
...
"server_id": 1,
}
2023-08-23 15:35:34 +02:00
Jose M. Guisado 4cc2ca61fd dbi: add server_id to og_computer struct
Extend og_dbi_get_computer_info to fetch "identorno" column from
"ordenadores". "identorno" holds the row id value from the "entornos"
table (valid ogserver addresses).

Extend og_computer struct with a new field: "server_id" that will store
the value of "identorno" column fetched from the database.
2023-08-23 15:34:44 +02:00
Jose M. Guisado 44745a3f22 rest: add POST client/server method
Enable modification of the associated ogserver of a given client.

This API is exposed via the POST /client/server endpoint and expects a
JSON payload with an array of clients ("client":[]) and the "id" of the
ogserver ("identorno" column value inside the "entornos" table)

For example:

>>>
POST /client/server
{
  "client": [
    "10.141.10.100",
    "10.141.10.101",
    "10.141.10.104",
    "10.141.10.102"
  ],
  "id": "6"
}
<<<
HTTP/1.1 200 OK

If the ogserver id does not exist the foreign key constraint (ON UPDATE
RESTRICT) inside the "ordenadores" table will cancel the operation and
the server will reply with 400 Bad Request.

>>>
POST /client/server
{
  "client": [
    "10.141.10.100",
    "10.141.10.101",
    "10.141.10.104",
    "10.141.10.102"
  ],
  "id": "666"
}
<<<
HTTP/1.1 400 Bad Request

The OpenGnsys database stores different ip addresses for the ogServer
inside the "entornos" table. This table is related to the "ordenadores"
table using a foreign key on the "identorno" column.

i.e: Clients in the "ordenadores" table associate to an specific server
in the database using the "identorno" column (from "entornos" table).
2023-08-23 13:17:03 +02:00
Jose M. Guisado a67c1088ef rest: add DELETE operation to /server endpoint
Expose deletion of rows from "entornos" table via the /server
endpoint using the DELETE http request method.

The expected payload is the server id as a string. For example:

>>>
DELETE /server
{ "id": "4" }

<<<
200 OK

If the specified server is currently associated with any computer
("ordenadores" table) the foreign key contraint (ON DELETE RESTRICT)
will avoid the deletion and the server responds with
400 Bad Request.

>>>
DELETE /server
{ "id": "1" }

<<<
400 Bad Request
2023-08-23 11:39:19 +02:00
Jose M. Guisado b2c8c9d9ab rest: support DELETE HTTP request method
Reuse endpoints in order to add deletion operation such as "/server".
This way there is no need to declare a different if/else block in order
to parse a new URI for the new "*/delete" endpoint.

Current deletion operations are implemented using a different endpoint
name such as "/client/delete", "/center/delete" with POST request method.

Endpoints using "/delete" suffix may not be removed for backwards
compatibility. Adding HTTP method DELETE support for endpoints such as
"/center" or "/client" can use the already existing *_post_delete*
functions.
2023-08-23 11:39:19 +02:00
Jose M. Guisado 351069b591 rest: add /server GET and POST methods
DB stores different ogserver addresses in the "entornos" table.

Expose addition and deletion operations for the "entornos" table using
the /server endpoint.

GET /server returns a list of rows from the "entornos" table including
the "identorno" and "ipserveradm" columns. For example:

>>>
GET /server

<<<
200 OK
...
{
  "servers": [
    {
      "id": 1,
      "address": "10.141.10.1"
    }
  ]
}

POST /server inserts into the "entornos" table and returns the
id ("identorno") of the new row.

>>>
POST /server
{
  "address": "192.168.2.240"
}

<<<
200 OK
...
{
  "id": 2
}

If the server address already exists the response is 400 Bad Request
with no payload.

>>>
POST /server
{
  "address": "192.168.2.240"
}

<<<
400 Bad Request
2023-08-23 11:39:10 +02:00
Jose M. Guisado 74b6e3ec72 rest: add optional param "backup" for create_image
This parameter is used by ogServer to instruct target client if image
backup should be performed before image creation.

This parameter is optional to preserve backward compatibility with
webconsole (legacy web client) and avoid the need of updating any legacy
client.

Default is true if the REST request is missing this parameter.
2023-07-07 10:04:36 +02:00
Jose M. Guisado 3de8c25e4e core: log payload if sequences do not match
We need to inspect the received payload if any error is raised related
to the X-Sequence header. Not just when a malformed X-Sequence header is
detected.

Fixes: d2c19ef13d ("core: add X-Sequence header support")
2023-07-03 09:17:53 +02:00
Jose M. Guisado d2c19ef13d core: add X-Sequence header support
Add non-standard HTTP header "X-Sequence" to the header section of
requests (og_send_request) sent to a connected client.

Define a starting sequence number when creating a new instance of struct
og_client inside og_server_accept_cb. This sequence number is
incremented by one for each outgoing request from ogServer.

This sequence number is checked when receiving a response from a
connected client, if they do not match the connection is dropped.

Use sequence 0 for out-of-band commands (reboot, poweroff, stop). Any
client response with header "X-Sequence: 0" bypasses sequence check.
2023-06-13 14:04:54 +02:00
Jose M. Guisado 92f83c0385 client: harden og_resp_refresh
Harden refresh response logic. Check for necessary JSON fields inside
the payload.

Check if serial_number is null before calling strlen, prevent ogServer
from a malformed refresh response with missing serial_number.

Refresh uses legacy function actualizaConfiguracion that takes a long
string with the computers configuration (serialno, partitions, disks,
link speed and status). Check for an empty string before executing any
legacy code inside actualizaConfiguracion.
2023-06-07 18:32:33 +02:00
Jose M. Guisado 8cf02475ba client: increase software inventory buffer size
Large software inventory is truncated because it does not fit into the
existing buffer.

Software inventory response payload consists of a string with each
component delimited by '\n'. Large software inventories can consist of
more than 8192 bytes.

Avoid truncating any large software inventory by increasing the buffer
size where this string is stored.
2023-04-20 10:08:52 +02:00
Javier Sánchez Parra 25e21f435d Log ogClient sessions in ogagent.log
Otherwise, administrators can not read the logging history from
WebConsole.
2022-11-02 13:59:28 +01:00
Javier Sánchez Parra 2213d005ff #915 List all database images.
ogServer "GET /images" list images that exist simultaneously in database
and in disk (/opt/opengnsys/images).

With this patch, ogServer list all images in database, exist or not in
disk. If an image exists in disk, it retrieves more information about
them.

This change is useful for environments where images are in different
machines/repositories.
2022-07-07 12:29:47 +02:00
Javier Sánchez Parra 5cf2de704c #915 Add POST /repository/delete
This method deletes a repository from the database.

Request:
POST /repository/delete
{
  "id": "10"
}

Response:
200 OK
2022-07-01 12:09:16 +02:00
Javier Sánchez Parra 86ccc3c2e8 #915 Add POST /repository/add
This method adds a new repository to the database.

Request:
POST /repository/add
{
  "name": "Repository 1",
  "ip": "192.168.56.10"
}

Response:
200 OK
2022-07-01 12:09:16 +02:00
Javier Sánchez Parra 9ecf638ba2 #915 Extend GET /repositories with param id
Add id parameter to the response. This is useful to identify
repositories that have several IPs.

Request:
GET /repositories
{
  "repositories": [
    {
      "id": 1,
      "ip": "192.168.56.10",
      "name": "Repositorio (Default)"
    }
  ]
}

Response:
200 OK

Related-to: d5e6dc0 ("#915 Add API GET /repositories")
2022-06-23 13:12:59 +02:00
Javier Sánchez Parra ce4eb4d833 #915 Fix missing id on image creation
On image creation, ogServer always sends 0 as image id to clients. When
clients sends the response to the "create image" command with new
information to update the image's entry in the database, the image id is
0 and ogServer fails to update the image's entry.

This patch fixes this, assigning the correct id of the image.

Fixes: d2f20d0be0 ("#942 Create DB image when calling POST /image/create")
2022-06-20 16:07:53 +02:00
Javier Sánchez Parra 30d6af09d5 #915 Use the repository id on image list
API "GET /images" shows the repository ID the image belongs to, instead
of the IP. This is a preparative commit to the support of repositories
with several IPs.

Request GET /images
Response 200 OK:
{
  "images": [
    {
      "name": "windows10",
      "datasize": 0,
      "size": 626088433,
      "modified": "Fri Jun 10 12:20:32 2022",
      "permissions": "744",
      "software_id": 1,
      "type": 1,
      "id": 6,
      "repo_id": 1
    }
  ],
  "disk": {
    "total": 52573995008,
    "free": 38964637696
  }
}
2022-06-20 10:41:50 +02:00
Javier Sánchez Parra 52a38d3e57 #915 Use the repository id on image creation
POST /image/create has two modes, image creation and update. You can
find more information about the "creation" mode in commit:
d2f20d0be0

On image creation, use the id to identify repositories instead of the
IP. This is a preparative commit to the support of repositories with
several IPs.

On image update, "repository_id" field is not needed because the image
already has the repository assigned.

This commit maintains backward compatibility with the Web Console (old
web interface), because it only use the "update" mode of /image/create.

Request POST /create/image:
{
  "clients": [
    "192.168.56.11"
  ],
  "disk": "1",
  "partition": "1",
  "name": "archlinux",
  "repository_id": 1,
  "id": "0",
  "code": "131",
  "description": "This is a test",
  "group_id": 0,
  "center_id": 1
}
Response 200 OK
2022-06-20 10:41:32 +02:00
Javier Sánchez Parra a0a3470682 #1074 rest: set_mode: add support for different ogserver addresses
Add foreign key "identornos" from table "entornos" to table
"ordenadores".

A row in table "entornos" represent a valid ogServer address.
Multiple ogServer valid addresses can exist when running several
instances or a single ogServer instance is exposed to different networks.

Can't delete rows in "entornos" table nor update their id (primary
key) if the row has any associated clients ({ON UPDATE/ON DELETE} RESTRICT).

Allows assigning different but valid ogServer IPs to clients.
Enabling support for multiple instances of ogServer (e.g: load balancing) or
exposing a single ogServer instance to different networks (e.g: VLAN).

Look up for the valid ogServer IP of a given client when changing a
client's mode (og_set_client_mode).

Determines valid ogServer IP using a JOIN statement.

	JOIN entornos USING(identorno)

Reuses the fetched ip using a statement variable.

	@serverip:=entornos.ipserveradm

For example, for a two VLAN setup:

	vlan1 ogserver: 192.168.56.10
	vlan2 ogserver: 192.168.57.10

The "entornos" table should look like:

	identorno       ipserveradm             ...
	---------       -----------             ...
	1               192.168.56.10           ...
	2               192.168.57.10           ...

And computers in the "ordenadores" table might look like:

	idordenador     identorno       ...
	----------      ---------       ...
	1               1               ...
	2               1               ...
	3               2               ...
	4               2               ...
	...             ...             ...

Additionally, splits the SQL query for better readability.

Co-authored-by: Jose Guisado <jguisado@soleta.eu>
2022-06-01 08:51:19 +02:00
Javier Sánchez Parra c0573b9ef0 #915 Set repository on image creation
Assign to the image the repository indicated in the JSON body instead of
a default one.
2022-05-26 15:15:52 +02:00
Javier Sánchez Parra b86b6e1443 #915 Extend GET /images function with the repository IP
This extension adds the field 'repo_ip', indicating which repository has
the image. This new field is useful when restoring an image.

Request:
GET /images

Response:
200 OK
{
  "disk": {
    "free": 37091418112,
    "total": 52573995008
  },
  "images": [
    {
      "datasize": 5939200000,
      "id": 25,
      "modified": "Wed Oct 14 11:49:00 2020",
      "name": "archlinux",
      "permissions": "744",
      "size": 1844222333,
      "software_id": 19,
      "type": 1
      "repo_ip": "192.168.56.10"
    }
  ]
}
2022-05-26 15:15:52 +02:00
Javier Sánchez Parra d5e6dc0990 #915 Add API GET /repositories
This API returns a list of available images repositories.

Request:
GET /repositories

Response
200 OK
{
  "repositories": [
    {
      "ip": "192.168.56.10",
      "name": "Default"
    },
    {
      "ip": "192.168.57.10",
      "name": "Extra"
    }
  ]
}
2022-05-26 15:15:29 +02:00
Javier Sánchez Parra 9b6171300b #915 Fix conditional jump depending on uninitialised value
Valgrind says:

==9452== 1 errors in context 1 of 38:
==9452== Conditional jump or move depends on uninitialised value(s)
==9452==    at 0x11BD1E: og_resp_refresh (client.c:383)
==9452==    by 0x11CF2A: og_agent_state_process_response (client.c:822)
==9452==    by 0x112FCE: og_agent_read_cb (core.c:254)
==9452==    by 0x4E41D72: ev_invoke_pending (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==9452==    by 0x4E453DD: ev_run (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==9452==    by 0x1107CD: ev_loop (ev.h:835)
==9452==    by 0x1107CD: main (main.c:108)
==9452==  Uninitialised value was created by a stack allocation
==9452==    at 0x11BB02: og_resp_refresh (client.c:348)

Fixes: f03425e ("#915 Add support for link speed in the refresh response")
2022-05-18 16:50:24 +02:00
Javier Sánchez Parra df5161ebc3 #915 Add last_cmd to GET /clients API
"last_cmd" json object contains information of the last command executed
by the correspondent client. For now, it only includes "result" string
property, which stores "success" if the last command finished correctly
or "failure" on the contrary.

To populate "result" property, this commit also adds "last_cmd_result"
enum attribute to og_client struct. Client response processing fills
this attribute according to its success.

Clients in WOL_SENT state always have last_cmd->result = "unknown".

Request: GET /clients

Response: 200 OK
{
  "clients": [
    {
      "addr": "10.141.10.102",
      "state": "WOL_SENT",
      "last_cmd": {
        "result": "unknown"
      }
    },
    {
      "addr": "10.141.10.101",
      "state": "OPG",
      "speed": 1000,
      "last_cmd": {
        "result": "success"
      }
    },
    {
      "addr": "10.141.10.100",
      "state": "OPG",
      "speed": 1000,
      "last_cmd": {
        "result": "failure"
      }
    }
  ]
}
2022-05-18 16:50:14 +02:00
Javier Sánchez Parra f03425e6ae #915 Add support for link speed in the refresh response
Add ogServer support for parsing and storing the link speed from
ogClient's refresh response.

Probe response already has client's link speed, but this API is
deprecated.
2022-05-09 12:18:56 +02:00
Javier Sánchez Parra f2d83cef7d #915 Set boot mode to ogLive on client creation
Otherwise, users have to use POST /modes to make clients bootable.
2022-03-28 13:46:58 +02:00
Javier Sánchez Parra 0e47f675e0 #915 Remove template_name from og_set_client_mode
This argument is not needed for setting clients' boot mode.
2022-03-28 13:15:21 +02:00
OpenGnSys Support Team f3422f6afa #915 add seconds since ogserver has been launched
Extend GET /stats to show the number of seconds since the ogserver started.

{
       "time": {
          "now": 1647262765,     /* Seconds since 1970 */
          "boot": 2151909        /* Seconds since boot */
	  "start" : 1647262854,, /* Seconds since 1970 */
       },
       [...]
2022-03-25 14:58:27 +01:00
Javier Sánchez Parra 3b4aa721a4 #915 Add GET /stats REST request
This request returns certain statistics on memory and swap usage, as
well as the uptime.

The below structure gives the sizes of the memory and swap fields in
bytes.

Request: GET /stats
NO BODY

Response: 200 OK
{
   "time": {
      "now": 1647262765,     /* Seconds since 1970 */
      "boot": 2151909        /* Seconds since boot */
   },
   "memory": {
      "size": 4104679424,    /* Total usable main memory size */
      "free": 322174976      /* Available memory size */
   },
   "swap": {
      "size": 2147479552,    /* Total swap space size */
      "free": 2122563584     /* Swap space still available */
   }
}
2022-03-14 14:46:13 +01:00
Jose M. Guisado 281d661fc9 #1065 og_client_status compatible with webconsole
Report linux and windows client status in a compatible manner
with webconsole.  This way clients are colored accordingly in
a room view depending on their status.

WIN/WINS: Windows, Windows session
LNX/LNXS: Linux, Linux session
2022-02-02 17:35:49 +01:00
OpenGnSys Support Team 1379ee95f4 #1043 check for WoL pending confirmation logic only for client
REST API request does not need to perform a list lookup on the wol list.
2022-01-21 15:18:50 +01:00
OpenGnSys Support Team 20301007a1 #915 release existing client on reconnections
Trasient network problems might result in duplicated clients, drop
client object if it already exists before creating a new one.
2022-01-21 15:18:47 +01:00
OpenGnSys Support Team b8b3839bba #915 remove temporary file to store shell output
Remove legacy behaviour, store it in the client object instead of a temporary
file.
2022-01-18 10:48:59 +01:00
Javier Sánchez Parra eaf7ed9da0 #915 Initialize group when adding a new client to DB
Other methods expect not NULL clients' group.
2022-01-17 11:22:13 +01:00
OpenGnSys Support Team 4e2ef1a13e #1067 fix use-after-free in deliver pending command
Do not release the json object twice, once from og_send_request() and
again og_cmd_free().

Valgrind reports:

==11885== Invalid read of size 8
==11885==    at 0x117B9A: json_decref (jansson.h:128)
==11885==    by 0x117B9A: og_cmd_free (rest.c:2409)
==11885==    by 0x113465: og_agent_deliver_pending_cmd (core.c:211)
==11885==    by 0x113465: og_agent_read_cb (core.c:256)
==11885==    by 0x4E41D72: ev_invoke_pending (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==11885==    by 0x4E453DD: ev_run (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==11885==    by 0x110C2D: ev_loop (ev.h:835)
==11885==    by 0x110C2D: main (main.c:104)
==11885==  Address 0x8e7e988 is 8 bytes inside a block of size 72 free'd
==11885==    at 0x4C32D3B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11885==    by 0x117437: json_decref (jansson.h:129)
==11885==    by 0x117437: og_send_request (rest.c:330)
==11885==    by 0x113454: og_agent_deliver_pending_cmd (core.c:208)
==11885==    by 0x113454: og_agent_read_cb (core.c:256)
==11885==    by 0x4E41D72: ev_invoke_pending (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==11885==    by 0x4E453DD: ev_run (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==11885==    by 0x110C2D: ev_loop (ev.h:835)
==11885==    by 0x110C2D: main (main.c:104)
==11885==  Block was alloc'd at
==11885==    at 0x4C31B0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11885==    by 0x526461A: json_object (in /usr/lib/x86_64-linux-gnu/libjansson.so.4.11.0)
==11885==    by 0x116A07: og_cmd_legacy_image_restore (rest.c:2627)
==11885==    by 0x116A07: og_cmd_legacy (rest.c:2757)
==11885==    by 0x116A07: og_queue_task_command (rest.c:2848)
==11885==    by 0x118284: og_dbi_queue_command (rest.c:3109)
==11885==    by 0x118284: og_schedule_run (rest.c:3190)
==11885==    by 0x1147B9: og_agent_timer_cb (schedule.c:445)
==11885==    by 0x4E41D72: ev_invoke_pending (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==11885==    by 0x4E453DD: ev_run (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==11885==    by 0x110C2D: ev_loop (ev.h:835)
==11885==    by 0x110C2D: main (main.c:104)
2021-12-23 15:33:29 +01:00
OpenGnSys Support Team 216986e848 #915 consolidate WoL sender function
This patch aims simplifies the WoL sender routine.

A few related changes:
- Replace goto err to continue if IP address is malformed
- Use ret |= instead of ret &= to accumulate error code.
2021-12-22 17:30:04 +01:00
OpenGnSys Support Team 6e70916005 #915 remove shim code to update database after image restore command
Make direct call to dbi API to update database instead.
2021-12-22 17:30:04 +01:00
OpenGnSys Support Team facd0d56e7 #915 remove dead code in ogAdmLib
Remove declarations that are not used anymore in ogAdmLib.
2021-12-22 17:30:04 +01:00
OpenGnSys Support Team 41ac15d100 #915 Remove useless WoL shim code
Levanta() is not required, iterate over the array of IP address and make
direct calls to WakeUp().

This is also implicitly fixing up a memleak in og_cmd_wol().
2021-12-20 12:18:46 +01:00
Javier Sánchez Parra dd578a944e #915 Add POST /oglive/set REST request
This patch allows you to update clients' database entry and PXE boot
file with the specified ogLive.

If you specify either an incorrect or unexisting ogLive, then, clients
use the default ogLive image. You can query ogLives installed on the
server with ogServer's GET /oglive/list API.

If you set the oglive field to "default", then the default ogLive is
used.

Request: POST /oglive/set
{
  "clients": ["192.168.56.11", "192.168.56.12"],
  "name": "ogLive-5.4.0-r20200629"
}
Response: 200 OK
2021-12-17 10:31:41 +01:00
Jose M. Guisado ff9dbd9033 #1065 split og_status_session_toggle
Handles non usual situations like a client sending more than
one event of same type.

When toggling, receiving two events of the same type is the
same as receiving two different ones (eg. start, then stop).

Split into _session_start and _session_stop in order to check
valid client status.
2021-12-03 09:14:07 +01:00
Jose M. Guisado 772811e76f #1065 Add support for client events
ogServer supports events from clients in an agent mode
(linux/windows).

Client sends event information (eg. user login/logout)
via a 103 Early Hints http response message.
2021-12-01 15:14:24 +01:00
Javier Sánchez Parra a801e788e8 #915 Add folders to scope
The database represents rooms groups and computers groups scope sets
with "grupos" (groups) and "gruposordenadores" (computers groups) tables
respectively. With this commit, ogServer abstracts both sets and offers
them though the API as the set "folder".

"grupos" table do not only group rooms, it can group other
elements of the database. You can see which kind of elements groups
looking at the column "tipo".

This commit often refers "rooms group" as group and "computers
group" as computers.

Request:
GET /scopes
NO BODY

Response
200 OK
{
  "scope": [
    {
      "name": "center1",
      "type": "center",
      "id": 1,
      "scope": [
        {
          "name": "folder1",
          "type": "folder",
          "id": 1,
          "scope": [
            {
              "name": "folder2",
              "type": "folder",
              "id": 2,
              "scope": []
            },
            {
              "name": "room1",
              "type": "room",
              "id": 2,
              "scope": [
                {
                  "name": "folder3",
                  "type": "folder",
                  "id": 3,
                  "scope": [
                    {
                      "name": "folder4",
                      "type": "folder",
                      "id": 4,
                      "scope": []
                    },
                    {
                      "name": "computer1",
                      "type": "computer",
                      "id": 8,
                      "scope": [],
                      "ip": "192.168.56.12"
                    }
                  ]
                },
                {
                  "name": "computer2",
                  "type": "computer",
                  "id": 7,
                  "scope": [],
                  "ip": "172.18.0.71"
                }
              ]
            }
          ]
        },
        {
          "name": "room2",
          "type": "room",
          "id": 1,
          "scope": []
        }
      ]
    }
  ]
}
2021-11-26 16:48:41 +01:00
OpenGnSys Support Team 64bbc0cf3f #1043 fix timeout refresh
as described by man(3) ev, to make it work with ev_timer_again()
otherwise timer might not ever expire.
2021-11-23 13:58:12 +01:00
Jose M. Guisado b6b1040997 #1065 client: add support for ogclient win state
ogClient can be run in windows mode, enabling connection with ogServer
when running on a Windows machine.

Don't expect the same payload in windows mode as a in live or virtual.
Client in windows mode does not send partition setup information, only
the status/state. (same case for linux mode)
2021-11-17 10:36:50 +01:00
Jose M. Guisado 5a3fd51261 #1065 client: add support for ogclient linux state
ogClient can be run in linux mode, intended for exposing some
ogServer commands when running in a linux distribution.

When connecting with a client in linux mode, do not expect a full
partition setup response. Just expect a 'status', and then accept
the connection without updating any partition information in
the database.
2021-11-17 09:07:57 +01:00
OpenGnSys Support Team ac3ce22c35 #1064 revisit error handling from ogClient
200 => successful command, run next pending command
202 => successful command in progress, do not run next pending command
403 => server sent a malformed HTTP header, should not ever happen,
       close connection (server is buggy?).
500 => client fails to run command, report error and run next pending command
503 => client is busy, report error and do not run next pending command

Anything else, should not ever happen (client is buggy?), close connection with
client.

On error, when processing response from ogClient, do not close the connection,
instead annotate in the database that command was not successful and run next
pending command.

*Only* if client replies status code 500 set last_cmd to UNSPEC so its state is
not BSY as reported by og_client_status function and pending cmds can be
sent.
2021-11-12 11:06:13 +01:00
OpenGnSys Support Team 6fc89cdfc4 #1042 incorrect initialization of software profiles array
The position 0 of the software profiles array is not initialized,
this triggers a bug randomly on image creation if the position 0
comes zero. Adjust the loop to initialize position 0 accordingly.
2021-10-20 09:57:41 +02:00
Jose M. Guisado e16f36cdef #915 Fix create image payload parsing
Commit 141b0797e1 introduced command scheduling rest api to
ogserver. Part of this changeset included
og_json_parse_create_image as a utility funtion to parse the json
payload of a "create image" command.

og_json_parse_create_image did not include the parsing of optional
parameters "description", "center_id" and "group_id". New components
like ogCP or ogCLI use these parameters.

Fix this by adding a struct og_image member to the struct og_msg_params
and assigning it when processing a "create image" command.

This could be extended to further payload parsing for image related
commands in the future.
2021-10-19 07:54:35 +00:00
Javier Sánchez Parra 36f02324e0 #915 Add POST /image/delete method
Delete operation for images stored in the server. It deletes an image
from the database and filesystem, thus images must exists in both places.

POST /image/delete
{
	"image": "3"
}
2021-10-04 17:44:50 +02:00
Jose M. Guisado 2d68f8a0ec #1061 add timeout to pending scheduled commands
Pending schedule commands can deny ogLive boot of clients due
to filling of pending cmd queue with commands such as "Iniciar Sesión".

For example: Using RemotePC to serve clients that do not boot into
ogLive will fill up the pending command queue with "Iniciar Sesión".

Introduce a safety timeout for pending (scheduled) commands to
avoid this situation.
2021-09-06 12:32:38 +02:00
Jose M. Guisado 047677bb4b #1054 Fix og_legacy_partition code buffer size
The "code" member of the og_legacy_partition is used to hold the string of
the partition type *name* for legacy parameter strings. Example:

par=2*cpt=LINUX-SWAP*sfi=LINUX-SWAP*tam=10000000*ope=0

Problem: Buffer size is smaller than possible values for this member.
Fix: Increase buffer size up to the max length defined in the DB
for the corresponding column.
2021-07-26 16:58:40 +02:00
Jose M. Guisado 8190c6f6df #1051 Initialize task_id once in og_cmd_post_schedule_command
Fixes task_id re-initialization in commit 33d8cecfe.

Task id is to be initialized with the "session" value and can be done
out of the for loop it was before. Avoiding unnecesary snprintf's with
the same value.
2021-07-22 16:06:26 +02:00
Jose M. Guisado 261d490c4e #1052 Populate session column when adding actions
If the scope of a command, procedure or task is related to a group of
computers then actions associated with that schedule can share the same
session value.

og_dbi_add_action was not initializing session value, as it is only used
for visualization purposes in the legacy web interface.

This patch enables og_dbi_add_action to populate session column by
assigning it the id value of the first action related to the scope.

Example: Power off command for a room scope of 4 clients will result in
4 actions, a power off for each client. The first action id will determine
the session value for the rest.
2021-07-22 15:52:12 +02:00
Jose M. Guisado 33d8cecfe1 #1051 Fix command schedule for several clients
A single command can be schedule for several clients.

Commit 141b0797e1 introduces a regression when scheduling a command for
several clients, the command only executes successfuly for the first
one.

Fix it by reintroducing the usage of the 'session' column to group
a single command into several actions (one for each client), the web
console interface already expects this 'session' column to be set
accordingly.
2021-07-21 17:55:55 +02:00
Javier Sánchez Parra 7325a8629e #915 Add POST /task/add method
Adds the possibility to create a task with procedures and other tasks
integrated as steps.

Note: "steps" parameter is optional and "steps" array object order
defines execution order.

Request:
POST /task/add
{
  "center": "1",
  "name": "task",
  "description": "My task",
  "steps": [
             {
               "procedure": 4
             },
             {
               "task": 1
             },
             {
               "procedure": 24
             }
           ]
}

Response:
200 OK

This commit also add task case to procedure's step processing.
Otherwise, gcc prints the following warning:

src/rest.c: In function ‘og_procedure_add_steps’:
src/rest.c:4089:17: warning: enumeration value ‘OG_STEP_TASK’ not handled in switch [-Wswitch]
 4089 |                 switch (step->type) {
      |                 ^~~~~~
2021-07-01 09:20:46 +02:00
Javier Sánchez Parra a496da17ea #915 Add POST /procedure/update method
Adds the possibility to update a procedure with commands and other
procedures integrated as steps.

Note: "steps" parameter is optional and "steps" array object order
defines execution order. Also, if the body has empty steps, the
procedure loses its previous steps.

Request:
POST /procedure/update
{
  "procedure": "34",
  "center": "1",
  "name": "procedure-edited",
  "description": "My procedure edited",
  "steps": [
             {
               "command": "wol",
               "params": { "type": "broadcast" }
             },
             {
               "procedure": 24
             },
             {
               "command": "reboot",
               "params": {}
             }
           ]
}

Response:
200 OK
2021-06-29 11:48:33 +02:00
Javier Sánchez Parra cf7d0742a3 Fix procedure id retrieving in steps creation
Otherwise, procedure id is always zero.

Fixes: 1fdb7e6d1c
2021-06-29 11:48:28 +02:00
Javier Sánchez Parra 66ba6d045e #915 Filter queued commands by id
ogServer searches queued commands (formerly actions) in the DB by
session. This can lead to problems because session is not an uniquely
identifier but an identifier that several commands can share to group
them.

This commit changes query filter from session to id, ensuring correct
results

This reverts commit d9b6aadf66.
2021-06-16 12:16:37 +02:00
Javier Sánchez Parra c03b87dcc6 #915 Add POST /procedure/run method
Add ogServer support procedure execution. Now users can send a procedure
and a list of clients to ogServer, then ogServer breaks down the
procedure into commands (formerly actions) and queues them for each
indicated client.

TODO: Do not reply 200 OK when the procedure do not exist.

Request:
POST /procedure/run
{
  "clients": ["192.168.56.11", "192.168.56.12"],
  "procedure": "33"
}

Response:
200 OK
2021-06-15 12:11:16 +02:00
Jose M. Guisado 830c321062 #915 Add procedure/delete
Delete operation for procedures stored in the database.

POST /procedure/delete
{
	"id": "7"
}

If no procedure is found returns 200 OK but a syslog call is issued to
warn so. Such behavior will likely change in the future.
2021-06-11 11:34:59 +02:00
Jose M. Guisado d9b6aadf66 #915 Revert filtering actions by id to "sesion" in og_dbi_queue_command
Commit 141b079 introduced a slight change in how rows from table
"acciones" are filtered when queuing a command, from "sesion" column to
"idaccion" column.

This seemed reasonable, as id column is the one autoincrementing. But
remotepc queued commands inserting actions id using a timestamp instead
of the action row id.

See c17ffa5d03/admin/WebConsole/rest/remotepc.php (L188)

Revert said change as long as remotepc keeps such behavior.
2021-06-10 17:36:51 +02:00
OpenGnSys Support Team 87774ab087 constify json parse helper function
json_t * parameter is not modified, constify to allow compiler to spew warnings
in case the function tries to modify it.
2021-06-10 17:05:07 +02:00
OpenGnSys Support Team 88c8b52e88 move json function declarations to json.h
These function declarations belong to json.h:

int og_json_parse_partition_setup(json_t *element, struct og_msg_params *params);
int og_json_parse_create_image(json_t *element, struct og_msg_params *params);
int og_json_parse_restore_image(json_t *element, struct og_msg_params *params);
2021-06-10 17:00:43 +02:00
Javier Sánchez Parra 1fdb7e6d1c #915 Add commands and procedures to procedure creation
Adds the possibility to create a procedure with commands and other
procedures integrated as steps.

Note: "steps" parameter is optional and "steps" array object order
defines execution order.

Request:
POST /procedure/add
{
  "center": "1",
  "name": "procedure",
  "description": "My procedure",
  "steps": [
             {
               "command": "wol",
               "params": { "type": "broadcast" }
             },
             {
               "procedure": 22
             },
             {
               "command": "poweroff",
               "params": {}
             }
           ]
}

Response:
200 OK

This commit also updates unit tests for /procedure/add POST method to
include steps.
2021-06-10 17:00:01 +02:00
OpenGnSys Support Team 893101ffc6 missing copyright header to new src/legacy.c file 2021-06-09 23:17:51 +02:00
Jose M. Guisado 141b0797e1 #915 Add schedule/command
Enables ogserver to schedule commands (also referred as actions in
legacy web console jargon).

This feature enables ogserver to write in the "acciones" table in order
to have full capabilities for command scheduling purposes, thus not
depending in the legacy web console to insert into "acciones" table.
2021-06-09 13:41:28 +02:00
Jose M. Guisado cb7fa569b2 #941 Free dbi_inst when og_dbi_open fails to connect
When trying to open a connection to a database, an instance of
libdbi is created before any connection attempt. If connection is
unsuccessful then the og_dbi struct is freed but not the
libdbi instance member, thus leaking its memory.

Use libdbi dbi_shutdown_r to shutdown libdbi instance member
before freeing og_dbi struct inside og_dbi_open.
2021-06-01 14:14:15 +02:00
Javier Sánchez Parra 41fad11408 #942 Add POST /procedure/add method
This method adds a procedure associated with a center to the database.
Required payload parameters are center and name, description is
optional.

Note: ogServer does not allow to add more than one procedure with the
same name and center.

Request:
POST /procedure/add
{
  "center": "1"
  "name": "procedure1"
  "description": "My procedure"
}

Response:
200 OK

This commit also adds unit tests for /procedure/add POST method.
2021-05-31 13:01:47 +02:00
OpenGnSys Support Team ee2f909dbe #1042 fix multiple definition of ogconfig
/usr/bin/ld: src/schema.o:/home/soleta/opengnsys/ogServer/src/schema.c:50: multiple definition of `ogconfig'; src/main.o:/home/soleta/opengnsys/ogServer/src/main.c:31: first defined here
 collect2: error: ld returned 1 exit status
 make: *** [Makefile:411: ogserver] Error 1
2021-05-27 12:22:49 +02:00
Javier Sánchez Parra a00eccc767 #1037 Simplify database update v3 code
Simplify database update v3, no need for iteration.

Fixes: 12d8fff (#1037 Add disk type)
2021-05-27 11:02:42 +02:00
Javier Sánchez Parra 12d8fff3ef #1037 Add disk type
Add ogServer support for parsing and storing in the DB disk type data
from ogClient refresh response.

See also commits with #1037 in ogClient and WebConsole repo.
2021-05-26 17:19:30 +02:00
Javier Sánchez Parra 10c9559dfc #1037 Make partition parameter validation permissive
Otherwise, ogServer rejects the response if ogClient sends more
parameters than required.
2021-05-26 17:19:30 +02:00
Javier Sánchez Parra bc9424724d Add REST POST /room/delete method
This method deletes a room (lab) from the DB and deletes on cascade
computers and computers partitions.

Note: if the room id do not exists in the database, ogserver still
tries to delete it and replies with 200 OK.

Request:
POST /room/delete
{
  "id": "1"
}

Response:
200 OK
2021-05-10 13:39:38 +02:00
Javier Sánchez Parra b48707333f #942 Add REST POST /center/delete method
This method deletes a center from the DB and deletes on cascade
rooms/labs, computers and computers partitions.

Note: if the center id do not exists in the database, ogserver still
tries to delete it and replies with 200 OK.

Request:
POST /center/delete
{
  "id": "1"
}

Response:
200 OK
2021-05-10 12:07:53 +02:00
OpenGnSys Support Team d3e9b5727a #980 ignore unknown attributes
If ogClient sends an unknown attribute, ignore it.
2021-05-04 18:29:15 +02:00
Jose M. Guisado 40d4279b31 #995 Add link speed parsing to client probe response
If a probe response contains speedinformation, parse and store
it inside the client struct. Speed is interpreted as an unsigned
integer representing Mbit/s.
2021-05-04 18:13:35 +02:00
OpenGnSys Support Team a7cce8d442 ogServer is AGPLv3+
Update license header in files.
2021-05-04 17:59:11 +02:00
OpenGnSys Support Team 79e7e2b8c8 #915 only API REST is supported
Socket hidra API has been removed, all connections use a REST API.
2021-05-04 16:14:38 +02:00
OpenGnSys Support Team 8a0a32cea1 #580 remove old keepalive code
Needed by the old socket Hydra that does not exist anymore
2021-05-04 16:11:34 +02:00
Jose M. Guisado 927d42bdf8 #1043 don't create wol entries when client is connected
Avoids multiple entries of a same client like

{"clients": [{"addr": "192.168.2.230", "state": "WOL_SENT"}, {"addr": "192.168.2.230", "state": "OPG"}]

These can arise when ogserver processes a WoL request for an already
connected client.

When processing the WoL request, search for the target address in the
clients list, if found we avoid creating the wol entry.
2021-04-29 13:11:34 +02:00
OpenGnSys Support Team 1f13855e41 #1043 add WOL_SENT state
WOL_SENT tells that WakeOnLan was sent to computer, after 60 seconds,
if computer does not boot, this state is released.
2021-04-29 11:52:32 +02:00
OpenGnSys Support Team c05f1345e7 #1043 add function to append client to json tree
og_json_client_append() adds a client objet to the json tree.
2021-04-29 11:52:04 +02:00
Jose M. Guisado 8775c06d36 #1042 Add schema version 2
Add foreign keys (version 1 introduced innoDB as default db engine)
allowing cascade deletions for some tables:

	- perfilessoft_softwares

	If a software profile or a software component is deleted, the
	corresponding row in this table will be deleted too.

	- ordenadores_particiones

	If a computer or a partition is deleted from the DB, delete the
	corresponding row inside this table.

	- aulas

	If the center the room is in is removed, delete the room too.

	- ordenadores

	If the room in which a computer is in is removed, the computer
	will be deleted accordingly.

We should take into account that this schema superseeds some code
regarding deletions inside WebConsole that probably are not needed any
more, at least for the tables mentioned.
(See admin/WebConsole/gestores/relaciones/*.php in OpenGnsys repo)
2021-04-28 12:10:27 +02:00
OpenGnSys Support Team 3b1f2c293f #980 Broken TCP connection times out after 120 seconds through keepalive
Enable TCP keepalive to detect if the ogClient is gone (hard reset). If no reply
after 120 seconds, then release the connection to the client.
2021-04-22 12:24:42 +02:00
Javier Sánchez Parra 29e7641e91 #915 Add /room/add POST method
Adds POST method to add rooms (labs), required payload parameters are
name, netmask and center; any additional attributes are optional.

Required JSON:
        { "center": 0,
          "name": "classroom10",
          "netmask": "255.255.255.0" }

Full JSON:
        { "center": 0,
          "name": "classroom11",
          "netmask": "255.255.255.0",
          "group": 0,
          "location": "First floor",
          "gateway": "192.168.56.1",
          "ntp": "hora.cica.es",
          "dns": "1.1.1.1",
          "remote": True }

This commit also adds unit tests for /room/add POST method.
2021-04-20 12:05:42 +02:00
Jose M. Guisado 7d74d42c79 #1042 Update database schema automatically
This patch adds database schema management capabilities to ogServer:

- ogServer now tracks the version of its database schema, if no version
is detected, creates a 'version' table with a single row starting at 0.
- ogServer can upgrade its database schema to a newer version if
detected. (ogServer ships required SQL commands to do so)

If ogServer is unable to upgrade the schema at startup (if needed be) it
*will not* start.

Defines schema update v1 which upgrades database engine tables of
ogServer database (usually named 'ogAdmBD') from myISAM to innoDB.
2021-04-20 11:27:21 +02:00
Javier Sánchez Parra 49fc6c5c5c #915 increase maximum API REST response size
GET /scope could generate a response larger than 64 Kbytes.
Rise the maximum API REST response size to 256 Kbytes.
2021-04-19 12:01:39 +02:00
Javier Sánchez Parra 90eab86796 #915 fix "response too large" error path
Otherwise, ogServer sends "200 OK" after a "500 Internal Server Error
error" response.
2021-04-19 12:01:16 +02:00
Javier Sánchez Parra 2c6cef71d8 #915 validate response json size
Otherwise, copying response json to response buffer could lead to stack
smashing is the json response is too large.

stdout example:
*** stack smashing detected ***: <unknown> terminated
2021-04-19 12:00:27 +02:00
Jose M. Guisado 746166e4c2 #971 Remove sql bottleneck when removing software profiles
Several universities have reported that creating a software profile
hangs the machine running the ogServer for a while, sometimes up to
minutes.

Legacy SQL code is producing said bottleneck, responsible for pruning a
intermediate table between "perfilessoft" and "softwares". There is
redundant code, "perfilssoft" should be pruned first, speeding up the
later task of pruning the intermediate table "perfilessoft_softwares"

There is no need to execute:

DELETE FROM perfilessoft_softwares
WHERE idperfilsoft IN (
	SELECT idperfilsoft
	FROM perfilessoft
	WHERE idperfilsoft NOT IN (
		SELECT DISTINCT idperfilsoft
		from ordenadores_particiones)
		AND idperfilsoft NOT IN (
			SELECT DISTINCT idperfilsoft from imagenes))

When afterwards "perfilessoft" is going to be pruned and
"perfilessoft_softwares" pruned again:

DELETE FROM perfilessoft WHERE idperfilsoft NOT IN
                (SELECT DISTINCT idperfilsoft from ordenadores_particiones)
                AND  idperfilsoft NOT IN
                (SELECT DISTINCT idperfilsoft from imagenes)

DELETE FROM perfilessoft_softwares WHERE idperfilsoft NOT IN
                        (SELECT idperfilsoft from perfilessoft)

The two latter commands suffice.

This should not happen when using a relational database supporting
foreign keys and ON DELETE CASCADE, like innoDB, which will be adopted
soon.
2021-04-16 13:31:45 +02:00
Jose M. Guisado 42c22539a3 schedule: fix daylight saving problem with mktime()
mktime modifies the struct tm it receives and takes into account whether DST is
active or not (tm_isdst). tm_isdst == 0 adjusts the time, which causes the time
mismatch error.

All fields are being initialized to 0 and therefore it is assumed that the time
that has been passed is not in daylight saving time.

When the value is negative in tm.tm_isdst it delegates to mktime to guess if it
is in daylight saving time or not, this works 99% of the time.

Best way would be that ogserver knows what is its timezone and when daylight
saving applies, so tm_isdst is set to 0 or 1 accordingly.

Meanwhile, "tm_isdst = -1" provides the hotfix.
2021-04-12 17:08:00 +02:00
Jose M. Guisado 0212091e7f #915 Add /center/add POST method
Adds POST method to add centers (organizational unit), required payload
parameter is the name, and an additional comment is optional.

	{"name": "ACME"}

	{"name": "ACME", "comment": "Some comment"}
2021-04-08 11:12:23 +02:00
Jose M. Guisado 11d6e84b8e #915 Avoid duplicate db entries in /create/image
/create/image adds an entry to the database for the given partition
image created when payload contains a "description" attribute. This
insertion into the database is lacking a check for duplicates, which are
not supported for the images table.

Add a prior duplicate check before inserting. Exit with -1 code if an
image with the same name is found.
2021-04-06 13:11:50 +02:00
Javier Sánchez Parra 8015f85b04 #915 Add GET /oglive/test REST API function
This function returns the installed and available ogLiveS in the server
to be booted from.

Request:
GET /oglive/list
NO BODY

Response
200 OK
{
  "oglive": [
    {
      "distribution": "bionic",
      "kernel": "5.4.0-40-generic",
      "architecture": "amd64",
      "revision": "r20200629",
      "directory": "ogLive-5.4.0-r20200629",
      "iso": "ogLive-bionic-5.4.0-40-generic-amd64-r20200629.85eceaf.iso"
    },
    {
      "distribution": "bionic",
      "kernel": "5.0.0-27-generic",
      "architecture": "amd64",
      "revision": "r20190830",
      "directory": "ogLive-5.0.0-r20190830",
      "iso": "ogLive-bionic-5.0.0-27-generic-amd64-r20190830.7208cc9.iso"
    }
  ],
  "default": 0
}

This commit also adds tests for GET /oglive/test.
2021-04-05 18:00:56 +02:00
Diego Crespo Quinta d9e1521a16 #1004 Add GET /images test
Fix incorrect error if json is missing.
2021-03-30 16:11:45 +02:00
OpenGnSys Support Team a71cba4df1 #990 fix crash in wol with malformed IP address
==28831== 1 errors in context 1 of 2:
==28831== Invalid read of size 1
==28831==    at 0x55AC6FD: inet_aton (inet_addr.c:127)
==28831==    by 0x10ECCA: WakeUp (ogAdmServer.c:337)
==28831==    by 0x10EED6: Levanta (ogAdmServer.c:292)
==28831==    by 0x11651E: og_cmd_wol (rest.c:498)
==28831==    by 0x11651E: og_client_state_process_payload_rest (rest.c:3970)
==28831==    by 0x110CF3: og_client_read_cb (core.c:143)
==28831==    by 0x4E41D72: ev_invoke_pending (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==28831==    by 0x4E453DD: ev_run (in /usr/lib/x86_64-linux-gnu/libev.so.4.0.0)
==28831==    by 0x10E3E5: ev_loop (ev.h:835)
==28831==    by 0x10E3E5: main (main.c:100)
==28831==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

Use number of matching ip addresses in the database, skip if zero.
2021-03-30 13:58:31 +02:00
OpenGnSys Support Team ab32ed87c4 #1004 update size to 64-bits
Otherwise dbi_result_get_uint returns 0.
2021-03-19 16:58:50 +01:00
OpenGnSys Support Team f844a1b6bc #971 check for NULL serial number
ogclient might return an empty serial number.
2021-03-19 14:48:34 +01:00
Javier Sánchez Parra e6c2c26f09 #990 Use lab netmask to calculate broadcast address
ogServer gets netmask address from computer (ordenadores) table, see
commit a35b7c4. Netmask field is empty in most cases, is only filled
when the user adds computers with dhcpd.conf syntax and cannot be edited
in computer properties view.

Labs/rooms (aulas) table also have netmask field, WebConsole backend
ensures it is not empty and can be edited in lab properties view.

Get netmask from labs table to ensure it is not empty.
2021-03-17 19:50:40 +01:00
OpenGnSys Support Team 4bd409774c #990 incorrect inet_aton() error check
inet_aton() reports 0 on failure
2021-03-17 12:12:14 +01:00
Jose M. Guisado 41bc66d0e7 #997 Fix og_tm_hours_mask
Tests for e68fefe were made after 00pm (12:00) so we did not cover <12:00 cases
for immediate commands that are logged (scheduled for the exact moment
they are processed and ignored the fact they are stale so they are executed
right away)

In addition, libdbi was complaining about the data type used to
represent the hours, they were not being inserted properly. From syslog:

	failed to query database (og_dbi_schedule_create:3288) 1264: Out of
	range value for column 'horas' at row 1

Fix og_tm_hours_mask so <12:00 immediate schedule is handled correctly.
Change return type to uint16_t, as the 'hours' column type is smallint(4)

Fixes e68fefe ("#997 Set stale check flag when processing schedule/create")
2021-03-15 12:17:56 +01:00
Jose M. Guisado 8b7b5f33a1 #997 Use stale check flag in schedule/update
Commit e68fefe introduced 'check_stale' flag to better distinguish
real scheduled actions that do not execute if they are stale from
immediate actions that we want them to be logged in the action queue
(by creating a decoy schedule for the exact moment they are processed,
meaning that we ignore if the are stale).

Add this feature into schedule update too, in order to avoid executing
stale commands that were not meant to, ie. real scheduled commands.

Follows e68fefe ("Set stale check flag when processing schedule/create")
2021-03-15 12:17:56 +01:00
OpenGnSys Support Team e7e80cdde6 #942 return error if API REST parser fails
Return error if json parser fails, ignore unknown json attributes.
Missing uninitialized error value.
2021-03-15 12:17:56 +01:00
Jose M. Guisado 829f8d8ac9 #997 Remove unnecessary strdup in og_dbi_queue_*
After executing an scheduled command/proc/task valgrind reported
leaks inside og_dbi_queue_{command,procedure,task}. String
duplication is not being freed after using them.

==21281== 36 bytes in 1 blocks are definitely lost in loss record 470 of
592
...
==21281==    by 0x113DCB: og_dbi_queue_procedure (rest.c:2748)
==21281==    by 0x113F91: og_dbi_queue_task (rest.c:2804)
==21281==    by 0x114392: og_schedule_run (rest.c:2916)
==21281==    by 0x112059: og_agent_timer_cb (schedule.c:441)
...
==21281==    by 0x10E2A5: main (main.c:100)

These strdup are not necessary because the dbi result is not freed
before using them, it's safe to use the dbi result's reference to
this string.

Fix previous memleaks when executing scheduled commands, procedures
and tasks.
2021-03-11 14:39:07 +01:00
Jose M. Guisado e68fefeac7 #997 Set stale check flag when processing schedule/create
If you schedule a command in the past, the scheduler executes such
command immediately.

When expanding a schedule that result in commands that run weekly,
commands in the past are also executed, which is not expected.

Fix this by using the check_stale flag (formerly on_start) so
commands in the past that result from expansions are skipped.
2021-03-11 12:22:36 +01:00
Jose M. Guisado 76e6375720 #1004 Fix memleak in og_cmd_images
image_json object is created to store the json representation of
an image returned by the database. This object is going to be appended
to a json list that will compose the overall root json object.

Use json_array_append_new to let "images" steal the reference of
image_json so when further decref(root) there is no json reference
hanging around.
2021-02-24 14:33:22 +01:00
OpenGnSys Support Team 1c52b78e72 #942 memleak in og_send_request() 2021-02-23 12:35:53 +01:00