d049144ca2716c7a493cab1be92f9fb698bde274
1 /*
2 * SysDB - src/utils/proto.c
3 * Copyright (C) 2013 Sebastian 'tokkee' Harl <sh@tokkee.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
28 #include "utils/proto.h"
29 #include "core/error.h"
31 #include <arpa/inet.h>
32 #include <errno.h>
34 #include <string.h>
35 #include <unistd.h>
37 /*
38 * public API
39 */
41 ssize_t
42 sdb_proto_send(int fd, size_t msg_len, const char *msg)
43 {
44 const char *buf;
45 size_t len;
47 if ((fd < 0) || (msg_len && (! msg)))
48 return -1;
49 if (! msg_len)
50 return 0;
52 buf = msg;
53 len = msg_len;
54 while (len > 0) {
55 ssize_t status;
57 /* XXX: use select() */
59 errno = 0;
60 status = write(fd, buf, len);
61 if (status < 0) {
62 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
63 continue;
64 if (errno == EINTR)
65 continue;
67 return status;
68 }
70 len -= (size_t)status;
71 buf += status;
72 }
74 return (ssize_t)msg_len;
75 } /* sdb_proto_send */
77 ssize_t
78 sdb_proto_send_msg(int fd, uint32_t code,
79 uint32_t msg_len, const char *msg)
80 {
81 size_t len = 2 * sizeof(uint32_t) + msg_len;
82 char buffer[len];
84 uint32_t tmp;
86 tmp = htonl(code);
87 memcpy(buffer, &tmp, sizeof(tmp));
88 tmp = htonl(msg_len);
89 memcpy(buffer + sizeof(tmp), &tmp, sizeof(tmp));
91 if (msg_len)
92 memcpy(buffer + 2 * sizeof(tmp), msg, msg_len);
94 return sdb_proto_send(fd, len, buffer);
95 } /* sdb_proto_send_msg */
97 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */