static int LUA_C_tcp_send(lua_State* ls) { SOCKET_ST* st = (SOCKET_ST*)luaL_checkudata(ls, 1, gk_tcp_register); if(st->bind_port != 0) return TCP_ERROR(ls, st, "TCP Server无法发送数据"); size_t len = 0; const char* buf = luaL_checklstring(ls, 2, &len); try { while(len > 0) { int sendlen = ::send(st->sock, buf, len, 0); if(sendlen <= 0) { return TCP_ERROR(ls, st, xmsg() << "TCP发送失败:" << WSAGetLastError()); } len -= sendlen; buf += sendlen; } } catch(const runtime_error& err) { return TCP_ERROR(ls, st, xmsg() << "TCP发送错误:" << err.what()); } catch(...) { return TCP_ERROR(ls, st, "TCP发送异常"); } lua_settop(ls, 1); return 1; }
static int xdecrypt(gcry_cipher_hd_t hd, int blklen, const char *iv, void *dst, size_t dstlen, const void *src, size_t srclen) { int i; gcry_error_t err = 0; char *s = (char *) src, *d = dst; if(dstlen < srclen) return xmsg(-1, VPN_DEBUG, "not enough space to put decrypted data!\n"); for(i = 0; i < srclen; i+=blklen, s+=blklen, d+=blklen) { err = gcry_cipher_setiv(hd, iv, blklen); if(err) { xmsg(0, VPN_DEBUG, "decrypt iv mismatch: %s\n", gpg_strerror(err)); break; } err = gcry_cipher_decrypt(hd, d, blklen, s, blklen); if(err) { xmsg(0, VPN_DEBUG, "decrypt failed: %s\n", gpg_strerror(err)); break; } } return err ? -1 : i; }
static int LUA_C_SerialCommRead(lua_State* ls) { auto sc = SerialCommCheck(ls); DWORD dwErrors; COMSTAT comStat; if(FALSE == ClearCommError(sc->h, &dwErrors, &comStat)) { return SerialCommError(ls, sc, xmsg() << "查询读取数据失败 : " << (intptr_t)GetLastError()); } if(comStat.cbInQue <= 0) { lua_pushstring(ls, ""); return 1; } string buf; buf.resize(comStat.cbInQue); DWORD size = 0; if(FALSE == ReadFile(sc->h, (void*)buf.c_str(), comStat.cbInQue, &size, nullptr)) { return SerialCommError(ls, sc, xmsg() << "读取数据失败 : " << (intptr_t)GetLastError()); } lua_pushlstring(ls, buf.c_str(), size); return 1; }
static int LUA_C_SerialCommWrite(lua_State* ls) { auto sc = SerialCommCheck(ls); size_t l = 0; const auto lp = luaL_checklstring(ls, 2, &l); DWORD size = 0; while(size < l) { DWORD s = 0; if(FALSE == WriteFile(sc->h, &lp[size], l - size, &s, nullptr)) { return SerialCommError(ls, sc, xmsg() << "写入数据失败 : " << (intptr_t)GetLastError()); } size += s; } DWORD dwErrors; COMSTAT comStat; do { if(FALSE == ClearCommError(sc->h, &dwErrors, &comStat)) { return SerialCommError(ls, sc, xmsg() << "等待写入缓冲失败 : " << (intptr_t)GetLastError()); } } while(comStat.cbOutQue > 0); lua_pushinteger(ls, l); return 1; }
static int LUA_C_udp_send(lua_State* ls) { SOCKET_ST* st = (SOCKET_ST*)luaL_checkudata(ls, 1, gk_udp_register); size_t len = 0; const char* buf = luaL_checklstring(ls, 2, &len); if(lua_type(ls, 3) == LUA_TNUMBER) { sockaddr_in addr; addr.sin_addr.s_addr = lua_tointeger(ls, 3); xmsg msg; msg << (int)addr.sin_addr.s_net << '.' << (int)addr.sin_addr.s_host << '.' << (int)addr.sin_addr.s_lh << '.' << (int)addr.sin_addr.s_impno; lua_pushstring(ls, msg.c_str()); lua_replace(ls, 3); } auto ip = luaL_optstring(ls, 3, "0.0.0.0"); auto port = luaL_optstring(ls, 4, "0"); try { auto addrto = AddrInfo(ip, port); if(addrto.sin_addr.S_un.S_addr == 0 && addrto.sin_port == 0) { addrto = st->addr; } while(len > 0) { int sendlen = ::sendto(st->sock, buf, len, 0, (const sockaddr *)&addrto, sizeof(addrto)); if(sendlen <= 0) { return UDP_ERROR(ls, st, xmsg() << "UDP发送失败:" << WSAGetLastError()); } len -= sendlen; buf += sendlen; } } catch(const runtime_error& err) { return UDP_ERROR(ls, st, xmsg() << "UDP发送错误:" << err.what()); } catch(...) { return UDP_ERROR(ls, st, "UDP发送异常"); } lua_settop(ls, 1); return 1; }
static int LUA_C_gzip_compress(lua_State* ls) { size_t l = 0; auto s = luaL_checklstring(ls, 1, &l); if(l == 0) { lua_pushstring(ls, ""); return 1; } string cp; cp.reserve(compressBound(l)); while(true) { z_stream c_stream; c_stream.zalloc = nullptr; c_stream.zfree = nullptr; c_stream.opaque = nullptr; intptr_t rets = deflateInit2(&c_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, 8, Z_DEFAULT_STRATEGY); if(rets != Z_OK) { lua_pushstring(ls, (xmsg() << "gzipѹËõ³õʼ»¯Ê§°Ü : " << rets).c_str()); return lua_error(ls); } c_stream.next_in = (Bytef*)s; c_stream.avail_in = l; c_stream.next_out = (Bytef*)cp.c_str(); c_stream.avail_out = cp.capacity(); rets = deflate(&c_stream, Z_FINISH); const intptr_t rend = deflateEnd(&c_stream); switch(rets) { case Z_STREAM_END: if(rend == Z_OK) { lua_pushlstring(ls, cp.end()._Ptr, c_stream.total_out); return 1; } break; case Z_OK: case Z_BUF_ERROR: cp.reserve(cp.capacity() + 0x10); continue; default: break; } lua_pushstring(ls, (xmsg() << "ѹËõʧ°Ü : " << rets << ' ' << rend).c_str()); return lua_error(ls); } }
static void SerialCommState(lua_State* ls, SerialCommST* sc, DCB& dcb) { if(FALSE == SetCommState(sc->h, &dcb)) { SerialCommError(ls, sc, xmsg() << "设置状态失败 : " << (intptr_t)GetLastError()); } }
static int LUA_C_zlib_compress(lua_State* ls) { size_t l = 0; auto s = luaL_checklstring(ls, 1, &l); if(l == 0) { lua_pushstring(ls, ""); return 1; } string cp; cp.reserve(compressBound(l)); while(true) { size_t size = cp.capacity(); const intptr_t rets = compress( (Bytef*)cp.end()._Ptr, (uLongf*)&size, (const Bytef*)s, (uLongf)l); switch(rets) { case Z_OK: lua_pushlstring(ls, cp.end()._Ptr, size); return 1; case Z_BUF_ERROR: cp.reserve(cp.capacity() + 0x10); continue; default: break; } lua_pushstring(ls, (xmsg() << "zlibѹËõʧ°Ü : " << rets).c_str()); return lua_error(ls); } }
void func2() { /* xmsg msg("This is an exception"); throw msg; */ throw xmsg("This is an exception"); }
static int LUA_C_SerialCommGets(lua_State* ls) { HKEY hKey; DWORD rets = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Hardware\\DeviceMap\\SerialComm"), NULL, KEY_READ, &hKey); if(ERROR_SUCCESS != rets) { lua_pushstring(ls, ( xmsg() << "查询串口失败 : " << (intptr_t)rets << " : " << (intptr_t)GetLastError() ).c_str()); return lua_error(ls); } lua_newtable(ls); TCHAR port_name[MAX_PATH]; TCHAR com_name[MAX_PATH]; for(size_t index = 0; true; ++index) { DWORD dwLong = _countof(port_name); DWORD dwSize = _countof(com_name); rets = RegEnumValue(hKey, index, port_name, &dwLong, nullptr, nullptr, (LPBYTE)com_name, &dwSize); if(ERROR_NO_MORE_ITEMS == rets) break; if(ERROR_SUCCESS != rets) { CloseHandle(hKey); lua_pushstring(ls, ( xmsg() << "枚举串口失败 : " << (intptr_t)rets << " : " << (intptr_t)GetLastError() ).c_str()); return lua_error(ls); } string cn(ws2s(com_name)); lua_pushlstring(ls, cn.c_str(), cn.size()); lua_rawseti(ls, -2, index + 1); } CloseHandle(hKey); return 1; }
static DCB SerialCommState(lua_State* ls, SerialCommST* sc) { DCB dcb; memset(&dcb, 0, sizeof(dcb)); dcb.DCBlength = sizeof(dcb); if(FALSE == GetCommState(sc->h, &dcb)) { SerialCommError(ls, sc, xmsg() << "获取状态失败 : " << (intptr_t)GetLastError()); } return dcb; }
/* exit */ static void mysig(int sig) { xmsg(0, VPN_DEBUG|VPN_INFO, "killed by signal %d\n", sig); /* kill pppd */ if(pppd_pid) kill(pppd_pid, SIGTERM); /* run command */ if(my_ptr && ifup) run_cmd(my_ptr->cmddown, NULL); vpn_cryptfinish(&cry); exit(0); }
void THelp :: AddWindowProc ( int index ) { THelpDefinition & e = HelpTable [index] ; register HANDLE hProp = GetProp ( e. WindowHwnd, HELP_PROPERTY ) ; /*** Premier appel pour ce HWND; on va créer deux propriétés de fenêtre . HELP_PROPERTY, pour indiquer le nombre de fois que cette fenêtre est référencée dans une entrée de HelpTable (ce nombre de références est utilisé ensuite par RemoveWindowProc, qui ne réinstallera la window proc d'origine que si ce nombre tombe à 1) . WNDPROC_PROPERTY, qui sert à stocker l'index de la 1e référence à ce HWND. Les références ultérieures se contenteront de récupérer cet index, afin de pouvoir donner une valeur à leur champ WindowProc (en effet, s'il y avait plusieurs tables d'aide pour une même fenêtre, un deuxièeme appel à GetWindowLong ( GWL_WNDPROC ) retournerait l'adresse de HelpWindowProc, ce qui donnerait une belle GPF). Note : on ajoute 1 à l'index, de manière à pouvoir identifier la valeur 0 comme l'absence de la propriété HELP_PROPERTY. ***/ if ( hProp == NULL ) { SetProp ( e. WindowHwnd, HELP_PROPERTY, ( HANDLE ) 1 ) ; e. WindowProc = ( WNDPROC ) GetWindowLong ( e. WindowHwnd, GWL_WNDPROC ) ; SetWindowLong ( e. WindowHwnd, GWL_WNDPROC, ( DWORD ) HelpWindowProc ) ; SetProp ( e. WindowHwnd, WNDPROC_PROPERTY, ( HANDLE ) ( index + 1 ) ) ; } /*** La fenêtre était déjà référencée. On augmente son nombre de références et on récupère l'index, dans HelpTable, de sa première référence, afin de pouvoir initialiser le champ WindowProc. ***/ else { SetProp ( e. WindowHwnd, HELP_PROPERTY, ( HANDLE ) ( ( DWORD ) hProp + 1 ) ) ; hProp = GetProp ( e. WindowHwnd, WNDPROC_PROPERTY ) ; if ( hProp ) e. WindowProc = HelpTable [ ( int ) hProp - 1 ]. WindowProc ; else throw xmsg ( string ( "La propriété WNDPROC n'a pas été trouvée !" ) ) ; } }
static int LUA_C_tcp_accept(lua_State* ls) { SOCKET_ST* st = (SOCKET_ST*)luaL_checkudata(ls, 1, gk_tcp_register); if(st->bind_port == 0) return TCP_ERROR(ls, st, "TCP Client不能接受连接"); const size_t timeout = luaL_optinteger(ls, 2, -1); timeval t; t.tv_sec = timeout / 1000; t.tv_usec = timeout % 1000; const timeval* lpt = (timeout == -1) ? nullptr : &t; fd_set s; s.fd_count = 1; s.fd_array[0] = st->sock; switch(select(1, &s, nullptr, nullptr, lpt)) { case SOCKET_ERROR: return TCP_ERROR(ls, st, "TCP监听连接失败"); case 0: lua_pushnil(ls); lua_pushstring(ls, "timeout"); return 2; default: break; } sockaddr_in addr; memset(&addr, 0, sizeof(addr)); int namelen = sizeof(addr); const SOCKET hS = accept(st->sock, (sockaddr*)&addr, &namelen); if(hS == INVALID_SOCKET) return TCP_ERROR(ls, st, xmsg() << "TCP接受连接失败:" << WSAGetLastError()); st = (SOCKET_ST*)lua_newuserdata(ls, sizeof(*st)); st->sock = hS; st->addr = addr; st->bind_port = 0; luaL_setmetatable(ls, gk_tcp_register); return 1; }
static int LUA_C_tcp_recv(lua_State* ls) { SOCKET_ST* st = (SOCKET_ST*)luaL_checkudata(ls, 1, gk_tcp_register); if(st->bind_port != 0) return TCP_ERROR(ls, st, "TCP Server无法接收数据"); char buf[0x800]; const int len = luaL_optinteger(ls, 2, sizeof(buf)); char* lp = buf; if(len > sizeof(buf)) { lp = new char[len]; } int recvlen = ::recv(st->sock, lp, len, 0); if(recvlen == 0) { if(lp != buf) delete[] lp; return TCP_ERROR(ls, st, "TCP接收失败,SOCKET已关闭"); } if(recvlen == SOCKET_ERROR) { const int codes = WSAGetLastError(); switch(codes) { case WSAETIMEDOUT: if(lp != buf) delete[] lp; lua_pushnil(ls); lua_pushstring(ls, "timeout"); return 2; default: { if(lp != buf) delete[] lp; return TCP_ERROR(ls, st, xmsg() << "TCP接收失败:" << codes); } } } lua_pushlstring(ls, lp, recvlen); if(lp != buf) delete[] lp; return 1; }
THelp :: THelp ( TWindow * win ) { register int i ; // Vérifier si un objet de ce type a déjà été déclaré if ( TheHelpObject != NULL ) throw xmsg ( string ( "Un objet de type THelp a été déclaré une seconde fois !" ) ) ; TheHelpObject = this ; // Fenêtre parente de WinHelp MainWindow = win ; // Initialisation des touches d'appel; on est sympa, on en fait une par défaut memset ( Hotkeys, 0, sizeof ( Hotkeys ) ) ; Hotkeys [0]. KeyCode = VK_F1 ; Hotkeys [0]. Modifiers = None ; Hotkeys [0]. Type = Normal ; HotkeyCount = 1 ; // Autres initialisations memset ( HelpTable, 0, sizeof ( HelpTable ) ) ; memset ( HelpFileNames, 0, sizeof ( HelpFileNames ) ) ; for ( i = 0 ; i < MAX_HELP_ENTRIES ; i ++ ) HelpTable [i]. HelpFileIndex = -1 ; HelpTableCount = 0 ; LastSelectedMenu = 0 ; LastSelectedMenuType = 0 ; LastSelectedMenuHandle = 0 ; // Puis d'installer le hook qui va nous permettre de récupérer la même chose, // mais pour les menus et les boîtes de dialogue MsgFilterHookId = SetWindowsHookEx ( WH_MSGFILTER, ( HOOKPROC ) MsgFilterHookProc, * ( MainWindow -> GetModule ( ) ), GetCurrentTask ( ) ) ; }
/* save pidfile */ void save_pidfile(const char *suffix) { FILE *fp; char pidfile[1024]; memset(pidfile, 0, sizeof(pidfile)); snprintf(pidfile, sizeof(pidfile), "/var/run/linvpn-%s.pid", suffix); setperm(VPN_ROOT); if((fp = fopen(pidfile, "w")) == NULL) { xmsg(0, VPN_DEBUG|VPN_INFO, "unable to create pidfile %s: %s\n", pidfile, errstr); } else { fprintf(fp, "%d", getpid()); fclose(fp); } setperm(VPN_USER); }
int vpn_recv(int fd, vpn_crypt_t *cry, vpn_proto_t type, void *buf, size_t buflen) { vpn_hdr_t hdr; gcry_cipher_hd_t hd = NULL; char bigpack[VPN_BIGPACKET], decpack[VPN_BIGPACKET], xiv[256], *s; int rr, rd, rc, rx; switch(type) { case VPN_CLIENT: hd = cry->hsrc; break; case VPN_SERVER: hd = cry->hdst; } memset(bigpack, 0, sizeof(bigpack)); memset(decpack, 0, sizeof(decpack)); /* read packet header */ memset(&hdr, 0, sizeof(hdr)); rr = recv(fd, &hdr, sizeof(hdr), 0); if(rr == -1) return rr; else if(!rr) return xmsg(0, VPN_DEBUG|VPN_INFO, "vpn_recv: lost connection, peer disconnected\n"); else if(rr != sizeof(hdr)) return xmsg(-1, VPN_DEBUG|VPN_INFO, "vpn_recv: partial recv of header not allowed\n"); xmsg(0, VPN_DEBUG, "received %d bytes header, checksum=%d and pad=%d\n", rr, hdr.checksum, hdr.pad); if(hdr.checksum > sizeof(bigpack)) return xmsg(-1, VPN_DEBUG|VPN_INFO, "packet too big: header checksum is %d\n", hdr.checksum); /* read packet data */ s = bigpack; rc = hdr.checksum; rx = 0; do { rr = safe_recv(fd, s, rc); if(rr == -1) return rr; else if(!rr) return xmsg(0, VPN_DEBUG|VPN_INFO, "vpn_recv: lost connection, peer disconnected\n"); xmsg(0, VPN_DEBUG, "read %d bytes of packet...\n", rr); s += rr; rx += rr; rc -= rr; } while(rx < hdr.checksum); /* generate iv to decrypt */ if(!cry->rndrecv) cry->rndrecv = initial_iv_random; memset(xiv, 0, sizeof(xiv)); gen_iv(xiv, cry->blklen, cry->rndrecv); /* xmsg(0, VPN_DEBUG, "recv using iv: %s\n", xiv); */ /* decrypt */ rd = xdecrypt(hd, cry->blklen, xiv, decpack, sizeof(decpack), bigpack, hdr.checksum); if(rd == -1 || rd != hdr.checksum) return xmsg(-1, VPN_DEBUG|VPN_INFO, "vpn_recv: cannot decrypt packet (%d != %d)\n", rd, hdr.checksum); /* copy data to user */ memcpy(buf, decpack, hdr.checksum - hdr.pad); /* set next iv */ cry->rndrecv = hdr.checksum - hdr.pad; return hdr.checksum - hdr.pad; }
static int LUA_C_SerialCommOpen(lua_State* ls) { const string names(luaL_checkstring(ls, 1)); const string name = (0 != memcmp(names.c_str(), "\\\\.\\", 4)) ? ("\\\\.\\" + names) : names; HANDLE h = CreateFileA(name.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr); if(h == INVALID_HANDLE_VALUE) { lua_pushstring(ls, ( xmsg() << "串行通讯口[" << names << "]打开失败 : " << (intptr_t)GetLastError() ).c_str()); return lua_error(ls); } DCB dcb; memset(&dcb, 0, sizeof(dcb)); dcb.DCBlength = sizeof(dcb); if(FALSE == GetCommState(h, &dcb)) { CloseHandle(h); lua_pushstring(ls, ( xmsg() << "串行通讯口[" << names << "]打开并获取状态失败 : " << (intptr_t)GetLastError() ).c_str()); return lua_error(ls); } dcb.fBinary = TRUE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fDsrSensitivity = FALSE; dcb.fTXContinueOnXoff = FALSE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fErrorChar = FALSE; dcb.fNull = FALSE; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fAbortOnError = FALSE; if(FALSE == SetCommState(h, &dcb)) { CloseHandle(h); lua_pushstring(ls, ( xmsg() << "串行通讯口[" << names << "]打开并设置状态失败 : " << (intptr_t)GetLastError() ).c_str()); return lua_error(ls); } if(FALSE == PurgeComm(h, PURGE_TXCLEAR | PURGE_RXCLEAR)) { CloseHandle(h); lua_pushstring(ls, ( xmsg() << "串行通讯口[" << names << "]打开并配置状态失败 : " << (intptr_t)GetLastError() ).c_str()); return lua_error(ls); } luaL_getmetatable(ls, gkSerialCommRegister); if(lua_type(ls, -1) == LUA_TNIL) { lua_pop(ls, 1); luaL_newmetatable(ls, gkSerialCommRegister); lua_pushvalue(ls, -1); lua_setfield(ls, -2, "__index"); luaL_setfuncs(ls, gkSerialCommLib, 0); lua_pop(ls, 1); } else { lua_pop(ls, 1); } SerialCommST* ch = (SerialCommST*)lua_newuserdata(ls, sizeof(*ch)); ch->h = h; memcpy(ch->name, names.c_str(), names.size() + 1); luaL_setmetatable(ls, gkSerialCommRegister); return 1; }
static int LUA_C_gzip_uncompress(lua_State* ls) { size_t l = 0; auto s = luaL_checklstring(ls, 1, &l); if(l == 0) { lua_pushstring(ls, ""); return 1; } string str(s, l); string cp; cp.reserve(l * 2); bool head_add = false; static char dummy_head[2] = { 0x8 + 0x7 * 0x10, (((0x8 + 0x7 * 0x10) * 0x100 + 30) / 31 * 31) & 0xFF, }; while(true) { z_stream d_stream = { 0 }; d_stream.zalloc = nullptr; d_stream.zfree = nullptr; d_stream.opaque = nullptr; intptr_t rets = inflateInit2(&d_stream, MAX_WBITS + 16); if(rets != Z_OK) { lua_pushstring(ls, (xmsg() << "gzip½âѹËõ³õʼ»¯Ê§°Ü : " << rets).c_str()); return lua_error(ls); } d_stream.next_in = (Bytef*)str.c_str(); d_stream.avail_in = str.size(); d_stream.next_out = (Bytef*)cp.c_str(); d_stream.avail_out = cp.capacity(); rets = inflate(&d_stream, Z_FINISH); const intptr_t rend = inflateEnd(&d_stream); if((rets == Z_DATA_ERROR) && !head_add) { str.insert(str.begin(), &dummy_head[0], &dummy_head[sizeof(dummy_head)]); head_add = true; continue; } switch(rets) { case Z_STREAM_END: if(rend == Z_OK) { lua_pushlstring(ls, cp.end()._Ptr, d_stream.total_out); return 1; } break; case Z_OK: case Z_BUF_ERROR: cp.reserve(cp.capacity() + 0x10); continue; default: break; } lua_pushstring(ls, (xmsg() << "½âѹËõʧ°Ü : " << rets).c_str()); return lua_error(ls); } }
int run_client(uint16_t port, vpn_conf_t *my) { fd_set fds; int r, fd = 0, ppp = 0; struct in_addr out; struct sockaddr_in s; char temp[VPN_PACKET]; if(vpn_cryptinit(&cry, my->algo, my->srckey, my->dstkey) == -1) return -1; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { xmsg(0, VPN_DEBUG|VPN_INFO, "socket: %s\n", errstr); vpn_cryptfinish(&cry); exit(1); } if(!inet_aton(my->dstaddr, &out)) { xmsg(0, VPN_DEBUG|VPN_INFO, "invalid IP address: %s\n", my->dstaddr); vpn_cryptfinish(&cry); exit(1); } /* connect */ s.sin_family = AF_INET; s.sin_port = port; s.sin_addr = out; if(connect(fd, (struct sockaddr *)&s, sizeof(s)) == -1) { close(fd); vpn_cryptfinish(&cry); return xmsg(-1, VPN_DEBUG|VPN_INFO, "connect (%s): %s\n", my->name, errstr); } /* set O_NONBLOCK, KEEPALIVE and TCP_NODELAY */ sockattr(fd); /* send VPN name */ memset(temp, 0, sizeof(temp)); snprintf(temp, sizeof(temp), "%s\n", my->name); send(fd, temp, strlen(temp), 0); /* xmsg(0, VPN_TERM, "connected to %s, running pppd\n", my->name); */ /* run pppd */ if((ppp = run_pppd(my->ppplocal, my->pppremote, &pppd_pid)) == -1) { close(fd); vpn_cryptfinish(&cry); return xmsg(-1, VPN_DEBUG|VPN_INFO, "unable to start pppd\n"); } else xmsg(0, VPN_INFO, "connected to %s\n", my->name); /* save pidfile */ save_pidfile(my->name); /* set signals */ signal(SIGINT, mysig); signal(SIGTERM, mysig); signal(SIGKILL, mysig); signal(SIGSEGV, mysig); for(;;) { FD_ZERO(&fds); FD_SET(fd, &fds); FD_SET(ppp, &fds); if(select(ppp+1, &fds, 0, 0, 0) >= 1) { memset(temp, 0, sizeof(temp)); if(FD_ISSET(fd, &fds)) { if((r = client_recv(fd, &cry, temp, sizeof(temp))) >= 1) write(ppp, temp, r); else { /* received invalid packet or peer disconnected * kill pppd */ kill(pppd_pid, SIGTERM); break; } } else if(FD_ISSET(ppp, &fds)) { r = read(ppp, temp, sizeof(temp)); if(r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue; else if(r <= 0) { xmsg(0, VPN_DEBUG|VPN_INFO, "lost pppd connection\n"); break; } client_send(fd, &cry, temp, r); } } else break; /* run `up' command */ if(!ifup) { if(!run_cmd(my->cmdup, my->ppplocal)) { my_ptr = my; ifup = 1; } } } if(fd) close(fd); if(ppp) close(ppp); vpn_cryptfinish(&cry); /* run downcmd */ if(ifup) { run_cmd(my->cmddown, NULL); ifup = 0; } return 0; }
static int LUA_C_udp_recv(lua_State* ls) { SOCKET_ST* st = (SOCKET_ST*)luaL_checkudata(ls, 1, gk_udp_register); char buf[0x800]; const int len = luaL_optinteger(ls, 2, sizeof(buf)); char* lp = buf; if(len > sizeof(buf)) { lp = new char[len]; } sockaddr_in addr; int addrlen = sizeof(addr); memset(&addr, 0, sizeof(addr)); int recvlen = ::recvfrom(st->sock, lp, len, 0, (sockaddr*)&addr, &addrlen); if(recvlen == 0) { if(lp != buf) delete[] lp; return UDP_ERROR(ls, st, "UDP接收失败,SOCKET已关闭"); } if(recvlen == SOCKET_ERROR) { const int codes = WSAGetLastError(); switch(codes) { case WSAETIMEDOUT: if(lp != buf) delete[] lp; lua_pushnil(ls); lua_pushstring(ls, "timeout"); return 2; case WSAEMSGSIZE: if(lp != buf) delete[] lp; lua_pushnil(ls); lua_pushstring(ls, "msgsize"); return 2; default: { if(lp != buf) delete[] lp; return UDP_ERROR(ls, st, xmsg() << "UDP接收失败:" << codes); } } } lua_pushlstring(ls, lp, recvlen); if(lp != buf) delete[] lp; xmsg msg; msg << (int)addr.sin_addr.s_net << '.' << (int)addr.sin_addr.s_host << '.' << (int)addr.sin_addr.s_lh << '.' << (int)addr.sin_addr.s_impno; lua_pushstring(ls, msg.c_str()); msg.clear(); msg << (int)htons(addr.sin_port); lua_pushstring(ls, msg.c_str()); lua_pushinteger(ls, htonl(addr.sin_addr.S_un.S_addr)); lua_pushinteger(ls, htons(addr.sin_port)); return 5; }
void func2() { throw xmsg("This is an exception"); }
int THelp :: AddHelp ( THelpApply appliesto, void * object, char * helpfile, TResId id ) { char Buffer [ MAX_PARAMETER_LENGTH ] ; HGLOBAL hGlobal ; HRSRC hResource ; char far * p, * ResourceEnd ; char * q ; THelpEntry * Entries = NULL ; THelpEntry NewEntry ; int EntryCount = 0 ; DWORD ResourceSize ; BOOL Break = FALSE ; // Accéder à la ressource hResource = FindResource ( * :: Module, id, HELP_RESOURCE ) ; ResourceSize = SizeofResource ( * :: Module, hResource ) ; if ( ! hResource ) return ( -1 ) ; hGlobal = LoadResource ( * :: Module, hResource ) ; p = ( char far * ) LockResource ( hGlobal ) ; ResourceEnd = p + ( unsigned int ) ResourceSize ; // Parcours de la resource while ( p < ResourceEnd ) { switch ( * p ) { // DEFINE_WINDOW : 1 seul octet case DEFWINTYPE - '0' : NewEntry. Id = 0 ; NewEntry. Type = WindowStart ; NewEntry. ContextParam = 0L ; p ++ ; break ; // END_WINDOW : 1 seul octet case ENDWINTYPE - '0' : NewEntry. Id = 0 ; NewEntry. Type = WindowEnd ; NewEntry. ContextParam = 0L ; p ++ ; break ; // DEFINE_MENU : 1 octet + 1 chaîne case DEFMENUTYPE - '0' : NewEntry. Id = 0 ; NewEntry. Type = MenuStart ; p ++ ; q = Buffer ; while ( p < ResourceEnd && q < Buffer + sizeof ( Buffer ) - 1 && * p ) * q ++ = * p ++ ; * q = 0 ; p ++ ; // Sauter le zéro NewEntry. ContextParam = ( DWORD ) strdup ( Buffer ) ; break ; // END_MENU : 1 octet case ENDMENUTYPE - '0' : NewEntry. Id = 0 ; NewEntry. Type = MenuEnd ; NewEntry. ContextParam = 0L ; p ++ ; break ; // DEFINE_CONTROL : 1 seul octet case DEFCONTROLTYPE - '0' : NewEntry. Id = 0 ; NewEntry. Type = ControlStart ; NewEntry. ContextParam = 0L ; p ++ ; break ; // END_CONTROL : 1 seul octet case ENDCONTROLTYPE - '0' : NewEntry. Id = 0 ; NewEntry. Type = ControlEnd ; NewEntry. ContextParam = 0L ; p ++ ; break ; // HELPID : 1 octet, id sur 16 bits, contexte sur 32 case BYIDTYPE - '0' : CHECKBOUND ( p, ResourceEnd, 1 + sizeof ( short int ) + sizeof ( long int ) ) ; p ++ ; NewEntry. Id = * ( ( short int * ) p ) ; p += sizeof ( short int ) ; NewEntry. ContextParam = * ( ( long int * ) p ) ; p += sizeof ( long int ) ; break ; // HELPKEY : 1 octet, id sur 16 bits, chaîne case BYKEYTYPE - '0' : CHECKBOUND ( p, ResourceEnd, 1 + sizeof ( short int ) ) ; p ++ ; NewEntry. Id = * ( ( short int * ) p ) ; p += sizeof ( short int ) ; q = Buffer ; while ( p < ResourceEnd && q < Buffer + sizeof ( Buffer ) - 1 && * p ) * q ++ = * p ++ ; * q = 0 ; p ++ ; // Sauter le zéro NewEntry. ContextParam = ( DWORD ) strdup ( Buffer ) ; break ; // Zéro : c'est la fin de la ressource (normalement...) case 0 : NewEntry. Id = 0 ; NewEntry. Type = EndOfTable ; NewEntry. ContextParam = 0L ; Break = TRUE ; break ; // Autre : y a une douille dans le pâté default : p ++ ; continue ; } // Le type de l'entrée a été déterminé : on l'ajoute à notre table if ( ! EntryCount ) Entries = ( THelpEntry * ) malloc ( REALLOC_INCREMENT * sizeof ( THelpEntry ) ) ; else if ( ! ( ( EntryCount + 1 ) % REALLOC_INCREMENT ) ) Entries = ( THelpEntry * ) realloc ( Entries, ( EntryCount + 1 + REALLOC_INCREMENT ) * sizeof ( THelpEntry ) ) ; if ( Entries == NULL ) throw xmsg ( string ( "Erreur d'allocation mémoire durant la lecture" " d'une ressource HELPTABLE" ) ) ; Entries [ EntryCount ++ ] = NewEntry ; // On est tombé sur le zéro de fin... if ( Break ) break ; } EndOfLoop : UnlockResource ( hGlobal ) ; FreeResource ( hGlobal ) ; // On arrive ici, que la lecture se soit bien passée ou non if ( ! EntryCount ) // Léger problème... return ( -1 ) ; else return ( AddHelp ( appliesto, object, helpfile, Entries ) ) ; }
LRESULT CALLBACK HelpWindowProc ( HWND hwnd, uint message, WPARAM wparam, LPARAM lparam ) { register THelp :: THotkeyType Type ; WNDPROC WindowProc ; HANDLE WndProcProperty ; if ( ! THelp :: TheHelpObject || ! THelp :: TheHelpObject -> HelpTableCount ) throw xmsg ( string ( "HelpWindowProc a été appelée alors qu'il n'y a aucune aide disponible !!!" ) ) ; switch ( message ) { // Messages qui sont peut-être des hotkeys case WM_KEYDOWN : case WM_CHAR : Type = THelp :: TheHelpObject -> IsHotkey ( hwnd, message, wparam, lparam ) ; if ( Type != THelp :: Unknown ) { THelp :: TheHelpObject -> ProcessHelpRequest ( THelp :: WindowHelp, Type, hwnd, message, wparam, lparam ) ; return ( 0L ) ; } break ; // C'est au MENUSELECT qu'on peut récupérer des infos sur l'élément de // menu actuellement sélectionné. // Lorsque LOWORD ( lparam ) == 0xFFFF et HIWORD ( lparam ) est à zéro, // on est sur un menu popup dont le handle est donné par wparam case WM_MENUSELECT : if ( LOWORD ( lparam ) != 0xFFFF && HIWORD ( lparam ) ) { THelp :: TheHelpObject -> LastSelectedMenuType = LOWORD ( lparam ) ; if ( LOWORD ( lparam ) & MF_POPUP ) { THelp :: TheHelpObject -> LastSelectedMenu = 0 ; THelp :: TheHelpObject -> LastSelectedMenuHandle = ( HMENU ) wparam ; } else { THelp :: TheHelpObject -> LastSelectedMenu = wparam ; THelp :: TheHelpObject -> LastSelectedMenuHandle = ( HMENU ) HIWORD ( lparam ) ; } } break ; } // Il s'agit maintenant d'appeler la bonne WindowProc. On récupère l'index de la // première référence à cette fenêtre WndProcProperty = GetProp ( hwnd, WNDPROC_PROPERTY ) ; WindowProc = NULL ; if ( WndProcProperty ) WindowProc = THelp :: TheHelpObject -> HelpTable [ ( int ) WndProcProperty - 1 ]. WindowProc ; if ( WindowProc != NULL ) return ( CallWindowProc ( WindowProc, hwnd, message, wparam, lparam ) ) ; else return ( 0L ) ; }
/* send encrypted packet */ int vpn_send(int fd, vpn_crypt_t *cry, vpn_proto_t type, const void *buf, size_t buflen) { vpn_hdr_t hdr; gcry_cipher_hd_t hd = NULL; char bigpack[VPN_BIGPACKET], encpack[VPN_BIGPACKET], xiv[256], *s; int pad = ~((buflen % cry->blklen) - cry->blklen)+1; int re, rs, rc, rx; switch(type) { case VPN_CLIENT: hd = cry->hsrc; break; case VPN_SERVER: hd = cry->hdst; } /* fill header */ hdr.pad = pad == cry->blklen ? 0 : pad; hdr.checksum = buflen + hdr.pad; /* check buffer size */ if(sizeof(bigpack) < hdr.checksum) return xmsg(-1, VPN_DEBUG|VPN_INFO, "packet too big to send: %d data bytes + %d header bytes\n", buflen, sizeof(hdr)); /* copy data to `bigpack' */ memset(bigpack, 0, sizeof(bigpack)); memcpy(&bigpack, buf, buflen); if(!cry->rndsend) cry->rndsend = initial_iv_random; memset(xiv, 0, sizeof(xiv)); gen_iv(xiv, cry->blklen, cry->rndsend); /* xmsg(0, VPN_DEBUG, "send using iv: %s\n", xiv); */ re = xencrypt(hd, cry->blklen, xiv, encpack, sizeof(encpack), bigpack, hdr.checksum); if(re == -1 || re != hdr.checksum) return xmsg(-1, VPN_DEBUG|VPN_INFO, "vpn_send: cannot encrypt packet (%d != %d)\n", re, hdr.checksum); /* send header */ rs = send(fd, &hdr, sizeof(hdr), 0); if(rs == -1) return rs; else if(!rs) return xmsg(0, VPN_DEBUG|VPN_INFO, "vpn_send: lost connection, peer disconnected\n"); else if(rs != sizeof(hdr)) return xmsg(-1, VPN_DEBUG|VPN_INFO, "vpn_send: partial send of header not allowed\n"); xmsg(0, VPN_DEBUG, "sent %d bytes header, checksum=%d and pad=%d\n", rs, hdr.checksum, hdr.pad); /* send data */ s = encpack; rc = re; rx = 0; do { rs = safe_send(fd, s, rc); if(rs == -1) return rs; else if(!rs) return xmsg(0, VPN_DEBUG|VPN_INFO, "vpn_send: lost connection, peer disconnected\n"); xmsg(0, VPN_DEBUG, "sent %d bytes of packet...\n", rs); s += rs; rx += rs; rc -= rs; } while(rx < re); cry->rndsend = buflen; return buflen; }
void flushline(register struct packet *pkt, register struct stats *stats) { register signed char *p; register unsigned char *u_p; char *xf = (char *) NULL; char ins[6], del[6], unc[6], hash[6]; if (pkt->p_upd == 0) return; putline(pkt,(char *) 0); rewind(Xiop); if (stats) { if (stats->s_ins > MAX_LINES) { stats->s_ins = MAX_LINES; } if (stats->s_del > MAX_LINES) { stats->s_del = MAX_LINES; } if (stats->s_unc > MAX_LINES) { stats->s_unc = MAX_LINES; } sprintf(ins,"%.05d",stats->s_ins); sprintf(del,"%.05d",stats->s_del); sprintf(unc,"%.05d",stats->s_unc); for (p = (signed char*)ins, u_p = (unsigned char *)ins; *p; p++,u_p++){ if(signed_chksum) pkt->p_nhash += (*p - '0'); else pkt->p_nhash += (*u_p - '0'); } for (p = (signed char*)del, u_p = (unsigned char*)del; *p; p++,u_p++) { if(signed_chksum) pkt->p_nhash += (*p - '0'); else pkt->p_nhash += (*u_p - '0'); } for (p = (signed char*)unc, u_p = (unsigned char*)unc; *p; p++, u_p++){ if(signed_chksum) pkt->p_nhash += (*p - '0'); else pkt->p_nhash += (*u_p - '0'); } } sprintf(hash,"%5d",pkt->p_nhash&0xFFFF); for (p=(signed char*)hash; *p == ' '; p++) /* replace initial blanks with '0's */ *p = '0'; fprintf(Xiop,"%c%c%s\n",CTLCHAR,HEAD,hash); if (stats) fprintf(Xiop,"%c%c %s/%s/%s\n",CTLCHAR,STATS,ins,del,unc); if (fflush(Xiop) == EOF) xmsg(xf, NOGETTEXT("flushline")); #ifdef USE_FSYNC /* * Lots of paranoia here, to try to catch * delayed failure information from NFS. */ if (fsync(fileno(Xiop)) < 0) xmsg(xf, NOGETTEXT("flushline")); #endif if (fclose(Xiop) == EOF) xmsg(xf, NOGETTEXT("flushline")); Xiop = NULL; }