1 /* This is a simple TCP server that listens on port 1234 and provides lists
2 * of files to clients, using a protocol defined in file_server.proto.
4 * It directly deserializes and serializes messages from network, minimizing
7 * For flexibility, this example is implemented using posix api.
8 * In a real embedded system you would typically use some other kind of
9 * a communication and filesystem layer.
12 #include <sys/socket.h>
13 #include <sys/types.h>
14 #include <netinet/in.h>
20 #include <pb_encode.h>
21 #include <pb_decode.h>
23 #include "fileproto.h"
25 bool write_callback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
27 int fd = *(int*)stream->state;
28 return send(fd, buf, count, 0) == count;
31 bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count)
33 int fd = *(int*)stream->state;
37 /* Well, this is a really inefficient way to skip input. */
38 /* It is only used when there are unknown fields. */
40 while (count-- && recv(fd, &dummy, 1, 0) == 1);
44 return recv(fd, buf, count, MSG_WAITALL) == count;
47 bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, const void *arg)
49 DIR *dir = (DIR*) arg;
53 while ((file = readdir(dir)) != NULL)
55 fileinfo.inode = file->d_ino;
56 strncpy(fileinfo.name, file->d_name, sizeof(fileinfo.name));
57 fileinfo.name[sizeof(fileinfo.name) - 1] = '\0';
59 if (!pb_encode_tag_for_field(stream, field))
62 if (!pb_enc_submessage(stream, field, &fileinfo))
69 void handle_connection(int connfd)
71 ListFilesRequest request;
72 ListFilesResponse response;
73 pb_istream_t input = {&read_callback, &connfd, SIZE_MAX};
74 pb_ostream_t output = {&write_callback, &connfd, SIZE_MAX, 0};
77 if (!pb_decode(&input, ListFilesRequest_fields, &request))
79 printf("Decoding failed.\n");
83 directory = opendir(request.path);
85 printf("Listing directory: %s\n", request.path);
87 if (directory == NULL)
91 response.has_path_error = true;
92 response.path_error = true;
93 response.file.funcs.encode = NULL;
97 response.has_path_error = false;
98 response.file.funcs.encode = &listdir_callback;
99 response.file.arg = directory;
102 if (!pb_encode(&output, ListFilesResponse_fields, &response))
104 printf("Encoding failed.\n");
108 int main(int argc, char **argv)
110 int listenfd, connfd;
111 struct sockaddr_in servaddr;
113 listenfd = socket(AF_INET, SOCK_STREAM, 0);
115 memset(&servaddr, 0, sizeof(servaddr));
116 servaddr.sin_family = AF_INET;
117 servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
118 servaddr.sin_port = htons(1234);
119 if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0)
125 if (listen(listenfd, 5) != 0)
133 connfd = accept(listenfd, NULL, NULL);
141 printf("Got connection.\n");
143 handle_connection(connfd);
145 printf("Closing connection.\n");