summaryrefslogtreecommitdiffstats
path: root/cmds/keystore/netkeystore.h
blob: a87a667e91236a88a7737ab5948729fe670962cc (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
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/

#ifndef __NETKEYSTORE_H__
#define __NETKEYSTORE_H__

#include <stdio.h>
#include <cutils/sockets.h>
#include <cutils/log.h>

#include "common.h"

static inline int readx(int s, void *_buf, int count)
{
    char *buf = _buf;
    int n = 0, r;
    if (count < 0) return -1;
    while (n < count) {
        r = read(s, buf + n, count - n);
        if (r < 0) {
            if (errno == EINTR) continue;
            LOGE("read error: %s\n", strerror(errno));
            return -1;
        }
        if (r == 0) {
            LOGE("eof\n");
            return -1; /* EOF */
        }
        n += r;
    }
    return 0;
}

static inline int writex(int s, const void *_buf, int count)
{
    const char *buf = _buf;
    int n = 0, r;
    if (count < 0) return -1;
    while (n < count) {
        r = write(s, buf + n, count - n);
        if (r < 0) {
            if (errno == EINTR) continue;
            LOGE("write error: %s\n", strerror(errno));
            return -1;
        }
        n += r;
    }
    return 0;
}

static inline int read_marshal(int s, LPC_MARSHAL *cmd)
{
    if (readx(s, cmd, 2 * sizeof(uint32_t))) {
        LOGE("failed to read header\n");
        return -1;
    }
    if (cmd->len > BUFFER_MAX) {
        LOGE("invalid size %d\n", cmd->len);
        return -1;
    }
    if (readx(s, cmd->data, cmd->len)) {
        LOGE("failed to read data\n");
        return -1;
    }
    cmd->data[cmd->len] = 0;
    return 0;
}

static inline int write_marshal(int s, LPC_MARSHAL *cmd)
{
    if (writex(s, cmd, 2 * sizeof(uint32_t))) {
        LOGE("failed to write marshal header\n");
        return -1;
    }
    if (writex(s, cmd->data, cmd->len)) {
        LOGE("failed to write marshal data\n");
        return -1;
    }
    return 0;
}

#endif