ref: 59402bf42b8b199218f1f0d111aaf273a3c1806a
dir: /srv.c/
#include <u.h>
#include <libc.h>
#include <bio.h>
#include <ndb.h>
#include <String.h>
#include "dat.h"
#include "fns.h"
static char *protos[] = {
"tcp", "udp", "il",
};
static char*
findnumber(char *s)
{
while (*s) {
if (*s >= '0' && *s <= '9')
return s;
s++;
}
return nil;
}
static int
validproto(char *proto)
{
int n = sizeof(protos) / sizeof(*protos);
for (int i = 0; i < n; i++)
if (strcmp(proto, protos[i]) == 0)
return 1;
return 0;
}
static char*
getport(char *num, char *proto)
{
char *s;
if (!validproto(proto))
return nil;
s = csgetvalue(netdir, "port", num, proto, nil);
return s ? s : strdup(num);
}
static void
condadd(Sys *sys, char *name)
{
char *s;
char num[6];
Tuple *t;
int n;
if (name[0] == '!')
return;
s = findnumber(name);
strncpy(num, s, sizeof(num));
*s = 0;
s = getport(num, name);
if (!s)
return;
t = findtuple(sys, name);
if (!t) {
addtuple(sys, strdup(name), s, 0);
return;
}
/* lengths + ", " + 0 */
n = strlen(t->value);
t->value = realloc(t->value, n + strlen(s) + 2 + 1);
strcpy(&t->value[n], ", ");
strcpy(&t->value[n+2], s);
free(s);
}
void
fetchsrv(Sys *sys, void*)
{
char path[128];
int fd;
Tuple *t;
int n;
Dir *d;
t = findtuple(sys, "sys");
if (!t)
return;
snprint(path, sizeof(path), "/cfg/%s/service", t->value);
fd = open(path, OREAD);
if (fd < 0)
return;
while ((n = dirread(fd, &d)) > 0) {
for (int i = 0; i < n; i++) {
if (!(d[i].mode & DMEXEC))
continue;
condadd(sys, d[i].name);
}
free(d);
}
}