summaryrefslogtreecommitdiff
path: root/c_src/erlport.c
blob: 372f98deb290a7db6424626293d0e531a6af2ef7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
 * Copyright (c) 2014-2015, NORDUnet A/S.
 * See LICENSE for licensing information.
 */

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "net_read_write.h"
#include "erlport.h"

static ssize_t
read_length(size_t length_size)
{
    unsigned char buf[4];

    if (length_size != 2 && length_size != 4) {
        return -1;
    }

    if (length_size > sizeof(buf)) {
        return -1;
    }

    ssize_t ret;

    ret = net_read(0, (char *)buf, length_size);

    if (ret != (ssize_t) length_size) {
        return -1;
    }

    if (length_size == 2) {
      return (ssize_t)(((unsigned long)buf[0] << 8) | (unsigned long)buf[1]);
    } else {
      return (ssize_t)(((unsigned long)buf[0] << 24) |
                       ((unsigned long)buf[1] << 16) |
                       ((unsigned long)buf[2] << 8) |
                       (unsigned long)buf[3]);
    }
}

ssize_t
read_command(unsigned char *buf, size_t maxlen, size_t length_size)
{
    ssize_t len;

    len = read_length(length_size);

    if (len < 0) {
        return -1;
    }

    if (len > (ssize_t) maxlen) {
        return -1;
    }
    return net_read(0, (char *)buf, (size_t)len);
}

static int
write_length(size_t len, size_t length_size)
{
    unsigned char buf[4];

    if (length_size != 2 && length_size != 4) {
        return -1;
    }

    if (length_size == 2) {
        buf[0] = (len >> 8) & 0xff;
        buf[1] = len & 0xff;
    } else {
        buf[0] = (len >> 24) & 0xff;
        buf[1] = (len >> 16) & 0xff;
        buf[2] = (len >> 8) & 0xff;
        buf[3] = len & 0xff;
    }

    ssize_t ret;

    ret = net_write(1, (char *)buf, length_size);

    if (ret < 0) {
        return -1;
    }

    if (ret != (ssize_t) length_size) {
        return -1;
    }

    return 0;
}

int
write_reply(unsigned char *msg, size_t len, size_t length_size)
{
    ssize_t ret;

    ret = write_length(len, length_size);
    if (ret < 0) {
        return -1;
    }
    ret = net_write(1, (char *)msg, len);
    if (ret < 0) {
        return -1;
    }

    return 0;
}

int
write_status(char *msg)
{
    return write_reply((unsigned char *)msg, strlen(msg), 2);
}