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 139 140 141 142 143 144 145
|
/*
* resmgr tester
*
*/
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/un.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/dir.h>
#include <sys/stat.h>
#include "protocol.h"
#include "resmgrd.h"
static const char * identify(int fd);
const char * find(const char *, dev_t, ino_t);
int
main(int argc, char **argv)
{
struct conn *conn;
struct pollfd p[2];
int done;
p[0].fd = 0;
fcntl(0, F_SETFL, O_NONBLOCK);
if (argc > 2) {
printf("Usage: tester [socketpath]\n");
return 1;
}
conn = rsm_connect(argc == 2? argv[1] : _PATH_RESMGR_SOCKET);
if (conn == 0) {
perror("Unable to connect to resource manager");
return 1;
}
p[1].fd = conn->fd;
done = 0;
while (!done) {
char c;
p[0].events = POLLIN|POLLHUP;
p[1].events = POLLIN|POLLHUP;
poll(p, 2, -1);
if (p[0].revents & POLLIN) {
if (read(0, &c, 1) == 1
&& rsm_send(conn, &c, 1) < 0) {
perror("rsm_send");
return 1;
}
}
if (p[0].revents & POLLHUP) {
done++;
}
if (p[1].revents & POLLIN) {
char buffer[1024];
if (rsm_recv(conn, buffer, sizeof(buffer)) < 0) {
perror("rsm_recv");
return 1;
}
if (conn->passfd >= 0) {
printf("Received a file descriptor [%u] %s\n",
conn->passfd, identify(conn->passfd));
close(conn->passfd);
conn->passfd = -1;
}
write(0, buffer, strlen(buffer));
}
if (p[1].revents & POLLHUP) {
printf("Server closed connection\n");
done++;
}
}
return 0;
}
const char *
identify(int fd)
{
static char string[1024];
struct stat stb;
const char *result;
if (fstat(fd, &stb) < 0)
return strerror(errno);
result = find("/dev", stb.st_dev, stb.st_ino);
if (result == NULL)
result = find(_PATH_PROC_BUS_USB,
stb.st_dev, stb.st_ino);
if (result == NULL) {
snprintf(string, sizeof(string),
"(unknown device 0x%x/%lu)",
(unsigned) stb.st_dev, stb.st_ino);
result = string;
}
return result;
}
const char *
find(const char *dirname, dev_t dev, ino_t ino)
{
static char result[1024];
char namebuf[1024];
struct stat stb;
DIR *dir;
struct dirent *de;
if (!strcmp(dirname, "/dev/fd"))
return NULL;
if ((dir = opendir(dirname)) == NULL) {
perror(dirname);
return NULL;
}
while ((de = readdir(dir)) != NULL) {
if (de->d_name[0] == '.')
continue;
snprintf(namebuf, sizeof(namebuf), "%s/%s",
dirname, de->d_name);
if (stat(namebuf, &stb) < 0)
continue;
if (stb.st_dev == dev && stb.st_ino == ino) {
strcpy(result, namebuf);
closedir(dir);
return result;
}
if (S_ISDIR(stb.st_mode) && find(namebuf, dev, ino))
return result;
}
closedir(dir);
return NULL;
}
|