-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmessage.c
138 lines (113 loc) · 2.1 KB
/
message.c
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/* Copyright (c) 2019 by Erik Larsson
SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <endian.h>
#include <string.h>
#include <errno.h>
#include "agent.h"
#define MAX_DATA_LEN 1048576
int read_message(int fd, buffer_t *msg) {
int r;
ssize_t n, d = 0;
uint32_t msgbuf = 0, msglen = 0;
uint8_t rbuf[1024];
n = read(fd, &msgbuf, 4);
if (n == -1) {
return -1;
}
if (n < 4) {
return -1;
}
msglen = be32toh(msgbuf);
if (!msglen) {
return -1;
}
if (msglen > MAX_DATA_LEN) {
return -1;
}
do {
memset(rbuf, 0, 1024);
n = read(fd, rbuf, 1024);
if (n == -1) {
r = n;
goto err_free;
}
r = append_buffer(msg, rbuf, n);
if (r) {
goto err_free;
}
d = d + n;
} while (n && d < msglen);
if (d < msglen) {
goto err_free;
}
return 0;
err_free:
free_buffer(msg);
return r;
}
int write_message(int fd, buffer_t *msg) {
ssize_t n, d = 0;
uint32_t len;
len = htobe32(msg->len);
n = write(fd, &len, 4);
if (n == -1) {
return -1;
}
if (n != 4) {
return -1;
}
while (n && d < msg->len) {
n = write(fd, msg->data + d, msg->len - d);
if (n == -1) {
return -1;
}
d = d + n;
}
if (d < msg->len) {
return -1;
}
return 0;
}
int handle_message(int fd, context_t *ctx, buffer_t *msg, buffer_t *rmsg) {
int r;
uint8_t type;
r = read_message(fd, msg);
if (r) {
return r;
}
r = buf_get_byte(msg, &type);
if (r) {
return r;
}
switch (type) {
case SSH_AGENTC_REQUEST_IDENTITIES:
r = buf_add_byte(rmsg, SSH_AGENT_IDENTITIES_ANSWER);
if (r) {
return r;
}
r = handle_listreq(ctx, rmsg);
if (r) {
return r;
}
break;
case SSH_AGENTC_SIGN_REQUEST:
r = buf_add_byte(rmsg, SSH_AGENT_SIGN_RESPONSE);
if (r) {
return r;
}
r = handle_signreq(ctx, msg, rmsg);
if (r) {
return r;
}
break;
case SSH_AGENTC_EXTENSION:
return buf_add_byte(rmsg, SSH_AGENT_FAILURE);
default:
return -1;
}
return 0;
}