1 /*
2 * msg.c
3 *
4 * Copyright (c) 1996-1999 Whistle Communications, Inc.
5 * All rights reserved.
6 *
7 * Subject to the following obligations and disclaimer of warranty, use and
8 * redistribution of this software, in source or object code forms, with or
9 * without modifications are expressly permitted by Whistle Communications;
10 * provided, however, that:
11 * 1. Any and all reproductions of the source or object code must include the
12 * copyright notice above and the following disclaimer of warranties; and
13 * 2. No rights are granted, in any manner or form, to use Whistle
14 * Communications, Inc. trademarks, including the mark "WHISTLE
15 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
16 * such appears in the above copyright notice or in the software.
17 *
18 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
19 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
20 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
21 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
23 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
24 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
25 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
26 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
27 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
28 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
29 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
34 * OF SUCH DAMAGE.
35 *
36 * Author: Archie Cobbs <[email protected]>
37 *
38 * $Whistle: msg.c,v 1.9 1999/01/20 00:57:23 archie Exp $
39 */
40
41 #ifdef FSTACK
42 #define _GNU_SOURCE
43 #include <stdio.h>
44 #endif
45
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48
49 #include <sys/types.h>
50 #include <sys/socket.h>
51 #include <stdarg.h>
52 #ifndef FSTACK
53 #include <stdatomic.h>
54 #endif
55 #include <netgraph/ng_message.h>
56 #include <netgraph/ng_socket.h>
57
58 #include "netgraph.h"
59 #include "internal.h"
60
61 #ifdef FSTACK
62 #define _Atomic(T) T volatile
63
64 #ifndef __ATOMIC_SEQ_CST
65 #define __ATOMIC_SEQ_CST 5
66 #endif
67
68 typedef enum {
69 memory_order_seq_cst = __ATOMIC_SEQ_CST
70 } memory_order;
71
72 #define atomic_fetch_add(object, operand) \
73 atomic_fetch_add_explicit(object, operand, memory_order_seq_cst)
74 #define atomic_fetch_add_explicit(object, operand, order) \
75 __atomic_fetch_add(object, operand, order)
76 #endif
77
78 /* Next message token value */
79 static _Atomic(unsigned int) gMsgId;
80
81 /* For delivering both messages and replies */
82 static int NgDeliverMsg(int cs, const char *path,
83 const struct ng_mesg *hdr, const void *args, size_t arglen);
84
85 /*
86 * Send a message to a node using control socket node "cs".
87 * Returns -1 if error and sets errno appropriately.
88 * If successful, returns the message ID (token) used.
89 */
90 int
NgSendMsg(int cs,const char * path,int cookie,int cmd,const void * args,size_t arglen)91 NgSendMsg(int cs, const char *path,
92 int cookie, int cmd, const void *args, size_t arglen)
93 {
94 struct ng_mesg msg;
95
96 /* Prepare message header */
97 memset(&msg, 0, sizeof(msg));
98 msg.header.version = NG_VERSION;
99 msg.header.typecookie = cookie;
100 msg.header.token = atomic_fetch_add(&gMsgId, 1) & INT_MAX;
101 msg.header.flags = NGF_ORIG;
102 msg.header.cmd = cmd;
103 snprintf((char *)msg.header.cmdstr, NG_CMDSTRSIZ, "cmd%d", cmd);
104
105 /* Deliver message */
106 if (NgDeliverMsg(cs, path, &msg, args, arglen) < 0)
107 return (-1);
108 return (msg.header.token);
109 }
110
111 /*
112 * Send a message given in ASCII format. We first ask the node to translate
113 * the command into binary, and then we send the binary.
114 */
115 int
NgSendAsciiMsg(int cs,const char * path,const char * fmt,...)116 NgSendAsciiMsg(int cs, const char *path, const char *fmt, ...)
117 {
118 struct ng_mesg *reply, *binary, *ascii;
119 char *buf, *cmd, *args;
120 va_list fmtargs;
121 int token;
122
123 /* Parse out command and arguments */
124 va_start(fmtargs, fmt);
125 vasprintf(&buf, fmt, fmtargs);
126 va_end(fmtargs);
127 if (buf == NULL)
128 return (-1);
129
130 /* Parse out command, arguments */
131 for (cmd = buf; isspace(*cmd); cmd++)
132 ;
133 for (args = cmd; *args != '\0' && !isspace(*args); args++)
134 ;
135 if (*args != '\0') {
136 while (isspace(*args))
137 *args++ = '\0';
138 }
139
140 /* Get a bigger buffer to hold inner message header plus arg string */
141 if ((ascii = malloc(sizeof(struct ng_mesg)
142 + strlen(args) + 1)) == NULL) {
143 free(buf);
144 return (-1);
145 }
146 memset(ascii, 0, sizeof(*ascii));
147
148 /* Build inner header (only need cmdstr, arglen, and data fields) */
149 strncpy((char *)ascii->header.cmdstr, cmd,
150 sizeof(ascii->header.cmdstr) - 1);
151 strcpy(ascii->data, args);
152 ascii->header.arglen = strlen(ascii->data) + 1;
153 free(buf);
154
155 /* Send node a request to convert ASCII to binary */
156 if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE, NGM_ASCII2BINARY,
157 (u_char *)ascii, sizeof(*ascii) + ascii->header.arglen) < 0) {
158 free(ascii);
159 return (-1);
160 }
161 free(ascii);
162
163 /* Get reply */
164 if (NgAllocRecvMsg(cs, &reply, NULL) < 0)
165 return (-1);
166
167 /* Now send binary version */
168 binary = (struct ng_mesg *)reply->data;
169 binary->header.token = atomic_fetch_add(&gMsgId, 1) & INT_MAX;
170 binary->header.version = NG_VERSION;
171 if (NgDeliverMsg(cs,
172 path, binary, binary->data, binary->header.arglen) < 0) {
173 free(reply);
174 return (-1);
175 }
176 token = binary->header.token;
177 free(reply);
178 return (token);
179 }
180
181 /*
182 * Send a message that is a reply to a previously received message.
183 * Returns -1 and sets errno on error, otherwise returns zero.
184 */
185 int
NgSendReplyMsg(int cs,const char * path,const struct ng_mesg * msg,const void * args,size_t arglen)186 NgSendReplyMsg(int cs, const char *path,
187 const struct ng_mesg *msg, const void *args, size_t arglen)
188 {
189 struct ng_mesg rep;
190
191 /* Prepare message header */
192 rep = *msg;
193 rep.header.flags = NGF_RESP;
194
195 /* Deliver message */
196 return (NgDeliverMsg(cs, path, &rep, args, arglen));
197 }
198
199 /*
200 * Send a message to a node using control socket node "cs".
201 * Returns -1 if error and sets errno appropriately, otherwise zero.
202 */
203 static int
NgDeliverMsg(int cs,const char * path,const struct ng_mesg * hdr,const void * args,size_t arglen)204 NgDeliverMsg(int cs, const char *path,
205 const struct ng_mesg *hdr, const void *args, size_t arglen)
206 {
207 u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
208 struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
209 u_char *buf = NULL;
210 struct ng_mesg *msg;
211 int errnosv = 0;
212 int rtn = 0;
213
214 /* Sanity check */
215 if (args == NULL)
216 arglen = 0;
217
218 /* Get buffer */
219 if ((buf = malloc(sizeof(*msg) + arglen)) == NULL) {
220 errnosv = errno;
221 if (_gNgDebugLevel >= 1)
222 NGLOG("malloc");
223 rtn = -1;
224 goto done;
225 }
226 msg = (struct ng_mesg *) buf;
227
228 /* Finalize message */
229 *msg = *hdr;
230 msg->header.arglen = arglen;
231 memcpy(msg->data, args, arglen);
232
233 /* Prepare socket address */
234 sg->sg_family = AF_NETGRAPH;
235 /* XXX handle overflow */
236 strlcpy(sg->sg_data, path, NG_PATHSIZ);
237 sg->sg_len = strlen(sg->sg_data) + 1 + NGSA_OVERHEAD;
238
239 /* Debugging */
240 if (_gNgDebugLevel >= 2) {
241 NGLOGX("SENDING %s:",
242 (msg->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
243 _NgDebugSockaddr(sg);
244 _NgDebugMsg(msg, sg->sg_data);
245 }
246
247 /* Send it */
248 if (sendto(cs, msg, sizeof(*msg) + arglen,
249 0, (struct sockaddr *) sg, sg->sg_len) < 0) {
250 errnosv = errno;
251 if (_gNgDebugLevel >= 1)
252 NGLOG("sendto(%s)", sg->sg_data);
253 rtn = -1;
254 goto done;
255 }
256
257 #ifndef FSTACK
258 /* Wait for reply if there should be one. */
259 if (msg->header.cmd & NGM_HASREPLY && !(msg->header.flags & NGF_RESP)) {
260 struct pollfd rfds;
261 int n;
262
263 rfds.fd = cs;
264 rfds.events = POLLIN;
265 rfds.revents = 0;
266 n = poll(&rfds, 1, INFTIM);
267 if (n == -1) {
268 errnosv = errno;
269 if (_gNgDebugLevel >= 1)
270 NGLOG("poll");
271 rtn = -1;
272 }
273 }
274 #endif
275
276 done:
277 /* Done */
278 free(buf); /* OK if buf is NULL */
279 errno = errnosv;
280 return (rtn);
281 }
282
283 /*
284 * Receive a control message.
285 *
286 * On error, this returns -1 and sets errno.
287 * Otherwise, it returns the length of the received reply.
288 */
289 int
NgRecvMsg(int cs,struct ng_mesg * rep,size_t replen,char * path)290 NgRecvMsg(int cs, struct ng_mesg *rep, size_t replen, char *path)
291 {
292 u_char sgbuf[NG_PATHSIZ + NGSA_OVERHEAD];
293 struct sockaddr_ng *const sg = (struct sockaddr_ng *) sgbuf;
294 socklen_t sglen = sizeof(sgbuf);
295 int len, errnosv;
296
297 /* Read reply */
298 len = recvfrom(cs, rep, replen, 0, (struct sockaddr *) sg, &sglen);
299 if (len < 0) {
300 errnosv = errno;
301 if (_gNgDebugLevel >= 1)
302 NGLOG("recvfrom");
303 goto errout;
304 }
305 if (path != NULL)
306 strlcpy(path, sg->sg_data, NG_PATHSIZ);
307
308 /* Debugging */
309 if (_gNgDebugLevel >= 2) {
310 NGLOGX("RECEIVED %s:",
311 (rep->header.flags & NGF_RESP) ? "RESPONSE" : "MESSAGE");
312 _NgDebugSockaddr(sg);
313 _NgDebugMsg(rep, sg->sg_data);
314 }
315
316 /* Done */
317 return (len);
318
319 errout:
320 errno = errnosv;
321 return (-1);
322 }
323
324 /*
325 * Identical to NgRecvMsg() except buffer is dynamically allocated.
326 */
327 int
NgAllocRecvMsg(int cs,struct ng_mesg ** rep,char * path)328 NgAllocRecvMsg(int cs, struct ng_mesg **rep, char *path)
329 {
330 int len;
331 #ifndef FSTACK
332 socklen_t optlen;
333
334 optlen = sizeof(len);
335 if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
336 #else
337 len = NGCTL_DEFAULT_RCVBUF;
338 if (
339 #endif
340 (*rep = malloc(len)) == NULL)
341 return (-1);
342 if ((len = NgRecvMsg(cs, *rep, len, path)) < 0)
343 free(*rep);
344 return (len);
345 }
346
347 /*
348 * Receive a control message and convert the arguments to ASCII
349 */
350 int
NgRecvAsciiMsg(int cs,struct ng_mesg * reply,size_t replen,char * path)351 NgRecvAsciiMsg(int cs, struct ng_mesg *reply, size_t replen, char *path)
352 {
353 struct ng_mesg *msg, *ascii;
354 int bufSize, errnosv;
355 u_char *buf;
356
357 /* Allocate buffer */
358 bufSize = 2 * sizeof(*reply) + replen;
359 if ((buf = malloc(bufSize)) == NULL)
360 return (-1);
361 msg = (struct ng_mesg *)buf;
362 ascii = (struct ng_mesg *)msg->data;
363
364 /* Get binary message */
365 if (NgRecvMsg(cs, msg, bufSize, path) < 0)
366 goto fail;
367 memcpy(reply, msg, sizeof(*msg));
368
369 /* Ask originating node to convert the arguments to ASCII */
370 if (NgSendMsg(cs, path, NGM_GENERIC_COOKIE,
371 NGM_BINARY2ASCII, msg, sizeof(*msg) + msg->header.arglen) < 0)
372 goto fail;
373 if (NgRecvMsg(cs, msg, bufSize, NULL) < 0)
374 goto fail;
375
376 /* Copy result to client buffer */
377 if (sizeof(*ascii) + ascii->header.arglen > replen) {
378 errno = ERANGE;
379 fail:
380 errnosv = errno;
381 free(buf);
382 errno = errnosv;
383 return (-1);
384 }
385 strncpy(reply->data, ascii->data, ascii->header.arglen);
386
387 /* Done */
388 free(buf);
389 return (0);
390 }
391
392 /*
393 * Identical to NgRecvAsciiMsg() except buffer is dynamically allocated.
394 */
395 int
NgAllocRecvAsciiMsg(int cs,struct ng_mesg ** reply,char * path)396 NgAllocRecvAsciiMsg(int cs, struct ng_mesg **reply, char *path)
397 {
398 int len;
399 #ifndef FSTACK
400 socklen_t optlen;
401
402 optlen = sizeof(len);
403 if (getsockopt(cs, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1 ||
404 #else
405 len = NGCTL_DEFAULT_RCVBUF;
406 if (
407 #endif
408 (*reply = malloc(len)) == NULL)
409 return (-1);
410 if ((len = NgRecvAsciiMsg(cs, *reply, len, path)) < 0)
411 free(*reply);
412 return (len);
413 }
414