Skip to content

Instantly share code, notes, and snippets.

@insom
Created May 9, 2013 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save insom/5551176 to your computer and use it in GitHub Desktop.
Save insom/5551176 to your computer and use it in GitHub Desktop.
Enough LXC to create separate networking stack and to bring up a usable getty.
#include <sched.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int child(void *n) {
char buf[512] = {0};
mount("/proc", "/proc", "proc", 0, NULL);
// mount("devpts", "/dev/pts", "devpts", 0, "newinstance,ptmxmode=0666,mode=0620,gid=5");
system("ifconfig slave 192.168.0.190/24 up");
close(2);
close(1);
close(0);
sprintf(buf, "agetty -L 38400 pts/%d vt100", *((int *)n));
system(buf);
sleep(30);
return 0;
}
void main(void) {
int cflags;
int stacksize = getpagesize() * 4;
char *stack, *stacktop;
char buf[1024] = {0}; // Bless me Father, for I have sinned.
int ptmx;
int unlock = 0;
int ptyno;
pid_t pid;
void *pointer;
int val;
cflags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD|CLONE_NEWNET;
stack = (char *)malloc(stacksize);
stacktop = stack + stacksize;
system("ip link add name master type veth peer name slave");
system("ifconfig master up");
system("brctl addif br1 master");
ptmx = open("/dev/pts/ptmx", O_RDWR|O_NOCTTY|O_NONBLOCK);
ioctl(ptmx, TIOCSPTLCK, &unlock);
pointer = (void *)malloc(1);
ioctl(ptmx, TIOCGPTN, pointer);
sleep(5); // Give the bridge a chance to spin up
pid = clone(child, stacktop, cflags, pointer);
sprintf(buf, "ip link set slave netns %d", pid);
system(buf);
val = fcntl(0, F_GETFL, 0);
fcntl(0, F_SETFL, val|O_NONBLOCK);
for(;;) {
int i = 0;
i = read(ptmx, buf, 512);
if(i > 0) {
write(1, buf, i);
} else {
sleep(1);
}
i = read(0, buf, 512);
if(i > 0) {
write(ptmx, buf, i);
}
}
}
@insom
Copy link
Author

insom commented May 9, 2013

That's an unforgivably bad read-write loop at the bottom of main, but it's late and I've gotta go to bed. select() is for people with time on their hands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment