mimgrating from another repo

This commit is contained in:
Xuan Sang LE 2018-09-19 15:10:48 +02:00
parent c945ac0ff5
commit 5db4e33511
7 changed files with 1374 additions and 0 deletions

45
Makefile Normal file
View File

@ -0,0 +1,45 @@
include ../../var.mk
PL_NAME=wvnc
PLUGINS=$(PL_NAME).$(EXT)
APP_DIR=$(BUILDIRD)/htdocs/
OBJS = $(PLUGINS_BASE)/plugin.o
PLUGINSDEP = $(OBJS) \
wvnc.o
PLUGINLIBS = libantd.$(EXT) -lvncclient -lpthread -lz# -lsqlite3
PCFLAGS=-W -Wall -g -D DEBUG $(PPF_FLAG) -D USE_ZLIB
main: $(PLUGINSDEP) $(PLUGINS) #lib
%.o: %.c
$(CC) $(PCFLAGS) -fPIC $(INCFLAG) -c $< -o $@
%.$(EXT):
-ln -s $(PBUILDIRD)/libantd.$(EXT) .
$(CC) $(PCFLAGS) $(PLUGINSDEP) $(PLUGINLIBS) -shared -o $(PBUILDIRD)/$(basename $@).$(EXT)
clean: #libclean
-rm -f *.o *.$(EXT) $(PBUILDIRD)/$(PLUGINS)
-rm $(PLUGINS_BASE)/plugin.o
libclean:
for file in lib/* ;do \
if [ -d "$$file" ]; then \
echo "Cleaning $$file" ;\
make -C "$$file" clean; \
fi \
done
.PRECIOUS: %.o
.PHONY: lib clean
full: clean main

7
test/Makefile Normal file
View File

@ -0,0 +1,7 @@
LDFLAGS="-L/usr/local/opt/jpeg-turbo/lib"
CPPFLAGS="-I/usr/local/opt/jpeg-turbo/include"
main: miniviewer
gcc viewer.c -D_REENTRANT $(CPPFLAGS) -I/usr/include/SDL2 $(LDFLAGS) -lSDL2 -lvncclient -o viewer
miniviewer:
gcc miniviewer.c -D_REENTRANT $(CPPFLAGS) -I/usr/include/SDL2 $(LDFLAGS) -lSDL2 -lvncclient -o viewer

242
test/miniviewer.c Normal file
View File

@ -0,0 +1,242 @@
/**
* @example SDLvncviewer.c
*/
#include <SDL2/SDL.h>
#include <signal.h>
#include <rfb/rfbclient.h>
static int enableResizable = 1, viewOnly, listenLoop, buttonMask;
int sdlFlags;
SDL_Texture *sdlTexture;
SDL_Renderer *sdlRenderer;
SDL_Window *sdlWindow;
static rfbBool resize(rfbClient* client) {
int width=client->width,height=client->height,
depth=client->format.bitsPerPixel;
if (enableResizable)
sdlFlags |= SDL_WINDOW_RESIZABLE;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = width; client->updateRect.h = height;
/* (re)create the surface used as the client's framebuffer */
SDL_FreeSurface(rfbClientGetClientData(client, SDL_Init));
SDL_Surface* sdl=SDL_CreateRGBSurface(0,
width,
height,
depth,
0,0,0,0);
if(!sdl)
rfbClientErr("resize: error creating surface: %s\n", SDL_GetError());
rfbClientSetClientData(client, SDL_Init, sdl);
client->width = sdl->pitch / (depth / 8);
client->frameBuffer=sdl->pixels;
client->format.bitsPerPixel=depth;
client->format.redShift=sdl->format->Rshift;
client->format.greenShift=sdl->format->Gshift;
client->format.blueShift=sdl->format->Bshift;
client->format.redMax=sdl->format->Rmask>>client->format.redShift;
client->format.greenMax=sdl->format->Gmask>>client->format.greenShift;
client->format.blueMax=sdl->format->Bmask>>client->format.blueShift;
SetFormatAndEncodings(client);
/* create or resize the window */
if(!sdlWindow) {
sdlWindow = SDL_CreateWindow(client->desktopName,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
sdlFlags);
if(!sdlWindow)
rfbClientErr("resize: error creating window: %s\n", SDL_GetError());
} else {
SDL_SetWindowSize(sdlWindow, width, height);
}
/* create the renderer if it does not already exist */
if(!sdlRenderer) {
sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);
if(!sdlRenderer)
rfbClientErr("resize: error creating renderer: %s\n", SDL_GetError());
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); /* make the scaled rendering look smoother. */
}
SDL_RenderSetLogicalSize(sdlRenderer, width, height); /* this is a departure from the SDL1.2-based version, but more in the sense of a VNC viewer in keeeping aspect ratio */
/* (re)create the texture that sits in between the surface->pixels and the renderer */
if(sdlTexture)
SDL_DestroyTexture(sdlTexture);
sdlTexture = SDL_CreateTexture(sdlRenderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
width, height);
if(!sdlTexture)
rfbClientErr("resize: error creating texture: %s\n", SDL_GetError());
return TRUE;
}
static void update(rfbClient* cl,int x,int y,int w,int h) {
SDL_Surface *sdl = rfbClientGetClientData(cl, SDL_Init);
/* update texture from surface->pixels */
SDL_Rect r = {x,y,w,h};
if(SDL_UpdateTexture(sdlTexture, &r, sdl->pixels + y*sdl->pitch + x*4, sdl->pitch) < 0)
rfbClientErr("update: failed to update texture: %s\n", SDL_GetError());
/* copy texture to renderer and show */
if(SDL_RenderClear(sdlRenderer) < 0)
rfbClientErr("update: failed to clear renderer: %s\n", SDL_GetError());
if(SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL) < 0)
rfbClientErr("update: failed to copy texture to renderer: %s\n", SDL_GetError());
SDL_RenderPresent(sdlRenderer);
}
static void cleanup(rfbClient* cl)
{
/*
just in case we're running in listenLoop:
close viewer window by restarting SDL video subsystem
*/
SDL_QuitSubSystem(SDL_INIT_VIDEO);
SDL_InitSubSystem(SDL_INIT_VIDEO);
if(cl)
rfbClientCleanup(cl);
}
static rfbBool handleSDLEvent(rfbClient *cl, SDL_Event *e)
{
switch(e->type) {
case SDL_QUIT:
if(listenLoop)
{
cleanup(cl);
return FALSE;
}
else
{
rfbClientCleanup(cl);
exit(0);
}
default:
rfbClientLog("ignore SDL event: 0x%x\n", e->type);
}
return TRUE;
}
/*
static void got_selection(rfbClient *cl, const char *text, int len)
{
rfbClientLog("received clipboard text '%s'\n", text);
if(SDL_SetClipboardText(text) != 0)
rfbClientErr("could not set received clipboard text: %s\n", SDL_GetError());
}
*/
static rfbCredential* get_credential(rfbClient* cl, int credentialType){
rfbCredential *c = malloc(sizeof(rfbCredential));
c->userCredential.username = malloc(RFB_BUF_SIZE);
c->userCredential.password = malloc(RFB_BUF_SIZE);
if(credentialType != rfbCredentialTypeUser) {
rfbClientErr("something else than username and password required for authentication\n");
return NULL;
}
rfbClientLog("username and password required for authentication!\n");
printf("user: ");
fgets(c->userCredential.username, RFB_BUF_SIZE, stdin);
printf("pass: ");
fgets(c->userCredential.password, RFB_BUF_SIZE, stdin);
/* remove trailing newlines */
c->userCredential.username[strcspn(c->userCredential.username, "\n")] = 0;
c->userCredential.password[strcspn(c->userCredential.password, "\n")] = 0;
return c;
}
int main(int argc,char** argv) {
rfbClient* cl;
int i, j;
SDL_Event e;
for (i = 1, j = 1; i < argc; i++)
if (!strcmp(argv[i], "-viewonly"))
viewOnly = 1;
else if (!strcmp(argv[i], "-resizable"))
enableResizable = 1;
else if (!strcmp(argv[i], "-no-resizable"))
enableResizable = 0;
else if (!strcmp(argv[i], "-listen")) {
listenLoop = 1;
argv[i] = "-listennofork";
++j;
}
else {
if (i != j)
argv[j] = argv[i];
j++;
}
argc = j;
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
atexit(SDL_Quit);
signal(SIGINT, exit);
do {
/* 16-bit: cl=rfbGetClient(5,3,2); */
cl=rfbGetClient(8,3,4);
cl->MallocFrameBuffer=resize;
cl->canHandleNewFBSize = TRUE;
cl->GotFrameBufferUpdate=update;
//cl->HandleKeyboardLedState=kbd_leds;
//cl->HandleTextChat=text_chat;
//cl->GotXCutText = got_selection;
cl->GetCredential = get_credential;
cl->listenPort = LISTEN_PORT_OFFSET;
cl->listen6Port = LISTEN_PORT_OFFSET;
if(!rfbInitClient(cl,&argc,argv))
{
cl = NULL; /* rfbInitClient has already freed the client struct */
cleanup(cl);
break;
}
while(1) {
if(SDL_PollEvent(&e)) {
/*
handleSDLEvent() return 0 if user requested window close.
In this case, handleSDLEvent() will have called cleanup().
*/
if(!handleSDLEvent(cl, &e))
break;
}
else {
i=WaitForMessage(cl,500);
if(i<0)
{
cleanup(cl);
break;
}
if(i)
if(!HandleRFBServerMessage(cl))
{
cleanup(cl);
break;
}
}
}
}
while(listenLoop);
return 0;
}

38
test/save-jpeg.cc Normal file
View File

@ -0,0 +1,38 @@
void EncodeJPEG(boost::uint8_t *rgb, const int &width, const int &height,
boost::shared_array<boost::uint8_t> &outbuffer, int *size) {
jpeg_compress_struct cinfo = {0};
jpeg_error_mgr jerror = {0};
jerror.trace_level = 10;
cinfo.err = jpeg_std_error(&jerror);
jerror.trace_level = 10;
cinfo.err->trace_level = 10;
jpeg_create_compress(&cinfo);
boost::uint8_t *jpeg_buffer_raw = NULL;
unsigned long outbuffer_size = 0;
jpeg_mem_dest(&cinfo, &jpeg_buffer_raw, &outbuffer_size);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 100, false);
jpeg_start_compress(&cinfo, true);
JSAMPROW row_pointer[1];
unsigned counter = 0;
while (cinfo.next_scanline < cinfo.image_height) {
row_pointer[0] = (JSAMPROW)(&rgb[cinfo.next_scanline * width * 3]);
unsigned return_code = jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
outbuffer.reset(new boost::uint8_t[outbuffer_size]);
std::memcpy(outbuffer.get(), jpeg_buffer_raw, outbuffer_size);
*size = outbuffer_size;
std::free(jpeg_buffer_raw);
}

BIN
test/viewer Executable file

Binary file not shown.

536
test/viewer.c Normal file
View File

@ -0,0 +1,536 @@
/**
* @example SDLvncviewer.c
*/
#include <SDL.h>
#include <signal.h>
#include <rfb/rfbclient.h>
struct { int sdl; int rfb; } buttonMapping[]={
{1, rfbButton1Mask},
{2, rfbButton2Mask},
{3, rfbButton3Mask},
{4, rfbButton4Mask},
{5, rfbButton5Mask},
{0,0}
};
struct { char mask; int bits_stored; } utf8Mapping[]= {
{0b00111111, 6},
{0b01111111, 7},
{0b00011111, 5},
{0b00001111, 4},
{0b00000111, 3},
{0,0}
};
static int enableResizable = 1, viewOnly, listenLoop, buttonMask;
int sdlFlags;
SDL_Texture *sdlTexture;
SDL_Renderer *sdlRenderer;
SDL_Window *sdlWindow;
/* client's pointer position */
int x,y;
static int rightAltKeyDown, leftAltKeyDown;
static rfbBool resize(rfbClient* client) {
int width=client->width,height=client->height,
depth=client->format.bitsPerPixel;
if (enableResizable)
sdlFlags |= SDL_WINDOW_RESIZABLE;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = width; client->updateRect.h = height;
/* (re)create the surface used as the client's framebuffer */
SDL_FreeSurface(rfbClientGetClientData(client, SDL_Init));
SDL_Surface* sdl=SDL_CreateRGBSurface(0,
width,
height,
depth,
0,0,0,0);
if(!sdl)
rfbClientErr("resize: error creating surface: %s\n", SDL_GetError());
rfbClientSetClientData(client, SDL_Init, sdl);
client->width = sdl->pitch / (depth / 8);
client->frameBuffer=sdl->pixels;
client->format.bitsPerPixel=depth;
client->format.redShift=sdl->format->Rshift;
client->format.greenShift=sdl->format->Gshift;
client->format.blueShift=sdl->format->Bshift;
client->format.redMax=sdl->format->Rmask>>client->format.redShift;
client->format.greenMax=sdl->format->Gmask>>client->format.greenShift;
client->format.blueMax=sdl->format->Bmask>>client->format.blueShift;
SetFormatAndEncodings(client);
/* create or resize the window */
if(!sdlWindow) {
sdlWindow = SDL_CreateWindow(client->desktopName,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
sdlFlags);
if(!sdlWindow)
rfbClientErr("resize: error creating window: %s\n", SDL_GetError());
} else {
SDL_SetWindowSize(sdlWindow, width, height);
}
/* create the renderer if it does not already exist */
if(!sdlRenderer) {
sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);
if(!sdlRenderer)
rfbClientErr("resize: error creating renderer: %s\n", SDL_GetError());
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); /* make the scaled rendering look smoother. */
}
SDL_RenderSetLogicalSize(sdlRenderer, width, height); /* this is a departure from the SDL1.2-based version, but more in the sense of a VNC viewer in keeeping aspect ratio */
/* (re)create the texture that sits in between the surface->pixels and the renderer */
if(sdlTexture)
SDL_DestroyTexture(sdlTexture);
sdlTexture = SDL_CreateTexture(sdlRenderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
width, height);
if(!sdlTexture)
rfbClientErr("resize: error creating texture: %s\n", SDL_GetError());
return TRUE;
}
static rfbKeySym SDL_key2rfbKeySym(SDL_KeyboardEvent* e) {
rfbKeySym k = 0;
SDL_Keycode sym = e->keysym.sym;
switch (sym) {
case SDLK_BACKSPACE: k = XK_BackSpace; break;
case SDLK_TAB: k = XK_Tab; break;
case SDLK_CLEAR: k = XK_Clear; break;
case SDLK_RETURN: k = XK_Return; break;
case SDLK_PAUSE: k = XK_Pause; break;
case SDLK_ESCAPE: k = XK_Escape; break;
case SDLK_DELETE: k = XK_Delete; break;
case SDLK_KP_0: k = XK_KP_0; break;
case SDLK_KP_1: k = XK_KP_1; break;
case SDLK_KP_2: k = XK_KP_2; break;
case SDLK_KP_3: k = XK_KP_3; break;
case SDLK_KP_4: k = XK_KP_4; break;
case SDLK_KP_5: k = XK_KP_5; break;
case SDLK_KP_6: k = XK_KP_6; break;
case SDLK_KP_7: k = XK_KP_7; break;
case SDLK_KP_8: k = XK_KP_8; break;
case SDLK_KP_9: k = XK_KP_9; break;
case SDLK_KP_PERIOD: k = XK_KP_Decimal; break;
case SDLK_KP_DIVIDE: k = XK_KP_Divide; break;
case SDLK_KP_MULTIPLY: k = XK_KP_Multiply; break;
case SDLK_KP_MINUS: k = XK_KP_Subtract; break;
case SDLK_KP_PLUS: k = XK_KP_Add; break;
case SDLK_KP_ENTER: k = XK_KP_Enter; break;
case SDLK_KP_EQUALS: k = XK_KP_Equal; break;
case SDLK_UP: k = XK_Up; break;
case SDLK_DOWN: k = XK_Down; break;
case SDLK_RIGHT: k = XK_Right; break;
case SDLK_LEFT: k = XK_Left; break;
case SDLK_INSERT: k = XK_Insert; break;
case SDLK_HOME: k = XK_Home; break;
case SDLK_END: k = XK_End; break;
case SDLK_PAGEUP: k = XK_Page_Up; break;
case SDLK_PAGEDOWN: k = XK_Page_Down; break;
case SDLK_F1: k = XK_F1; break;
case SDLK_F2: k = XK_F2; break;
case SDLK_F3: k = XK_F3; break;
case SDLK_F4: k = XK_F4; break;
case SDLK_F5: k = XK_F5; break;
case SDLK_F6: k = XK_F6; break;
case SDLK_F7: k = XK_F7; break;
case SDLK_F8: k = XK_F8; break;
case SDLK_F9: k = XK_F9; break;
case SDLK_F10: k = XK_F10; break;
case SDLK_F11: k = XK_F11; break;
case SDLK_F12: k = XK_F12; break;
case SDLK_F13: k = XK_F13; break;
case SDLK_F14: k = XK_F14; break;
case SDLK_F15: k = XK_F15; break;
case SDLK_NUMLOCKCLEAR: k = XK_Num_Lock; break;
case SDLK_CAPSLOCK: k = XK_Caps_Lock; break;
case SDLK_SCROLLLOCK: k = XK_Scroll_Lock; break;
case SDLK_RSHIFT: k = XK_Shift_R; break;
case SDLK_LSHIFT: k = XK_Shift_L; break;
case SDLK_RCTRL: k = XK_Control_R; break;
case SDLK_LCTRL: k = XK_Control_L; break;
case SDLK_RALT: k = XK_Alt_R; break;
case SDLK_LALT: k = XK_Alt_L; break;
case SDLK_LGUI: k = XK_Super_L; break;
case SDLK_RGUI: k = XK_Super_R; break;
#if 0
case SDLK_COMPOSE: k = XK_Compose; break;
#endif
case SDLK_MODE: k = XK_Mode_switch; break;
case SDLK_HELP: k = XK_Help; break;
case SDLK_PRINTSCREEN: k = XK_Print; break;
case SDLK_SYSREQ: k = XK_Sys_Req; break;
default: break;
}
/* SDL_TEXTINPUT does not generate characters if ctrl is down, so handle those here */
if (k == 0 && sym > 0x0 && sym < 0x100 && e->keysym.mod & KMOD_CTRL)
k = sym;
return k;
}
/* UTF-8 decoding is from https://rosettacode.org/wiki/UTF-8_encode_and_decode which is under GFDL 1.2 */
static rfbKeySym utf8char2rfbKeySym(const char chr[4]) {
int bytes = strlen(chr);
int shift = utf8Mapping[0].bits_stored * (bytes - 1);
rfbKeySym codep = (*chr++ & utf8Mapping[bytes].mask) << shift;
int i;
for(i = 1; i < bytes; ++i, ++chr) {
shift -= utf8Mapping[0].bits_stored;
codep |= ((char)*chr & utf8Mapping[0].mask) << shift;
}
return codep;
}
static void update(rfbClient* cl,int x,int y,int w,int h) {
SDL_Surface *sdl = rfbClientGetClientData(cl, SDL_Init);
/* update texture from surface->pixels */
SDL_Rect r = {x,y,w,h};
if(SDL_UpdateTexture(sdlTexture, &r, sdl->pixels + y*sdl->pitch + x*4, sdl->pitch) < 0)
rfbClientErr("update: failed to update texture: %s\n", SDL_GetError());
/* copy texture to renderer and show */
if(SDL_RenderClear(sdlRenderer) < 0)
rfbClientErr("update: failed to clear renderer: %s\n", SDL_GetError());
if(SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL) < 0)
rfbClientErr("update: failed to copy texture to renderer: %s\n", SDL_GetError());
SDL_RenderPresent(sdlRenderer);
}
static void kbd_leds(rfbClient* cl, int value, int pad) {
/* note: pad is for future expansion 0=unused */
fprintf(stderr,"Led State= 0x%02X\n", value);
fflush(stderr);
}
/* trivial support for textchat */
static void text_chat(rfbClient* cl, int value, char *text) {
switch(value) {
case rfbTextChatOpen:
fprintf(stderr,"TextChat: We should open a textchat window!\n");
TextChatOpen(cl);
break;
case rfbTextChatClose:
fprintf(stderr,"TextChat: We should close our window!\n");
break;
case rfbTextChatFinished:
fprintf(stderr,"TextChat: We should close our window!\n");
break;
default:
fprintf(stderr,"TextChat: Received \"%s\"\n", text);
break;
}
fflush(stderr);
}
#ifdef __MINGW32__
#define LOG_TO_FILE
#endif
#ifdef LOG_TO_FILE
#include <stdarg.h>
static void
log_to_file(const char *format, ...)
{
FILE* logfile;
static char* logfile_str=0;
va_list args;
char buf[256];
time_t log_clock;
if(!rfbEnableClientLogging)
return;
if(logfile_str==0) {
logfile_str=getenv("VNCLOG");
if(logfile_str==0)
logfile_str="vnc.log";
}
logfile=fopen(logfile_str,"a");
va_start(args, format);
time(&log_clock);
strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock));
fprintf(logfile,buf);
vfprintf(logfile, format, args);
fflush(logfile);
va_end(args);
fclose(logfile);
}
#endif
static void cleanup(rfbClient* cl)
{
/*
just in case we're running in listenLoop:
close viewer window by restarting SDL video subsystem
*/
SDL_QuitSubSystem(SDL_INIT_VIDEO);
SDL_InitSubSystem(SDL_INIT_VIDEO);
if(cl)
rfbClientCleanup(cl);
}
static rfbBool handleSDLEvent(rfbClient *cl, SDL_Event *e)
{
switch(e->type) {
case SDL_WINDOWEVENT:
switch (e->window.event) {
case SDL_WINDOWEVENT_EXPOSED:
SendFramebufferUpdateRequest(cl, 0, 0,
cl->width, cl->height, FALSE);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
if (SDL_HasClipboardText()) {
char *text = SDL_GetClipboardText();
if(text) {
rfbClientLog("sending clipboard text '%s'\n", text);
SendClientCutText(cl, text, strlen(text));
}
}
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
if (rightAltKeyDown) {
SendKeyEvent(cl, XK_Alt_R, FALSE);
rightAltKeyDown = FALSE;
rfbClientLog("released right Alt key\n");
}
if (leftAltKeyDown) {
SendKeyEvent(cl, XK_Alt_L, FALSE);
leftAltKeyDown = FALSE;
rfbClientLog("released left Alt key\n");
}
break;
}
break;
case SDL_MOUSEWHEEL:
{
int steps;
if (viewOnly)
break;
if(e->wheel.y > 0)
for(steps = 0; steps < e->wheel.y; ++steps) {
SendPointerEvent(cl, x, y, rfbButton4Mask);
SendPointerEvent(cl, x, y, 0);
}
if(e->wheel.y < 0)
for(steps = 0; steps > e->wheel.y; --steps) {
SendPointerEvent(cl, x, y, rfbButton5Mask);
SendPointerEvent(cl, x, y, 0);
}
if(e->wheel.x > 0)
for(steps = 0; steps < e->wheel.x; ++steps) {
SendPointerEvent(cl, x, y, 0b01000000);
SendPointerEvent(cl, x, y, 0);
}
if(e->wheel.x < 0)
for(steps = 0; steps > e->wheel.x; --steps) {
SendPointerEvent(cl, x, y, 0b00100000);
SendPointerEvent(cl, x, y, 0);
}
break;
}
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEMOTION:
{
int state, i;
if (viewOnly)
break;
if (e->type == SDL_MOUSEMOTION) {
x = e->motion.x;
y = e->motion.y;
state = e->motion.state;
}
else {
x = e->button.x;
y = e->button.y;
state = e->button.button;
for (i = 0; buttonMapping[i].sdl; i++)
if (state == buttonMapping[i].sdl) {
state = buttonMapping[i].rfb;
if (e->type == SDL_MOUSEBUTTONDOWN)
buttonMask |= state;
else
buttonMask &= ~state;
break;
}
}
SendPointerEvent(cl, x, y, buttonMask);
buttonMask &= ~(rfbButton4Mask | rfbButton5Mask);
break;
}
case SDL_KEYUP:
case SDL_KEYDOWN:
if (viewOnly)
break;
SendKeyEvent(cl, SDL_key2rfbKeySym(&e->key),
e->type == SDL_KEYDOWN ? TRUE : FALSE);
if (e->key.keysym.sym == SDLK_RALT)
rightAltKeyDown = e->type == SDL_KEYDOWN;
if (e->key.keysym.sym == SDLK_LALT)
leftAltKeyDown = e->type == SDL_KEYDOWN;
break;
case SDL_TEXTINPUT:
if (viewOnly)
break;
rfbKeySym sym = utf8char2rfbKeySym(e->text.text);
SendKeyEvent(cl, sym, TRUE);
SendKeyEvent(cl, sym, FALSE);
break;
case SDL_QUIT:
if(listenLoop)
{
cleanup(cl);
return FALSE;
}
else
{
rfbClientCleanup(cl);
exit(0);
}
default:
rfbClientLog("ignore SDL event: 0x%x\n", e->type);
}
return TRUE;
}
static void got_selection(rfbClient *cl, const char *text, int len)
{
rfbClientLog("received clipboard text '%s'\n", text);
if(SDL_SetClipboardText(text) != 0)
rfbClientErr("could not set received clipboard text: %s\n", SDL_GetError());
}
static rfbCredential* get_credential(rfbClient* cl, int credentialType){
rfbCredential *c = malloc(sizeof(rfbCredential));
c->userCredential.username = malloc(RFB_BUF_SIZE);
c->userCredential.password = malloc(RFB_BUF_SIZE);
if(credentialType != rfbCredentialTypeUser) {
rfbClientErr("something else than username and password required for authentication\n");
return NULL;
}
rfbClientLog("username and password required for authentication!\n");
printf("user: ");
fgets(c->userCredential.username, RFB_BUF_SIZE, stdin);
printf("pass: ");
fgets(c->userCredential.password, RFB_BUF_SIZE, stdin);
/* remove trailing newlines */
c->userCredential.username[strcspn(c->userCredential.username, "\n")] = 0;
c->userCredential.password[strcspn(c->userCredential.password, "\n")] = 0;
return c;
}
#ifdef mac
#define main SDLmain
#endif
int main(int argc,char** argv) {
rfbClient* cl;
int i, j;
SDL_Event e;
#ifdef LOG_TO_FILE
rfbClientLog=rfbClientErr=log_to_file;
#endif
for (i = 1, j = 1; i < argc; i++)
if (!strcmp(argv[i], "-viewonly"))
viewOnly = 1;
else if (!strcmp(argv[i], "-resizable"))
enableResizable = 1;
else if (!strcmp(argv[i], "-no-resizable"))
enableResizable = 0;
else if (!strcmp(argv[i], "-listen")) {
listenLoop = 1;
argv[i] = "-listennofork";
++j;
}
else {
if (i != j)
argv[j] = argv[i];
j++;
}
argc = j;
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
atexit(SDL_Quit);
signal(SIGINT, exit);
do {
/* 16-bit: cl=rfbGetClient(5,3,2); */
cl=rfbGetClient(8,3,4);
cl->MallocFrameBuffer=resize;
cl->canHandleNewFBSize = TRUE;
cl->GotFrameBufferUpdate=update;
cl->HandleKeyboardLedState=kbd_leds;
cl->HandleTextChat=text_chat;
cl->GotXCutText = got_selection;
cl->GetCredential = get_credential;
cl->listenPort = LISTEN_PORT_OFFSET;
cl->listen6Port = LISTEN_PORT_OFFSET;
if(!rfbInitClient(cl,&argc,argv))
{
cl = NULL; /* rfbInitClient has already freed the client struct */
cleanup(cl);
break;
}
while(1) {
if(SDL_PollEvent(&e)) {
/*
handleSDLEvent() return 0 if user requested window close.
In this case, handleSDLEvent() will have called cleanup().
*/
if(!handleSDLEvent(cl, &e))
break;
}
else {
i=WaitForMessage(cl,500);
if(i<0)
{
cleanup(cl);
break;
}
if(i)
if(!HandleRFBServerMessage(cl))
{
cleanup(cl);
break;
}
}
}
}
while(listenLoop);
return 0;
}

506
wvnc.c Normal file
View File

@ -0,0 +1,506 @@
#include <stdlib.h>
#include <string.h>
#include <rfb/rfbclient.h>
#include <pthread.h>
#ifdef USE_ZLIB
#include <zlib.h>
#endif
#include "plugin.h"
#define get_user_data(x) ((wvnc_user_data_t *)x)
#define R_SHIFT(x) (0)
#define G_SHIFT(x) ((x >= 24) ? 8 :)
/*
Vnc to web socket using the
libvncserver/libvncclient
*/
typedef struct
{
uint8_t cmd;
uint16_t size;
uint8_t *data;
} wvnc_cmd_t;
typedef struct
{
void *client;
int status;
void *vncl;
} wvnc_user_data_t;
typedef struct
{
uint8_t r_shift;
uint8_t g_shift;
uint8_t b_shift;
uint8_t r_max;
uint8_t g_max;
uint8_t b_max;
} wvnc_pixel_format_t;
void *vnc_fatal(void *client, const char *msg);
void *identify();
void *process(void *cl, int wait);
static rfbBool resize(rfbClient *client);
void open_session(void *client, const char *addr);
void *consume_client(void *cl, wvnc_cmd_t header);
static rfbCredential *get_credential(rfbClient *cl, int credentialType);
static void update(rfbClient *cl, int x, int y, int w, int h);
#ifdef USE_ZLIB
int buff_compress(uint8_t* src, uint8_t* dest, int len)
{
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
// setup "a" as the input and "b" as the compressed output
defstream.avail_in = (uInt)len; // size of input
defstream.next_in = (Bytef *)src; // input char array
defstream.avail_out = (uInt)len; // size of output
defstream.next_out = (Bytef *)dest; // output char array
// the actual compression work.
deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
return defstream.total_out;
}
#endif
int get_pixel_format(uint8_t deep, wvnc_pixel_format_t *d)
{
switch (deep)
{
case 32:
case 24:
d->r_shift = 0;
d->g_shift = 8;
d->b_shift = 16;
d->r_max = d->b_max = d->g_max = 255;
return 1;
break;
case 16:
// RGB 565 format
d->r_shift = 0;
d->g_shift = 5;
d->b_shift = 11;
d->r_max = 31;
d->b_max = 31;
d->g_max = 63;
return 1;
default:
break;
}
return 0;
}
void pexit()
{
}
void *identify()
{
void *ptr = (void *)pthread_self();
//printf("stackaddr = %p\n", ptr);
return ptr;
}
void *process(void *data, int wait)
{
wvnc_user_data_t *user_data = get_user_data(data);
uint8_t *buff = NULL;
ws_msg_header_t *h = NULL;
while (!(h = ws_read_header(user_data->client)) && user_data->status && wait)
;
if (h)
{
if (h->mask == 0)
{
LOG("%s\n", "data is not masked");
ws_close(user_data->client, 1012);
user_data->status = 0;
free(h);
return NULL;
//break;
}
if (h->opcode == WS_CLOSE)
{
LOG("%s\n", "Websocket: connection closed");
ws_close(user_data->client, 1011);
user_data->status = 0;
free(h);
return 0;
//break;
}
else if (h->opcode == WS_BIN)
{
int l;
buff = (uint8_t *)malloc(h->plen + 1);
if (!buff)
{
free(h);
return vnc_fatal(user_data, "Cannot alloc memory for the command");
}
// read the command from the client
int len = h->plen;
if ((l = ws_read_data(user_data->client, h, h->plen, buff)) > 0)
{
// process client command
wvnc_cmd_t header;
header.cmd = buff[0];
buff[len] = '\0';
header.data = (buff + 3);
memcpy(&header.size, buff + 1, 2);
void *st = consume_client(user_data, header);
if (buff)
free(buff);
free(h);
return st;
}
else
{
vnc_fatal(user_data, "Invalid request");
if (buff)
free(buff);
free(h);
return 0;
//break;
}
//buff = NULL;
}
else
{
vnc_fatal(user_data, "Unknow opcode");
free(h);
return 0;
}
}
return 0;
}
static rfbBool resize(rfbClient *client)
{
int width = client->width;
int height = client->height;
int depth = client->format.bitsPerPixel;
LOG("width %d, height %d, depth %d\n", width, height, depth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = width;
client->updateRect.h = height;
//depth = 32;
void *data = rfbClientGetClientData(client, identify());
wvnc_user_data_t *user_data = get_user_data(data);
//client->width = sdl->pitch / (depth / 8);
if (client->frameBuffer)
free(client->frameBuffer);
client->frameBuffer = (uint8_t *)malloc(width * height * depth / 8);
wvnc_pixel_format_t pxf;
if (!get_pixel_format(depth, &pxf))
{
vnc_fatal(user_data, "Cannot get pixel format");
return FALSE;
}
client->format.bitsPerPixel = depth;
client->format.redShift = pxf.r_shift;
client->format.greenShift = pxf.g_shift;
client->format.blueShift = pxf.b_shift;
client->format.redMax = pxf.r_max;
client->format.greenMax = pxf.g_max;
client->format.blueMax = pxf.b_max;
SetFormatAndEncodings(client);
/* create or resize the window */
// send data to client
uint8_t cmd[6];
cmd[0] = 0x83; // resize command
cmd[1] = (uint8_t)(width & 0xFF);
cmd[2] = (uint8_t)(width >> 8);
cmd[3] = (uint8_t)(height & 0xFF);
cmd[4] = (uint8_t)(height >> 8);
cmd[5] = (uint8_t)depth;
ws_b(user_data->client, cmd, 6);
uint8_t *ack = (uint8_t *)process(user_data, 1);
if (!ack || !(*ack))
{
LOG("Client fail to resize\n");
if (ack)
free(ack);
return FALSE;
}
free(ack);
return TRUE;
}
static void update(rfbClient *client, int x, int y, int w, int h)
{
wvnc_user_data_t *user_data = get_user_data(rfbClientGetClientData(client, identify()));
uint8_t bbp = (uint8_t)client->format.bitsPerPixel / 8;
int size = w * h * bbp;
uint8_t *cmd = (uint8_t *)malloc(size + 10); // + 9
#ifdef USE_ZLIB
uint8_t* buff = (uint8_t *)malloc(size);
if (!buff)
{
vnc_fatal(user_data, "Cannot allocate data for update");
return;
}
#endif
if (!cmd)
{
vnc_fatal(user_data, "Cannot allocate data for update");
return;
}
if (!client->frameBuffer)
{
LOG("Client frame buffe data not found\n");
return;
}
#ifdef USE_ZLIB
uint8_t *dest_ptr = buff;
#else
uint8_t *dest_ptr = cmd + 10;
#endif
uint8_t *src_ptr;
//cpy line by line
int cw = client->width;
for(int j = y; j < y+ h; j++)
{
src_ptr = client->frameBuffer + ( j*cw*bbp + x*bbp);
memcpy(dest_ptr, src_ptr, w*bbp);
if(bbp == 4)
for(int i= bbp -1; i < w*bbp; i+=bbp)
dest_ptr[i] = 255;
dest_ptr += w*bbp;
}
cmd[0] = 0x84; //update command
cmd[1] = (uint8_t)(x & 0xFF);
cmd[2] = (uint8_t)(x >> 8);
cmd[3] = (uint8_t)(y & 0xFF);
cmd[4] = (uint8_t)(y >> 8);
cmd[5] = (uint8_t)(w & 0xFF);
cmd[6] = (uint8_t)(w >> 8);
cmd[7] = (uint8_t)(h & 0xFF);
cmd[8] = (uint8_t)(h >> 8);
cmd[9] = 0x0;
#ifdef USE_ZLIB
cmd[9] = 0x1;
size = buff_compress(buff, cmd+10, size);
#endif
ws_b(user_data->client, cmd, size + 10);
free(cmd);
#ifdef USE_ZLIB
free(buff);
#endif
}
static rfbCredential *get_credential(rfbClient *cl, int credentialType)
{
wvnc_user_data_t *user_data = get_user_data(rfbClientGetClientData(cl, identify()));
rfbCredential *c = malloc(sizeof(rfbCredential));
c->userCredential.username = malloc(RFB_BUF_SIZE);
c->userCredential.password = malloc(RFB_BUF_SIZE);
if (credentialType != rfbCredentialTypeUser)
{
vnc_fatal(user_data, "something else than username and password required for authentication\n");
return NULL;
}
uint8_t cmd[1];
cmd[0] = 0x82;
ws_b(user_data->client, cmd, 1);
char *up = (char *)process(user_data, 1);
if (!up)
{
if (c)
{
free(c->userCredential.username);
free(c->userCredential.password);
free(c);
return vnc_fatal(user_data, "Cannot get user credential");
}
}
char *pass = up;
while (*pass != '\0')
pass++;
pass++;
LOG("User name %s, pass: %s\n", up, pass);
memcpy(c->userCredential.username, up, strlen(up) + 1);
memcpy(c->userCredential.password, pass, strlen(pass) + 1);
free(up);
// remove trailing newlines
//c->userCredential.username[strcspn(c->userCredential.username, "\n")] = 0;
//c->userCredential.password[strcspn(c->userCredential.password, "\n")] = 0;
return c;
}
static char *get_password(rfbClient *client)
{
uint8_t cmd[1];
void *data = rfbClientGetClientData(client, identify());
wvnc_user_data_t *user_data = get_user_data(data);
cmd[0] = 0x81; // resize command
ws_b(user_data->client, cmd, 1);
// call process to get the password
char *pwd = (char *)process(user_data, 1);
//not free
if (!pwd)
{
vnc_fatal(user_data, "Cannot read user password");
return NULL;
}
LOG("Password is '%s'\n", pwd);
return pwd;
}
void open_session(void *data, const char *addr)
{
// main loop
int argc = 2;
char *argv[2];
argv[0] = "-listennofork";
argv[1] = (char *)addr;
wvnc_user_data_t *user_data = get_user_data(data);
if (!rfbInitClient(user_data->vncl, &argc, argv))
{
user_data->vncl = NULL; /* rfbInitClient has already freed the client struct */
//cleanup(vncl);
vnc_fatal(user_data, "Cannot connect to the server");
return;
}
while (1)
{
if (!user_data->status)
{
if (user_data->vncl)
rfbClientCleanup(user_data->vncl);
break;
}
process(user_data, 0);
//LOG("ENd process \n");
int status = WaitForMessage(user_data->vncl, 500);//500
if (status < 0)
{
if (user_data->vncl)
rfbClientCleanup(user_data->vncl);
break;
}
if (status)
{
if (!HandleRFBServerMessage(user_data->vncl))
{
if (user_data->vncl)
rfbClientCleanup(user_data->vncl);
break;
}
}
}
return;
}
void *vnc_fatal(void *data, const char *msg)
{
// print the message then close the
// connection
wvnc_user_data_t *user_data = get_user_data(data);
int len, size;
len = strlen(msg);
size = len + 1;
LOG("%s\n", msg);
uint8_t *cmd = (uint8_t *)malloc(size);
cmd[0] = 0xFE; // error opcode
user_data->status = 0;
if (cmd)
{
memcpy(cmd + 1, (uint8_t *)msg, len);
ws_b(user_data->client, cmd, size);
free(cmd);
}
// quit the socket
ws_close(user_data->client, 1011);
return 0;
}
void *consume_client(void *ptr, wvnc_cmd_t header)
{
uint8_t cmd = header.cmd;
uint16_t size = header.size;
wvnc_user_data_t *user_data = get_user_data(ptr);
//LOG("Data size is %d\n", size);
uint8_t *data;
// in case of string
switch (cmd)
{
case 0x01: /*client open a connection*/
open_session(user_data, (char *)header.data);
break;
case 0x02: //client enter a vnc password
if (!header.data)
return NULL;
return strdup((char *)header.data);
case 0x03: // client enter a credential
data = (uint8_t*)malloc(size);
memcpy(data, header.data, size);
return data;
break;
case 0x04: // ack from client
data = (uint8_t *)malloc(1);
*data = (uint8_t)header.data[0];
return data;
break;
case 0x05: //mouse event
SendPointerEvent(user_data->vncl, header.data[0]|(header.data[1]<<8) , header.data[2]|(header.data[3]<<8), header.data[4]);
break;
default:
return vnc_fatal(user_data, "Unknown client command");
}
return NULL;
}
void handle(void *cl, const char *m, const char *rqp, dictionary rq)
{
if (ws_enable(rq))
{
#ifdef USE_ZLIB
LOG("Zlib is enabled\n");
#endif
//set time out for the tcp socket
// set timeout to socket
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 500;
if (setsockopt(((antd_client_t *)cl)->sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
perror("setsockopt failed\n");
//if (setsockopt (((antd_client_t*)cl)->sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,sizeof(timeout)) < 0)
// perror("setsockopt failed\n");
//rfbClient* vncl;
rfbClient *vncl = NULL;
vncl = rfbGetClient(8, 3, 4);
vncl->MallocFrameBuffer = resize;
vncl->canHandleNewFBSize = TRUE;
vncl->GotFrameBufferUpdate = update;
vncl->GetPassword = get_password;
//cl->HandleKeyboardLedState=kbd_leds;
//cl->HandleTextChat=text_chat;
//cl->GotXCutText = got_selection;
vncl->GetCredential = get_credential;
vncl->listenPort = LISTEN_PORT_OFFSET;
vncl->listen6Port = LISTEN_PORT_OFFSET;
wvnc_user_data_t *user_data = (wvnc_user_data_t *)malloc(sizeof(wvnc_user_data_t));
user_data->client = cl;
user_data->status = 1;
user_data->vncl = vncl;
rfbClientSetClientData(vncl, identify(), user_data);
//while(1)
//{
process(user_data, 1);
//}
}
LOG("%s\n", "EXIT Streaming..");
}