summaryrefslogtreecommitdiffstats
path: root/yamn_encoder.php
blob: 3503b5418969c9788efaae387018d70176ce01a2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
declare(strict_types=1);

require_once __DIR__ . '/yamn_config.php';

/** Encode a plaintext message with the local YAMN encoder binary. */
function encodeYamnMessage(array $request): array
{
    $encoder = yamnConfig('YAMN_ENCODER', '/usr/local/bin/yamn-encode');
    $keyring = yamnConfig('YAMN_PUBRING', '/opt/yamn-master/pubring.mix');
    if (!is_executable($encoder)) {
        return ['success' => false, 'error' => 'YAMN encoder is not available'];
    }
    $request['public_keyring'] = $keyring;
    try {
        $input = json_encode($request, JSON_THROW_ON_ERROR);
    } catch (JsonException $exception) {
        return ['success' => false, 'error' => 'Unable to encode YAMN request'];
    }

    $descriptors = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
    $process = proc_open([$encoder], $descriptors, $pipes);
    if (!is_resource($process)) {
        return ['success' => false, 'error' => 'Unable to start YAMN encoder'];
    }
    fwrite($pipes[0], $input);
    fclose($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[2]);
    $status = proc_close($process);

    $response = json_decode($stdout, true);
    if ($status !== 0 || !is_array($response) || ($response['success'] ?? false) !== true) {
        return ['success' => false, 'error' => 'YAMN encoding failed'];
    }
    if (!isset($response['entry_address'], $response['envelope']) || !is_string($response['envelope'])) {
        return ['success' => false, 'error' => 'Invalid response from YAMN encoder'];
    }
    return ['success' => true, 'entry_address' => $response['entry_address'], 'envelope' => $response['envelope']];
}