3d38b22599ac8385ba5f0e890aa2bfa051f256ad
7 int pack_control(uint8_t *data
, int len
, uint8_t type
, int argc
, char *argv
[])
9 struct nsctl_packet pkt
;
10 struct nsctl_args arg
;
12 int sz
= (p
- (char *) &pkt
);
14 if (len
> sizeof(pkt
))
18 argc
= 0xff; // paranoia
20 pkt
.magic
= ntohs(NSCTL_MAGIC
);
29 if (s
> sizeof(arg
.value
))
30 s
= sizeof(arg
.value
); // silently truncate
36 return -1; // overflow
39 memcpy(arg
.value
, a
, arg
.len
);
47 * terminate: this is both a sanity check and additionally
48 * ensures that there's a spare byte in the packet to null
49 * terminate the last argument when unpacking (see unpack_control)
51 if (sz
+ sizeof(arg
.len
) > len
)
52 return -1; // overflow
55 memcpy(p
, &arg
.len
, sizeof(arg
.len
));
57 sz
+= sizeof(arg
.len
);
58 memcpy(data
, &pkt
, sz
);
63 int unpack_control(struct nsctl
*control
, uint8_t *data
, int len
)
65 struct nsctl_packet pkt
;
67 int sz
= (p
- (char *) &pkt
);
71 return NSCTL_ERR_SHORT
;
73 if (len
> sizeof(pkt
))
74 return NSCTL_ERR_LONG
;
76 memcpy(&pkt
, data
, len
);
77 if (ntohs(pkt
.magic
) != NSCTL_MAGIC
)
78 return NSCTL_ERR_MAGIC
;
83 case NSCTL_REQ_UNLOAD
:
85 case NSCTL_REQ_CONTROL
:
88 control
->type
= pkt
.type
;
92 return NSCTL_ERR_TYPE
;
95 control
->argc
= pkt
.argc
;
96 for (i
= 0; i
<= control
->argc
; i
++)
101 return NSCTL_ERR_SHORT
;
104 *p
++ = 0; // null terminate previous arg
107 if (i
< control
->argc
)
110 return NSCTL_ERR_SHORT
;
112 control
->argv
[i
] = p
;
118 /* check for terminator */
120 return NSCTL_ERR_SHORT
;
125 return NSCTL_ERR_LONG
; // trailing cr*p
127 return control
->type
;
130 void dump_control(struct nsctl
*control
, FILE *stream
)
132 char *type
= "*unknown*";
137 switch (control
->type
)
139 case NSCTL_REQ_LOAD
: type
= "NSCTL_REQ_LOAD"; break;
140 case NSCTL_REQ_UNLOAD
: type
= "NSCTL_REQ_UNLOAD"; break;
141 case NSCTL_REQ_HELP
: type
= "NSCTL_REQ_HELP"; break;
142 case NSCTL_REQ_CONTROL
: type
= "NSCTL_REQ_CONTROL"; break;
143 case NSCTL_RES_OK
: type
= "NSCTL_RES_OK"; break;
144 case NSCTL_RES_ERR
: type
= "NSCTL_RES_ERR"; break;
147 fprintf(stream
, "Control packet:\n");
148 fprintf(stream
, " Type: %d (%s)\n", (int) control
->type
, type
);
149 fprintf(stream
, " Args: %d", (int) control
->argc
);
153 fprintf(stream
, " (\"");
154 for (i
= 0; i
< control
->argc
; i
++)
155 fprintf(stream
, "%s%s", i
? "\", \"" : "", control
->argv
[i
]);
157 fprintf(stream
, "\")");
160 fprintf(stream
, "\n\n");