#include <sys/param.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <atf-c.h>
const char create_pat[] = "!system=DEVFS subsystem=CDEV type=CREATE cdev=md";
const char destroy_pat[] = "!system=DEVFS subsystem=CDEV type=DESTROY cdev=md";
static void
create_two_events(void)
{
FILE *create_stdout;
FILE *destroy_stdout;
char mdname[80];
char destroy_cmd[95];
char *error;
create_stdout = popen("mdconfig -a -s 64 -t null", "r");
ATF_REQUIRE(create_stdout != NULL);
error = fgets(mdname, sizeof(mdname), create_stdout);
ATF_REQUIRE(error != NULL);
ATF_REQUIRE_EQ(0, pclose(create_stdout));
snprintf(destroy_cmd, nitems(destroy_cmd), "mdconfig -d -u %s", mdname);
destroy_stdout = popen(destroy_cmd, "r");
ATF_REQUIRE(destroy_stdout != NULL);
ATF_REQUIRE_EQ(0, pclose(destroy_stdout));
}
static int
common_setup(int socktype, const char* sockpath) {
struct sockaddr_un devd_addr;
int s, error;
memset(&devd_addr, 0, sizeof(devd_addr));
devd_addr.sun_family = PF_LOCAL;
strlcpy(devd_addr.sun_path, sockpath, sizeof(devd_addr.sun_path));
s = socket(PF_LOCAL, socktype, 0);
ATF_REQUIRE(s >= 0);
error = connect(s, (struct sockaddr*)&devd_addr, SUN_LEN(&devd_addr));
ATF_REQUIRE_EQ(0, error);
create_two_events();
return (s);
}
ATF_TC_WITHOUT_HEAD(seqpacket);
ATF_TC_BODY(seqpacket, tc)
{
int s;
bool got_create_event = false;
bool got_destroy_event = false;
s = common_setup(SOCK_SEQPACKET, "/var/run/devd.seqpacket.pipe");
while (!(got_create_event && got_destroy_event)) {
int cmp;
ssize_t len;
char event[1024];
len = recv(s, event, sizeof(event) - 1, MSG_WAITALL);
ATF_REQUIRE(len != -1);
event[len] = '\0';
printf("%s", event);
cmp = strncmp(event, create_pat, sizeof(create_pat) - 1);
if (cmp == 0)
got_create_event = true;
cmp = strncmp(event, destroy_pat, sizeof(destroy_pat) - 1);
if (cmp == 0)
got_destroy_event = true;
}
close(s);
}
ATF_TC_WITHOUT_HEAD(stream);
ATF_TC_BODY(stream, tc)
{
char *event;
int s;
bool got_create_event = false;
bool got_destroy_event = false;
size_t len = 0, sz;
s = common_setup(SOCK_STREAM, "/var/run/devd.pipe");
sz = 1024 * 1024;
event = malloc(sz);
ATF_REQUIRE(event != NULL);
while (!(got_create_event && got_destroy_event) && len < sz - 1) {
ssize_t newlen;
char *create_pos, *destroy_pos;
newlen = read(s, &event[len], sz - len - 1);
ATF_REQUIRE(newlen > 0);
len += newlen;
event[len] = '\0';
create_pos = strstr(event, create_pat);
if (create_pos != NULL)
got_create_event = true;
destroy_pos = strstr(event, destroy_pat);
if (destroy_pos != NULL)
got_destroy_event = true;
}
printf("%s", event);
if (len >= sz - 1)
atf_tc_fail("Event buffer overflowed");
free(event);
close(s);
}
ATF_TP_ADD_TCS(tp)
{
ATF_TP_ADD_TC(tp, seqpacket);
ATF_TP_ADD_TC(tp, stream);
return (atf_no_error());
}