Jean-Baptiste Queru | 4d3b5c1 | 2009-07-21 11:16:54 -0700 | [diff] [blame] | 1 | /* |
| 2 | ** |
| 3 | ** Copyright 2009, The Android Open Source Project |
| 4 | ** |
| 5 | ** Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | ** you may not use this file except in compliance with the License. |
| 7 | ** You may obtain a copy of the License at |
| 8 | ** |
| 9 | ** http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | ** |
| 11 | ** Unless required by applicable law or agreed to in writing, software |
| 12 | ** distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | ** See the License for the specific language governing permissions and |
| 15 | ** limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | #ifndef __NETKEYSTORE_H__ |
| 19 | #define __NETKEYSTORE_H__ |
| 20 | |
| 21 | #include <stdio.h> |
| 22 | #include <cutils/sockets.h> |
| 23 | #include <cutils/log.h> |
| 24 | |
| 25 | #include "common.h" |
| 26 | |
| 27 | static inline int readx(int s, void *_buf, int count) |
| 28 | { |
| 29 | char *buf = _buf; |
| 30 | int n = 0, r; |
| 31 | if (count < 0) return -1; |
| 32 | while (n < count) { |
| 33 | r = read(s, buf + n, count - n); |
| 34 | if (r < 0) { |
| 35 | if (errno == EINTR) continue; |
| 36 | LOGE("read error: %s\n", strerror(errno)); |
| 37 | return -1; |
| 38 | } |
| 39 | if (r == 0) { |
| 40 | LOGE("eof\n"); |
| 41 | return -1; /* EOF */ |
| 42 | } |
| 43 | n += r; |
| 44 | } |
| 45 | return 0; |
| 46 | } |
| 47 | |
| 48 | static inline int writex(int s, const void *_buf, int count) |
| 49 | { |
| 50 | const char *buf = _buf; |
| 51 | int n = 0, r; |
| 52 | if (count < 0) return -1; |
| 53 | while (n < count) { |
| 54 | r = write(s, buf + n, count - n); |
| 55 | if (r < 0) { |
| 56 | if (errno == EINTR) continue; |
| 57 | LOGE("write error: %s\n", strerror(errno)); |
| 58 | return -1; |
| 59 | } |
| 60 | n += r; |
| 61 | } |
| 62 | return 0; |
| 63 | } |
| 64 | |
| 65 | static inline int read_marshal(int s, LPC_MARSHAL *cmd) |
| 66 | { |
| 67 | if (readx(s, cmd, 2 * sizeof(uint32_t))) { |
| 68 | LOGE("failed to read header\n"); |
| 69 | return -1; |
| 70 | } |
| 71 | if (cmd->len > BUFFER_MAX) { |
| 72 | LOGE("invalid size %d\n", cmd->len); |
| 73 | return -1; |
| 74 | } |
| 75 | if (readx(s, cmd->data, cmd->len)) { |
| 76 | LOGE("failed to read data\n"); |
| 77 | return -1; |
| 78 | } |
| 79 | cmd->data[cmd->len] = 0; |
| 80 | return 0; |
| 81 | } |
| 82 | |
| 83 | static inline int write_marshal(int s, LPC_MARSHAL *cmd) |
| 84 | { |
| 85 | if (writex(s, cmd, 2 * sizeof(uint32_t))) { |
| 86 | LOGE("failed to write marshal header\n"); |
| 87 | return -1; |
| 88 | } |
| 89 | if (writex(s, cmd->data, cmd->len)) { |
| 90 | LOGE("failed to write marshal data\n"); |
| 91 | return -1; |
| 92 | } |
| 93 | return 0; |
| 94 | } |
| 95 | |
| 96 | #endif |