Commit Graph

188 Commits (cd9650108af1eb882ca11858249dc428087667ff)

Author SHA1 Message Date
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 721ab28fdf rest: expose description in GET /images
add .description field to json.
2023-12-12 10:23:46 +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 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
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 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 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 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
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 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 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 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 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 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 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
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
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 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
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
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
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
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
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
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
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
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 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
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
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
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
OpenGnSys Support Team 9b708e0a7b #942 memleak in error path
Fix memleaks in error path.

json_decref() checks for null objects.
2021-02-23 12:32:57 +01:00
Jose M. Guisado a46b69b590 #990 Fix og_cmd_wol memory leak
Allocated strings using dbi_result_get_string_copy are not being freed
after using them. This patch fix this memory leak.

Fixes: e4cb91b ("#990 wol: migrate mac and netmask query to ogServer")
2021-02-23 10:49:12 +01:00
OpenGnSys Support Team 3b3405bc2f #1019 UAF in schedule run
Otherwise accessing IP address results in use-after-free.
2021-02-23 10:48:13 +01:00
Javier Sánchez Parra ed0d86b010 #1019 Fix queued Wake on LAN
UMA and UPV report that Wake on LAN command (in queue mode) does not
work.

We improved WoL command, now ogServer calculates the broadcast address
of the network to which the client belongs. To calculate this address
ogServer needs the IP and the netmask of the client. We updated ogServer
to retrieve the netmask from the database in non-queue mode, but we forgot
to add this in queue mode.

This patch adds netmask retrieving to queued WoL.
2021-02-22 11:05:34 +01:00
Jose M. Guisado e4cb91b5f6 #990 wol: migrate mac and netmask query to ogServer
ogServer WoL rest function is expecting ip, mac and netmask from the
request's payload. This makes the client responsible for providing such
data.

ogServer should be the owner of the database, this patch adjusts the
parameter expected in a request payload for /wol action so clients only
need to provide the ips and wol type (broadcast, unicast).

Database is expected to contain valid data for the netmask and mac of
target computers.
2021-02-15 16:26:21 +01:00
Jose M. Guisado 4d2e1dd31c #1004 Fix client setup disk size showing as 0
og_cmd_get_client_setup is querying the database for computers disk
setup information. This includes the size of a disk or a partition,
which are stored as BIGINT in the database.

Using dbi_result_get_int will result in an error as libdbi expects to
store this kind of data type in a long long instead of an int.

Fix disk size variable declaration and use the correct dbi_result_get
function for this particular data column.
2021-02-09 13:13:53 +01:00