repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
isshe/code-library | B.Operating-System/Linux/Application/C.Test/test_isshe_crypto.c | #include <stdio.h>
#include <string.h>
#include "isshe_aes_cfg128.h"
void test_aes_cfb128()
{
unsigned char ckey[] = "helloworldkey";
unsigned char ivec[] = "goodbyworldkey";
unsigned char ivec_cp[ISSHE_AES_BLOCK_SIZE];
int bytes_read;
unsigned char indata[ISSHE_AES_BLOCK_SIZE * 2];
//unsigned char outdata[ISSHE_AES_BLOCK_SIZE];
//unsigned char decryptdata[ISSHE_AES_BLOCK_SIZE];
isshe_aes_key_t key;
//isshe_aes_key_t dkey;
memcpy(ivec_cp , ivec, ISSHE_AES_BLOCK_SIZE);
isshe_aes_set_encrypt_key(ckey, 128, &key);
//isshe_aes_set_decrypt_key(ckey, 128, &dkey);
int num = 0;
strcpy((char*)indata , "0123456789abcdef0123456789abcde");
bytes_read = sizeof(indata);
//isshe_aes_encrypt(indata, outdata, &key);
printf("num = %d, ivec = %s\n", num, ivec);
printf("src: %s\n", indata);
isshe_aes_cfb128_encrypt(indata, indata, bytes_read, &key, ivec, &num, ISSHE_AES_ENCRYPT);
printf("num = %d, ivec = %s\n", num, ivec);
printf("encrypt: %s\n", indata);
num = 0;
//isshe_aes_decrypt(outdata, decryptdata, &dkey);
printf("num = %d, ivec = %s\n", num, ivec_cp);
isshe_aes_cfb128_encrypt(indata, indata, bytes_read, &key, ivec_cp, &num, ISSHE_AES_DECRYPT);
printf("num = %d, ivec = %s\n", num, ivec_cp);
printf("decrypt: %s\n", indata);
}
int main()
{
test_aes_cfb128();
} |
isshe/code-library | K.Tools/wantype/common.h |
#ifndef _COMMON_H_
#define _COMMON_H_
#include <stdint.h>
#include <sys/time.h>
#define ETH_10MB 1
#define SEC2USEC 1000000
#define DEFAULT_TIMEOUT 3
enum wantype {
WANTYPE_UNKNOWN = 0,
WANTYPE_DHCP = 1,
WANTYPE_PPPOE = 1 << 1,
};
struct wantype_config {
char ifname[64];
struct timeval timeout;
int show_config;
};
void hwaddr_get(int sockfd, const char *ifname, char *res_hwaddr);
uint16_t checksum(void *addr, int count);
uint32_t random_xid(void);
#endif |
isshe/code-library | K.Tools/issheSocks/src/base/iuser/iuser.h | #ifndef _ISSHE_IUSER_H_
#define _ISSHE_IUSER_H_
#include <stdint.h>
#define IUSER_NAME_PWD_MAX_LEN 32
typedef struct {
// 测试使用明文,后面加密后保存
uint8_t username[IUSER_NAME_PWD_MAX_LEN]; // aes(md5(username))
uint8_t userpwd[IUSER_NAME_PWD_MAX_LEN]; // aes(md5(userpwd))
}iuser_s;
#endif |
isshe/code-library | K.Tools/issheSocks/src/roles/isocks/isocks.c |
#include "isocks.h" |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_time.c | #include <sys/time.h>
#include <string.h>
#include <stdio.h>
#ifdef __linux__
#include <time.h>
#endif
#include "isshe_time.h"
#include "isshe_error.h"
#include "isshe_common.h"
int isshe_gettimeofday(struct timeval *tv, struct timezone *tz)
{
int rc;
if ((rc = gettimeofday(tv, tz)) < ISSHE_SUCCESS) {
isshe_sys_error_exit("gettimeofday error");
}
return rc;
}
char *isshe_gf_time(void)
{
struct timeval tv;
static char str[30];
char *ptr;
isshe_gettimeofday(&tv, NULL);
ptr = ctime(&tv.tv_sec);
strcpy(str, &ptr[11]);
/* Fri Sep 13 00:00:00 1986\n\0 */
/* 0123456789012345678901234 5 */
snprintf(str+8, sizeof(str)-8, ".%06ld", (long)tv.tv_usec);
return(str);
} |
isshe/code-library | B.Operating-System/Linux/Application/C.Test/test_isshe_error.c | #include <stdio.h>
#include <errno.h>
#include "isshe_error.h"
int main(void)
{
isshe_error("isshe_error...");
return 0;
} |
isshe/code-library | J.Dynamic-Tracing/Linux-Observability-with-BPF/3.BPF-Map/map-iterate/main.c | #include <linux/bpf.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "bpf/bpf.h"
int main(int argc, char **argv)
{
int fd, result, key, value, it;
fd = bpf_create_map(BPF_MAP_TYPE_HASH, sizeof(key),
sizeof(value), 256, 0);
if (fd < 0) {
printf("failed to create map '%s'\n", strerror(errno));
return 1;
}
for( it = 1; it < 6; it++ ){
key = it;
value = it + 1234;
bpf_map_update_elem(fd, &key, &value, BPF_NOEXIST);
}
int next_key, lookup_key;
lookup_key = -1;
while ( bpf_map_get_next_key( fd, &lookup_key, &next_key) == 0)
{
printf("The next key in the map is: '%d'\n", next_key);
lookup_key = next_key;
}
lookup_key = -1;
printf("\nDelete key test\n");
while ( bpf_map_get_next_key( fd, &lookup_key, &next_key) == 0)
{
printf("The next key in the map is: '%d'\n", next_key);
if (next_key == 2)
{
printf("Deleting key '2'\n");
bpf_map_delete_elem(fd, &next_key);
}
lookup_key = next_key;
}
return 0;
}
|
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_encode.h | <filename>K.Tools/issheSocks/src/protocol/isout/isout_encode.h
#ifndef _ISSHE_ISOUT_ENCODE_H_
#define _ISSHE_ISOUT_ENCODE_H_
#include <stdint.h>
//#include <event2/bufferevent.h>
//#include <event2/buffer.h>
#include "iuser.h"
#include "isession.h"
#define ISOUT_HEADER_MIN_LEN 32
int isout_encode_hmac(uint8_t *data, int len, uint8_t *result);
int isout_encode_opts(uint8_t *data, int len);
int isout_encode_data(uint8_t *data, int len);
int isout_encode(isession_s *session);
#endif |
isshe/code-library | K.Tools/wantype/dhcp.c | <filename>K.Tools/wantype/dhcp.c
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h> /* the L2 protocols */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <net/if.h> // for if_nametoindex
#include "dhcp.h"
void init_dhcp_header(struct dhcphdr *hdr)
{
memset(hdr, 0, sizeof(struct dhcphdr));
hdr->opcode = BOOTREQUEST;
hdr->hw_type = ETH_10MB;
hdr->hw_addr_len = ETH_ALEN;
hdr->cookie = htonl(DHCP_MAGIC);
hdr->options[0] = DHCP_OPTION_END;
}
int end_option_pos(uint8_t *options)
{
int i = 0;
while (options[i] != DHCP_OPTION_END) {
if (options[i] == DHCP_OPTION_PADDING) {
i++;
} else {
i += options[i + OPTION_LEN] + 2; // 2: CODE + LENGTH
}
}
return i;
}
void add_dhcp_option(struct dhcphdr *hdr, uint8_t code, uint8_t len, uint8_t *data)
{
int end_pos = end_option_pos(hdr->options);
hdr->options[end_pos++] = code;
hdr->options[end_pos++] = len;
memcpy(hdr->options + end_pos, data, len);
end_pos += len;
hdr->options[end_pos] = DHCP_OPTION_END;
}
void add_dhcp_option_u8(struct dhcphdr *hdr, uint8_t code, uint8_t data)
{
add_dhcp_option(hdr, code, 1, &data);
}
void add_dhcp_option_u16(struct dhcphdr *hdr, uint8_t code, uint16_t data)
{
add_dhcp_option(hdr, code, 2, (uint8_t *)&data);
}
void add_dhcp_option_u32(struct dhcphdr *hdr, uint8_t code, uint32_t data)
{
add_dhcp_option(hdr, code, 4, (uint8_t *)&data);
}
int send_dhcp_discovery(int sockfd, struct wantype_config *cfg)
{
const int on = 1;
struct sockaddr_in myaddr;
struct sockaddr_in servaddr;
uint8_t buff[16];
int len = 0;
struct dhcpopt opt;
struct dhcp_packet packet;
struct sockaddr_ll dest;
// dhcp
init_dhcp_header(&packet.dhcp);
packet.dhcp.tid = random_xid();
packet.dhcp.secs = htons(100);
hwaddr_get(sockfd, cfg->ifname, packet.dhcp.chw_addr);
add_dhcp_option_u8(&packet.dhcp, DHCP_OPTION_MESSAGE_TYPE, DHCP_DISCOVER);
add_dhcp_option(&packet.dhcp, DHCP_OPTION_HOST_NAME, sizeof(HOST_NAME), HOST_NAME);
add_dhcp_option_u16(&packet.dhcp, DHCP_OPTION_MAX_SIZE, htons(576));
buff[len++] = ETH_10MB; // ethernet
memcpy(buff + len, packet.dhcp.chw_addr, ETH_ALEN);
len += ETH_ALEN;
add_dhcp_option(&packet.dhcp, DHCP_OPTION_CLIENT_ID, len, buff);
// udp && ip
packet.ip.protocol = IPPROTO_UDP;
packet.ip.saddr = INADDR_ANY;
packet.ip.daddr = INADDR_BROADCAST;
packet.udp.source = htons(CLIENT_PORT);
packet.udp.dest = htons(SERVER_PORT);
packet.udp.len = htons(sizeof(struct udphdr) + sizeof(struct dhcphdr));
packet.ip.tot_len = packet.udp.len;
packet.udp.check = checksum(&packet, sizeof(struct dhcp_packet));
packet.ip.tot_len = htons(sizeof(struct dhcp_packet));
packet.ip.ihl = sizeof(packet.ip) >> 2;
packet.ip.version = IPVERSION;
packet.ip.ttl = IPDEFTTL;
packet.ip.check = checksum(&(packet.ip), sizeof(packet.ip));
dest.sll_family = AF_PACKET;
dest.sll_protocol = htons(ETH_P_IP);
dest.sll_ifindex = if_nametoindex(cfg->ifname);
dest.sll_halen = ETH_ALEN;
memset(dest.sll_addr, 0xff, sizeof(dest.sll_addr));
if (sendto(sockfd, &packet, sizeof(struct dhcp_packet), 0, (struct sockaddr *) &dest, sizeof(dest)) < 0) {
printf("sendto error: %s\n", strerror(errno));
exit(1);
}
return 0;
}
int is_dhcp_packet(int sockfd)
{
struct dhcp_packet packet;
struct sockaddr_ll dest;
socklen_t len;
if (recvfrom(sockfd, &packet, sizeof(struct dhcp_packet), 0, (struct sockaddr *) &dest, &len) < 0) {
printf("recvfrom error: %s\n", strerror(errno));
exit(1);
}
if (ntohs(packet.udp.source) == SERVER_PORT && ntohs(packet.udp.dest) == CLIENT_PORT) {
return 1;
}
return 0;
} |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_socket.c | #include "isshe_common.h"
#include "isshe_error.h"
#include "isshe_socket.h"
int isshe_socket(int domain, int type, int protocol)
{
int rc;
if ((rc = socket(domain, type, protocol)) < 0) {
isshe_sys_error_exit("socket error");
}
return rc;
}
int isshe_setsockopt(int s, int level, int optname, const void *optval, int optlen)
{
int rc;
if ((rc = setsockopt(s, level, optname, optval, optlen)) < 0) {
isshe_sys_error_exit("setsockopt error");
}
return rc;
}
int isshe_bind(int sockfd, struct sockaddr *my_addr, int addrlen)
{
int rc;
if ((rc = bind(sockfd, my_addr, addrlen)) < 0) {
isshe_sys_error_exit("bind error");
}
return rc;
}
int isshe_listen(int s, int backlog)
{
int rc;
if ((rc = listen(s, backlog)) < 0) {
isshe_sys_error_exit("listen error");
}
return rc;
}
int isshe_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
int rc;
if ((rc = accept(s, addr, addrlen)) < 0) {
isshe_sys_error_exit("accept error");
}
return rc;
}
int isshe_connect(int sockfd, struct sockaddr *serv_addr, int addrlen)
{
int rc;
if ((rc = connect(sockfd, serv_addr, addrlen)) < 0) {
isshe_sys_error_exit("connect error");
}
return rc;
}
/*
* 协议无关包裹函数
*/
int isshe_getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res)
{
int rc;
if ((rc = getaddrinfo(node, service, hints, res)) != 0) {
isshe_gai_error_exit(rc, "getaddrinfo error");
}
return rc;
}
int isshe_getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host,
size_t hostlen, char *serv, size_t servlen, int flags)
{
int rc;
if ((rc = getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)) != 0) {
isshe_gai_error_exit(rc, "getnameinfo error");
}
return rc;
}
void isshe_freeaddrinfo(struct addrinfo *res)
{
freeaddrinfo(res);
}
const char * isshe_inet_ntop(int af, const void *src, char *dst, socklen_t size)
{
const char *res;
if ((res = inet_ntop(af, src, dst, size)) == NULL) {
isshe_sys_error_exit("inet_ntop error");
}
return res;
}
int isshe_inet_pton(int af, const char *src, void *dst)
{
int rc;
rc = inet_pton(af, src, dst);
if (rc == 0) {
isshe_app_error_exit("inet_pton error: invalid dotted-decimal address");
}
else if (rc < 0) {
isshe_sys_error_exit("inet_pton error");
}
return rc;
}
/*
* 一些方便使用的包裹函数
*/
int open_client_fd(char *hostname, char *port)
{
int clientfd, rc;
struct addrinfo hints, *listp, *p;
/* 获取潜在服务器地址列表 */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* Open a connection */
hints.ai_flags = AI_NUMERICSERV; /* 数字化的地址/端口字符串,不能是域名 */
hints.ai_flags |= AI_ADDRCONFIG; /* 仅当本地系统配置了IPv4/IPv6地址,listp才返回IPv4/IPv6地址 */
if ((rc = getaddrinfo(hostname, port, &hints, &listp)) != 0) {
fprintf(stderr, "getaddrinfo failed (%s:%s): %s\n", hostname, port, gai_strerror(rc));
return -2;
}
/* 遍历列表,找一个可以成功连接上的服务器 */
for (p = listp; p; p = p->ai_next) {
/* Create a socket descriptor */
if ((clientfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
continue; /* Socket failed, try the next */
/* Connect to the server */
if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1) {
break; /* Success */
}
if (close(clientfd) < 0) { /* Connect failed, try another */ //line:netp:openclientfd:closefd
fprintf(stderr, "open_client_fd: close failed: %s\n", strerror(errno));
return -1;
}
}
/* Clean up */
freeaddrinfo(listp);
if (!p) { /* All connects failed */
return -1;
}
/* The last connect succeeded */
return clientfd;
}
int open_listen_fd(char *port)
{
struct addrinfo hints, *listp, *p;
int listenfd, rc, optval=1;
/* 获取潜在服务器地址列表 */
/* AI_PASSIVE: 如果getaddrinfo第一个参数为NULL,则返回可以用于bind和accept的地址 */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* 流套接字:TCP... */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
hints.ai_flags |= AI_NUMERICSERV; /* 数字化的地址/端口字符串,不能是域名 */
if ((rc = getaddrinfo(NULL, port, &hints, &listp)) != 0) {
fprintf(stderr, "getaddrinfo failed (port %s): %s\n", port, gai_strerror(rc));
return -2;
}
/* 遍历列表,绑定一个可以绑定的 */
for (p = listp; p; p = p->ai_next) {
/* Create a socket descriptor */
if ((listenfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
continue; /* Socket failed, try the next */
}
/* 消除bind的"Address already in use"错误 */
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, //line:netp:csapp:setsockopt
(const void *)&optval , sizeof(int));
/* Bind the descriptor to the address */
if (bind(listenfd, p->ai_addr, p->ai_addrlen) == 0)
break; /* Success */
if (close(listenfd) < 0) { /* Bind failed, try the next */
fprintf(stderr, "open_listen_fd close failed: %s\n", strerror(errno));
return -1;
}
}
/* Clean up */
freeaddrinfo(listp);
if (!p) { /* No address worked */
return -1;
}
/* Make it a listening socket ready to accept connection requests */
if (listen(listenfd, LISTENQ) < 0) {
close(listenfd);
return -1;
}
return listenfd;
}
int isshe_open_client_fd(char *hostname, char *port)
{
int rc;
if ((rc = open_client_fd(hostname, port)) < 0) {
isshe_sys_error_exit("open_client_fd error");
}
return rc;
}
int isshe_open_listen_fd(char *port)
{
int rc;
if ((rc = open_listen_fd(port)) < 0) {
isshe_sys_error_exit("open_listen_fd error");
}
return rc;
}
ssize_t isshe_sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen)
{
ssize_t rc;
if ((rc = sendto(sockfd, buf, len, flags, dest_addr, addrlen)) < 0) {
isshe_sys_error_exit("sendto error");
}
return rc;
}
ssize_t isshe_recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen)
{
ssize_t rc;
if ((rc = recvfrom(sockfd, buf, len, flags, src_addr, addrlen)) < 0) {
isshe_sys_error_exit("recvfrom error");
}
return rc;
}
|
isshe/code-library | K.Tools/wantype/common.c | <filename>K.Tools/wantype/common.c
#include "common.h"
#include <stdint.h>
#include <time.h> // time()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> // open
#include <sys/ioctl.h>
#include <string.h>
#include <stdio.h>
#include <net/if.h> // if_nametoindex()、ifreq
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_ether.h> // ETH_ALEN
void hwaddr_get(int sockfd, const char *ifname, char *res_hwaddr)
{
struct ifreq ifr;
int len;
memset(&ifr, 0, sizeof(struct ifreq));
len = strlen(ifname) > sizeof(ifr.ifr_name) - 1 ? sizeof(ifr.ifr_name) - 1 : strlen(ifname);
memcpy(ifr.ifr_name, ifname, len);
if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) < 0) {
printf("ioctl error: %s\n", strerror(errno));
exit(1);
}
memcpy(res_hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
}
uint16_t checksum(void *addr, int count)
{
/* Compute Internet Checksum for "count" bytes
* beginning at location "addr".
*/
register int32_t sum = 0;
uint16_t *source = (uint16_t *) addr;
while (count > 1) {
/* This is the inner loop */
sum += *source++;
count -= 2;
}
/* Add left-over byte, if any */
if (count > 0) {
/* Make sure that the left-over byte is added correctly both
* with little and big endian hosts */
uint16_t tmp = 0;
*(unsigned char *) (&tmp) = * (unsigned char *) source;
sum += tmp;
}
/* Fold 32-bit sum to 16 bits */
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return ~sum;
}
/* Create a random xid */
uint32_t random_xid(void)
{
static int initialized;
if (!initialized) {
int fd;
uint32_t seed;
fd = open("/dev/urandom", 0);
if (fd < 0 || read(fd, &seed, sizeof(seed)) < 0) {
printf("Could not load seed from /dev/urandom: %s", strerror(errno));
seed = time(0);
}
if (fd >= 0) close(fd);
srand(seed);
initialized++;
}
return (uint32_t)rand();
}
|
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_protocol.h | #ifndef _ISSHE_SOCKS_PROTOCOL_H_
#define _ISSHE_SOCKS_PROTOCOL_H_
// 标准
#include <stdint.h>
// 第三方
#include <event2/event.h>
#include <event2/listener.h>
#define ISSHE_SOCKS_FLAG_TO_USER 1
#define ISSHE_SOCKS_FLAG_FROM_USER 2
#define ISSHE_SOCKS_FLAG_CONFIG 4
#define ISSHE_SOCKS_OPT_MAX_LEN 1024
/*
+----------+---------+---------+
| 消息验证码 | 协议选项 | 加密数据 |
+----------+---------+---------+
* 消息验证码:128位/16字节,根据程序ID、时间等生成;防篡改,程序认证。
* 协议选项:类似DHCP选项的形式。通过某个加密算法加密。
* 加密数据:对用户数据进行加密
*/
enum isshe_socks_opt_type
{
ISSHE_SOCKS_OPT_MAC = 0, // Message Authentication Code
ISSHE_SOCKS_OPT_VERSION,
ISSHE_SOCKS_OPT_PROTOCOL, // TCP/UDP
ISSHE_SOCKS_OPT_DOMAIN,
ISSHE_SOCKS_OPT_IPV4,
ISSHE_SOCKS_OPT_IPV6,
ISSHE_SOCKS_OPT_PORT,
ISSHE_SOCKS_OPT_CRYPTO, // 指定数据部分加密算法,没有指定就按配置文件的来
ISSHE_SOCKS_OPT_CRYPTO_KEY,
ISSHE_SOCKS_OPT_CRYPTO_IVEC,
ISSHE_SOCKS_OPT_USER, // 用户名,可以用于流量统计等
ISSHE_SOCKS_OPT_USER_DATA_LEN,
ISSHE_SOCKS_OPT_END = 255,
};
enum isshe_socks_connection_status
{
ISSHE_SCS_CLOSED = 0,
ISSHE_SCS_ESTABLISHED = 1,
};
struct isshe_socks_opt
{
uint8_t type;
uint8_t len;
uint8_t data[0];
};
// TODO 再考虑一下
/*
* isshe_socks_header: 请求/应答,对称协议使用
* isshe_socks_request: 请求,非对称协议使用
* isshe_socks_reply: 应答,非对称协议使用
*/
struct isshe_socks_header
{
uint8_t mac[16];
struct isshe_socks_opt opts[0];
//uint8_t version;
//uint8_t addr_type;
//uint8_t addr_len; // bytes
//uint8_t addr;
};
struct isshe_socks_request
{
// 请求
// uint8_t mac[16];
};
struct isshe_socks_reply
{
// 应答
// uint8_t mac[16];
// isshe_socks_opt opts[0];
};
struct isshe_socks_opts
{
uint8_t addr_type; // 初始化为0, ISSHE_SOCKS_ADDR_TYPE_DOMAIN
uint32_t ipv4; // 初始化为0
uint16_t port; // 初始化为0
uint8_t dname_len; // 初始化为0
uint8_t ipv6_len; // 初始化为0
uint8_t *dname; // domain name
uint8_t *ipv6; // 初始化为NULL
uint32_t user_data_len; // 用户数据长度
};
struct isshe_socks_connection
{
uint8_t status;
int fd;
struct bufferevent *bev;
struct addrinfo *target_ai;
struct isshe_socks_opts *opts;
};
/*
struct isshe_socks_connection
{
uint8_t status;
int fd_from_user;
int fd_to_user;
struct addrinfo *target_ai;
struct isshe_socks_opts *opts;
struct bufferevent *bev_from_user; // 出去的流量(用户角度)
struct bufferevent *bev_to_user; // 进来的流量(用户角度)
};
*/
void isshe_socks_opt_init(uint8_t *buf);
void isshe_socks_opt_add(uint8_t *buf,
uint8_t type, uint8_t len, const void *data);
int isshe_socks_opt_len(uint8_t *buf);
void isshe_socks_opt_parse(uint8_t *buf, int buflen,
struct isshe_socks_opts *opts);
struct isshe_socks_connection *isshe_socks_connection_new();
void isshe_socks_connection_free(
struct isshe_socks_connection *isc);
struct bufferevent *isshe_socks_connect_to_next(
struct event_base *evbase,
struct sockaddr *ai_addr,
socklen_t ai_addrlen,
uint16_t port);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/crypto/isshe_md5.h | #ifndef _ISSHE_MD5_H_
#define _ISSHE_MD5_H_
#include <stdint.h>
typedef struct {
uint64_t bytes;
uint32_t a, b, c, d;
uint8_t buffer[64];
} isshe_md5_s;
void isshe_md5_init(isshe_md5_s *ctx);
void isshe_md5_update(isshe_md5_s *ctx, const void *data, uint64_t size);
void isshe_md5_final(isshe_md5_s *ctx, uint8_t result[16]);
int isshe_md5(uint8_t *data, uint32_t len, uint8_t result[16]);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/C.Test/test_isshe_hmac.c | #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "isshe_hmac.h"
void print_hex_buf(uint8_t *buf, int num)
{
int i;
for (i = 0; i < num; i++) {
printf("%02X ", buf[i]);
}
printf("\n");
}
int main(void)
{
uint8_t result[1024];
uint8_t data[1024] = "123";
uint32_t data_len = 3;
uint8_t key[1024] = "abc";
uint32_t key_len = 3;
uint32_t res_len = 16;
printf("data = %u:%s\n", data_len, data);
isshe_hmac_md5(data, data_len, key, key_len, result);
printf("result = %s\n", result);
print_hex_buf(result, res_len);
res_len = 32;
printf("data = %u:%s\n", data_len, data);
isshe_hmac_sha256(data, data_len, key, key_len, result);
printf("result = %s\n", result);
print_hex_buf(result, res_len);
}
|
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_process.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/errno.h>
#include <string.h>
#include <sys/wait.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#ifdef __linux__
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include "isshe_process.h"
#include "isshe_error.h"
#include "isshe_common.h"
#include "isshe_signal.h"
extern int daemon_proc; // defined in isshe_error.c
pid_t isshe_fork(void)
{
pid_t pid;
if ((pid = fork()) < 0) {
isshe_sys_error_exit("Fork error");
}
return pid;
}
void isshe_print_exit_status(int status)
{
if (WIFEXITED(status)) {
printf("normal termination, exit status = %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("abnormal termination, signal number = %d%s\n", WTERMSIG(status),
#ifdef WCOREDUMP
WCOREDUMP(status) ? "(core file generated)" : "");
#else
"");
#endif
} else if (WIFSTOPPED(status)) {
printf("child stopped, signal number = %d\n", WSTOPSIG(status));
}
}
void isshe_daemonize(const char *pname, int facility)
{
int i, fd0, fd1, fd2;
pid_t pid;
struct rlimit rl;
// 清除文件模式创建屏蔽字
umask(0);
// 获取最大文件描述符
if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
printf("%s: can't get file limit\n", pname);
exit(0);
}
// 成为会话leader,没有控制终端
pid = isshe_fork();
if (pid < 0) {
printf("fork failed\n");
exit(0);
} else if (pid != 0) {
exit(0); // 终止父进程
}
setsid();
// 确保之后的open不会分配控制终端
isshe_signal(SIGHUP, SIG_IGN);
pid = isshe_fork();
if (pid != 0) {
exit(0); // 终止第一个子进程
}
daemon_proc = 1; /* for our err_XXX() functions */
// 改工作目录
if (chdir("/") < 0) {
printf("%s: can't change directory to /", pname);
exit(0);
}
// close all open file descriptors
if (rl.rlim_max == RLIM_INFINITY) {
rl.rlim_max = 1024;
}
for (i = 0; i < rl.rlim_max; i++) {
close(i);
}
// 把0、1、2整到/dev/null
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
// 初始化log文件
openlog(pname, LOG_PID, LOG_DAEMON);
if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
syslog(LOG_ERR, "unexpected file descriptors %d %d %d\n", fd0, fd1, fd2);
exit(1);
}
}
pid_t isshe_waitpid(pid_t pid, int *iptr, int options)
{
pid_t ret_pid;
if ( (ret_pid = waitpid(pid, iptr, options)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("waitpid error");
}
return ret_pid;
}
|
isshe/code-library | K.Tools/issheSocks/src/isshe_proxy_server.h | <gh_stars>1-10
#ifndef _ISSHE_PROXY_SERVER_H_
#define _ISSHE_PROXY_SERVER_H_
// 标准
#include <stdint.h>
// 第三方
#include <event2/event.h>
#include <event2/listener.h>
// 自定义
#include "isshe_config_parser.h"
#include "isshe_socks_protocol.h"
struct isshe_proxy_server
{
struct event_base *evbase;
struct evconnlistener *evlistener;
struct isshe_socks_config *config;
};
struct isshe_proxy_server_connection
{
uint64_t flag;
//struct isshe_socks_connection *isc;
struct isshe_socks_connection *to_user_conn;
struct isshe_socks_connection *from_user_conn;
struct isshe_proxy_server *ps;
};
void proxy_server_accept_cb(
struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sa, int socklen, void *user_data);
void proxy_server_from_user_event_cb(
struct bufferevent *bev, short what, void *ctx);
void proxy_server_from_user_read_cb(
struct bufferevent *bev, void *ctx);
void proxy_server_to_user_event_cb(
struct bufferevent *bev, short what, void *ctx);
void proxy_server_to_user_read_cb(
struct bufferevent *bev, void *ctx);
#endif |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_connection.h | <filename>K.Tools/issheSocks/src/protocol/isout/isout_connection.h
#ifndef _ISSHE_ISOUT_CONNECTION_H_
#define _ISSHE_ISOUT_CONNECTION_H_
#include <stdint.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include "isout_protocol.h"
#define ISOUT_OPTS_FLAG_DNAME (1 << 0)
#define ISOUT_OPTS_FLAG_IPV4 (1 << 1)
#define ISOUT_OPTS_FLAG_IPV6 (1 << 2)
#define ISOUT_OPTS_FLAG_ADDR_TYPE (1 << 3)
#define ISOUT_OPTS_FLAG_PORT (1 << 4)
typedef struct
{
uint64_t count; // 计数器,初始化为0
uint32_t random; // 随机数, 初始化为0
uint8_t *dname; // domain name
uint8_t *ipv6; // 初始化为NULL
uint32_t ipv4; // 初始化为0
uint16_t port; // 初始化为0
uint8_t addr_type; // 初始化为0, ISSHE_SOCKS_ADDR_TYPE_DOMAIN
uint8_t dname_len; // 初始化为0
uint8_t ipv6_len; // 初始化为0
uint16_t user_data_len; // 用户数据长度
}isout_conn_opts_s;
typedef struct
{
int fd;
int status;
struct bufferevent *bev;
struct addrinfo *target_ai;
uint64_t opts_flag;
isout_conn_opts_s opts;
}isout_connection_s;
int isout_opts_parse(isout_conn_opts_s *opts, uint8_t *opts_str);
#endif |
isshe/code-library | B.Operating-System/Linux/Kernel/Examples/1.Hello/hello.c | <gh_stars>1-10
#include "linux/init.h"
#include "linux/module.h"
static int hello_init(void)
{
printk(KERN_ALERT "Hello World linux_driver_module\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "Goodbey linux_driver_module\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("lpj");
|
isshe/code-library | K.Tools/issheSocks/src/base/isession/isession.h | <filename>K.Tools/issheSocks/src/base/isession/isession.h
#include <stdint.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
//#include "iconfig.h"
//#include "iuser.h"
typedef struct
{
void *in;
void *out;
void *config;
uint64_t flag;
struct event_base *evbase;
struct evconnlistener *evlistener;
}isession_s; |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_rio.h |
#ifndef _ISSHE_RIO_H_
#define _ISSHE_RIO_H_
#define RIO_BUFSIZE 8192
typedef struct {
int rio_fd; /* Descriptor for this internal buf */
int rio_cnt; /* Unread bytes in internal buf */
char *rio_bufptr; /* Next unread byte in internal buf */
char rio_buf[RIO_BUFSIZE]; /* Internal buffer */
} rio_t;
/****************************************
* 健壮I/O函数:标准I/O的包装函数
****************************************/
ssize_t rio_readn(int fd, void *usrbuf, size_t n);
ssize_t rio_writen(int fd, void *usrbuf, size_t n);
void rio_readinitb(rio_t *rp, int fd);
ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n);
ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen);
/****************************************
* 健壮I/O的包装函数
****************************************/
ssize_t isshe_rio_readn(int fd, void *ptr, size_t nbytes);
void isshe_rio_writen(int fd, void *usrbuf, size_t n);
void isshe_rio_readinitb(rio_t *rp, int fd);
ssize_t isshe_rio_readnb(rio_t *rp, void *usrbuf, size_t n);
ssize_t isshe_rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/crypto/isshe_sha2.h | #ifndef _ISSHE_SHA2_H_
#define _ISSHE_SHA2_H_
#pragma once
#include <stdint.h>
#include <stdio.h>
#define ISSHE_SHA256_LBLOCK 16
// SHA-256 treats input data as a contiguous
// array of 32 bit wide big-endian values.
#define ISSHE_SHA256_CBLOCK 64
#define ISSHE_SHA256_DIGEST_LENGTH 32
typedef struct {
uint32_t state[8];
uint32_t Nl, Nh;
uint32_t data[ISSHE_SHA256_LBLOCK];
uint32_t num;
} isshe_sha256_state_s;
int isshe_sha256_init(isshe_sha256_state_s *state);
int isshe_sha256_update(isshe_sha256_state_s *state, const uint8_t *data, uint64_t len);
void isshe_sha256_transform(isshe_sha256_state_s *state, const uint8_t *data);
int isshe_sha256_final(isshe_sha256_state_s *state, uint8_t result[32]);
int isshe_sha256(const uint8_t *data, uint64_t len, uint8_t result[32]);
#endif
|
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_stdio.h | #ifndef _ISSHE_STDIO_H_
#define _ISSHE_STDIO_H_
char *isshe_fgets(char *ptr, int n, FILE *stream);
void isshe_fputs(const char *ptr, FILE *stream);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/C.Test/test_isshe_rand.c | <reponame>isshe/code-library<filename>B.Operating-System/Linux/Application/C.Test/test_isshe_rand.c<gh_stars>1-10
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "isshe_rand.h"
void print_hex_buf(uint8_t *buf, int num)
{
int i;
for (i = 0; i < num; i++) {
printf("%02X ", buf[i]);
}
printf("\n");
}
int main(void)
{
char buf[16];
print_hex_buf((uint8_t *)buf, sizeof(buf));
isshe_rand_bytes((unsigned char *)buf, sizeof(buf));
printf("buf = %s\n", buf);
print_hex_buf((uint8_t *)buf, sizeof(buf));
}
|
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_time.h | #ifndef _ISSHE_TIME_H_
#define _ISSHE_TIME_H_
int isshe_gettimeofday(struct timeval *tv, struct timezone *tz);
char * isshe_gf_time(void);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/crypto/isshe_rand.c | #include <stdio.h>
#include "isshe_rand.h"
int isshe_rand_bytes_dev_urandom(unsigned char *buf, int num)
{
int res;
FILE *fp = fopen(ISSHE_DEV_URANDOM, "rb");
if (!fp) {
return -1;
}
res = fread(buf, 1, num, fp);
fclose(fp);
if (res != num) {
return -1;
}
return res;
}
int isshe_rand_bytes(unsigned char *buf, int num)
{
return isshe_rand_bytes_dev_urandom(buf, num);
} |
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_protocol.c | #include <stdint.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include "isshe_socks_protocol.h"
#include "isshe_socks_common.h"
void isshe_socks_opt_add_end(uint8_t *buf)
{
struct isshe_socks_opt opt;
opt.type = ISSHE_SOCKS_OPT_END;
opt.len = 0;
memcpy(buf, &opt, sizeof(opt.type) + sizeof(opt.len));
}
void isshe_socks_opt_init(uint8_t *buf)
{
isshe_socks_opt_add_end(buf);
}
// TODO 不够健壮,只考虑了正常已初始化的情况
int isshe_socks_opt_find(uint8_t *buf, uint8_t type)
{
int i;
struct isshe_socks_opt *opt;
i = 0;
while(i < ISSHE_SOCKS_OPT_MAX_LEN) {
opt = (struct isshe_socks_opt *)(buf + i);
if (opt->type == type) {
return i;
} else if (opt->type == ISSHE_SOCKS_OPT_END) {
return FAILURE;
}
i += opt->len + sizeof(opt->len) + sizeof(opt->type);
}
}
int isshe_socks_opt_find_end(uint8_t *buf)
{
return isshe_socks_opt_find(buf, ISSHE_SOCKS_OPT_END);
}
int isshe_socks_opt_len(uint8_t *buf)
{
return isshe_socks_opt_find_end(buf) + 2; // type + len;
}
void isshe_socks_opt_add(uint8_t *buf, uint8_t type, uint8_t len, const void *data)
{
int end_pos = isshe_socks_opt_find_end(buf);
if (end_pos == FAILURE) {
printf("find end error!!!\n");
return ;
}
buf += end_pos;
memcpy(buf, &type, sizeof(type));
buf += sizeof(type);
memcpy(buf, &len, sizeof(len));
buf += sizeof(len);
if (len && data) {
memcpy(buf, data, len);
buf += len;
}
isshe_socks_opt_add_end(buf);
}
void isshe_socks_opt_parse(uint8_t *buf, int buflen, struct isshe_socks_opts *opts)
{
if (!buf) {
printf("ERROR: buf is NULL!!!\n");
return ;
}
int i = 0;
uint8_t cur_type;
uint8_t cur_len;
uint8_t *cur_data;
uint8_t end = FALSE;
while(!end && i < buflen) {
cur_type = buf[i];
cur_len = buf[i + sizeof(cur_type)];
cur_data = buf + i + sizeof(cur_len) + sizeof(cur_type);
switch (cur_type)
{
case ISSHE_SOCKS_OPT_DOMAIN:
opts->dname_len = cur_len;
opts->dname = (uint8_t *)malloc(opts->dname_len + 1); // TODO: 释放 && 健壮化
memcpy(opts->dname, cur_data, opts->dname_len);
opts->dname[opts->dname_len] = '\0';
printf("opts->dname = %s\n", opts->dname);
break;
case ISSHE_SOCKS_OPT_PORT:
memcpy(&opts->port, cur_data, sizeof(opts->port));
opts->port = ntohs(opts->port);
printf("---isshe---: opts->port = %u\n", opts->port);
break;
case ISSHE_SOCKS_OPT_USER_DATA_LEN:
memcpy(&opts->user_data_len, cur_data, sizeof(opts->user_data_len));
//opts->user_data_len = opts->user_data_len;
printf("---isshe---: opts->user_data_len = %u\n", opts->user_data_len);
break;
case ISSHE_SOCKS_OPT_END:
end = TRUE;
break;
default:
break;
}
i += cur_len + sizeof(cur_len) + sizeof(cur_type);
}
}
struct isshe_socks_opts *
isshe_socks_opts_new()
{
struct isshe_socks_opts *iso =
(struct isshe_socks_opts *)malloc(sizeof(struct isshe_socks_opts));
if (!iso) {
printf("malloc isshe_socks_opts failed!\n");
return iso;
}
memset(iso, 0, sizeof(struct isshe_socks_opts));
return iso;
}
void
isshe_socks_opts_free(struct isshe_socks_opts *iso)
{
// TODO
if (iso) {
if (iso->dname) {
free(iso->dname);
iso->dname = NULL;
}
if (iso->ipv6) {
free(iso->ipv6);
iso->ipv6 = NULL;
}
free(iso);
iso = NULL;
}
}
struct isshe_socks_connection *
isshe_socks_connection_new()
{
struct isshe_socks_connection *isc =
(struct isshe_socks_connection*)malloc(sizeof(struct isshe_socks_connection));
if (!isc) {
printf("malloc isshe_socks_connection failed!\n");
exit(0);
}
memset(isc, 0, sizeof(struct isshe_socks_connection));
isc->opts = isshe_socks_opts_new();
return isc;
}
void
isshe_socks_connection_free(struct isshe_socks_connection *isc)
{
printf("---free isshe_socks_connection_free---\n");
if (isc) {
if (isc->opts) {
isshe_socks_opts_free(isc->opts);
}
if (isc->target_ai) {
freeaddrinfo(isc->target_ai);
isc->target_ai = NULL;
}
if (isc->bev) {
printf("---free bev: %p\n", isc->bev);
bufferevent_free(isc->bev);
isc->bev = NULL;
printf("---after free: %p\n", isc->bev);
}
free(isc);
//isc = NULL;
}
}
// TODO 拓展为根据配置使用特定的协议进行连接。(当前是TCP)
// TODO 支持IPV4、IPV6
/*
* 连接下一级
*/
struct bufferevent *
isshe_socks_connect_to_next(
struct event_base *evbase,
struct sockaddr *ai_addr,
socklen_t ai_addrlen,
uint16_t port)
{
struct bufferevent *bev_to_user;
bev_to_user = isshe_bufferevent_socket_new(evbase, -1);
assert(bev_to_user);
// TODO 这里没用到opts里面的addr,相关部分进行优化
// TODO 修改这个函数,考虑把这部分提成sockaddr_in *
struct sockaddr_in *addr;
addr = (struct sockaddr_in*)ai_addr;
addr->sin_port = htons(port);
printf("isshe: connet to: %s(%d):%d\n",
inet_ntoa(addr->sin_addr), ai_addrlen,
ntohs(addr->sin_port));
//isshe_print_addrinfo(sc->target_ai);
if (bufferevent_socket_connect(bev_to_user,
(struct sockaddr*)addr, sizeof(struct sockaddr_in)) < 0) {
perror("bufferevent_socket_connect");
bufferevent_free(bev_to_user);
return NULL;
}
/*
int fd_to_user = bufferevent_getfd(bev_to_user);
// TODO 这里什么意思?搬示例libevent的
struct linger linger;
memset(&linger, 0, sizeof(struct linger));
if (setsockopt(fd_to_user, SOL_SOCKET, SO_LINGER,
(const void *)&linger, sizeof(struct linger)) != 0) {
printf("can not disable linger!\n");
return FAILURE;
}
*/
return bev_to_user;
} |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_protocol.h | <reponame>isshe/code-library
/*
* 定义/处理协议本身
*/
#ifndef _ISSHE_ISOUT_PROTOCOL_H_
#define _ISSHE_ISOUT_PROTOCOL_H_
// 标准
#include <stdint.h>
#define ISOUT_ALL_OPT_MAX_LEN 1024
#define ISOUT_HMAC_LEN 32
/*
+------------+----------+----------+
| 消息验证码 | 协议选项 | 加密数据 |
+------------+----------+----------+
*/
typedef struct {
uint8_t type;
uint8_t len;
uint8_t data[0];
} isout_opt_s;
typedef enum {
ISOUT_OPT_COUNT,
ISOUT_OPT_RANDOM,
ISOUT_OPT_DATA_PROTOCOL,
ISOUT_OPT_DATA_LEN,
ISOUT_OPT_IPV4,
ISOUT_OPT_IPV6,
ISOUT_OPT_DOMAIN,
ISOUT_OPT_PORT,
ISOUT_OPT_ADDR_TYPE,
ISOUT_OPT_CRYPTO_ALGO,
ISOUT_OPT_CRYPTO_KEY,
ISOUT_OPT_CRYPTO_IV,
ISOUT_OPT_END = 255,
} isout_opt_e;
int isout_opt_append(uint8_t *buf, uint8_t type, uint8_t len, const void *data);
void isout_opt_init_with_end(uint8_t *buf);
int isout_opts_len(uint8_t *buf);
int isout_opt_find_end(uint8_t *buf);
int isout_opt_insert(uint8_t *buf, uint8_t type, uint8_t len, const void *data);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_process.h | #ifndef _ISSHE_PROCESS_H_
#define _ISSHE_PROCESS_H_
#include "isshe_common.h"
#define isshe_log_pid getpid()
pid_t isshe_fork(void);
void isshe_print_exit_status(int status);
/**
* daemonize: 守护进程化——使一个进程"变为"守护进程
*/
void isshe_daemonize(const char *pname, int facility);
pid_t isshe_waitpid(pid_t pid, int *iptr, int options);
#endif |
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_common.h | #ifndef _ISSHE_SOCKS_COMMON_H_
#define _ISSHE_SOCKS_COMMON_H_
#include <event2/event.h>
#include <event2/listener.h>
#define MAX_OUTPUT (512*1024) // ???!!!
#define SUCCESS 0
#define FAILURE (-1)
#define FALSE 0
#define TRUE 1
struct event_base *isshe_socks_event_new();
struct evconnlistener *isshe_socks_listerner_new_bind(
struct event_base *base, uint16_t port,
evconnlistener_cb cb, void *ptr);
void isshe_forward_data_read_cb(
struct bufferevent *bev, void *ctx);
void isshe_forward_data_event_cb(
struct bufferevent *bev, short what, void *ctx);
int isshe_domain_name_resolution(
const char *domain_name, struct addrinfo **res);
void isshe_print_addrinfo(struct addrinfo *addr_info);
void isshe_print_buffer(char *buf, int buf_len, int print_len);
struct bufferevent *
isshe_bufferevent_socket_new(struct event_base *base, evutil_socket_t fd);
void
isshe_common_event_cb(struct bufferevent *bev, short what, void *ctx);
#endif |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_decode.h | #ifndef _ISSHE_ISOUT_DECODE_H_
#define _ISSHE_ISOUT_DECODE_H_
#include "isession.h"
int isout_decode(isession_s *session);
#endif |
isshe/code-library | K.Tools/issheSocks/src/isshe_config_parser.c | <reponame>isshe/code-library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "isshe_config_parser.h"
static struct socks_parser_config *
socks_parser_config_new()
{
struct socks_parser_config *sp_config;
sp_config = (struct socks_parser_config *)malloc(sizeof(struct socks_parser_config));
if (!sp_config) {
printf("malloc socks parser config failed! exiting...\n");
exit(1);
}
return sp_config;
}
static struct proxy_server_config *
proxy_server_config_new()
{
struct proxy_server_config *ps_config;
ps_config = (struct proxy_server_config *)malloc(sizeof(struct proxy_server_config));
if (!ps_config) {
printf("malloc socks parser config failed! exiting...\n");
exit(1);
}
return ps_config;
}
// TODO 配置解析
void
config_parse(struct isshe_socks_config *config)
{
struct socks_parser_config *sp_config;
struct proxy_server_config *ps_config;
memset(config, 0, sizeof(struct isshe_socks_config));
sp_config = socks_parser_config_new();
sp_config->port = 1080;
ps_config = proxy_server_config_new();
ps_config->port = 27759;
config->sp_config = sp_config;
config->ps_config = ps_config;
}
void config_free(struct isshe_socks_config *config)
{
if (config->sp_config) {
free(config->sp_config);
}
if (config->ps_config) {
free(config->ps_config);
}
}
void
config_print(struct isshe_socks_config *config)
{
printf("-------------isshe socks config--------------\n");
printf("socks parser port: %d\n", config->sp_config->port);
printf("proxy server port: %d\n", config->ps_config->port);
printf("---------------------------------------------\n");
} |
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_parser.c |
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include "isshe_socks_parser.h"
#include "isshe_config_parser.h"
#include "isshe_socks_common.h"
#include "isshe_socks_protocol.h"
void
socks_parser_init(struct isshe_socks_parser *parser, struct isshe_socks_config *config)
{
parser->evbase = NULL;
parser->evlistener = NULL;
parser->config = config;
}
void
socks_parser_uninit(struct isshe_socks_parser *parser)
{
evconnlistener_free(parser->evlistener);
event_base_free(parser->evbase);
}
struct isshe_socks_parser_connection *
socks_parser_connection_new(int fd)
{
struct isshe_socks_parser_connection *spc = malloc(sizeof(struct isshe_socks_parser_connection));
if (!spc) {
printf("can not malloc socks connection, return\n");
return NULL;
}
memset(spc, 0, sizeof(struct isshe_socks_parser_connection));
spc->from_user_conn = isshe_socks_connection_new();
spc->to_user_conn = isshe_socks_connection_new();
spc->from_user_conn->fd = fd;
spc->from_user_conn->status = SCS_WAITING_SELECTION_MSG;
return spc;
}
void
socks_parser_connection_free(struct isshe_socks_parser_connection *spc, uint64_t flag)
{
printf("---free socks_parser_connection_free---\n");
if (spc) {
if (flag & ISSHE_SOCKS_FLAG_FROM_USER) {
printf("---free socks_parser_connection_free---free from user\n");
isshe_socks_connection_free(spc->from_user_conn);
spc->from_user_conn = NULL;
}
if (flag & ISSHE_SOCKS_FLAG_TO_USER) {
printf("---free socks_parser_connection_free---free to user\n");
isshe_socks_connection_free(spc->to_user_conn);
spc->to_user_conn = NULL;
}
if (!flag) {
free(spc);
//spc = NULL;
}
}
}
int is_socks_selection_msg(struct socks_selection_msg *msg)
{
// TODO
return 1;
}
int is_socks_request(struct socks_request *req)
{
// TODO
return 1;
}
void
read_and_drop_all(struct bufferevent *bev, struct evbuffer *evb)
{
char temp;
while(evbuffer_get_length(evb)) {
//printf("len: %d\n", evbuffer_get_length(evb));
bufferevent_read(bev, &temp, sizeof(temp));
}
}
int scs_selction_msg_process(struct bufferevent *bev)
{
printf("---isshe---: scs_selction_msg_process---\n");
struct evbuffer *inevb = bufferevent_get_input(bev);
int len = evbuffer_get_length(inevb);
struct socks_selection_msg msg;
printf("len = %d, sizeof(msg) = %lu\n", len, sizeof(msg));
if (len < sizeof(msg)) {
return 0;
}
bufferevent_read(bev, &msg, sizeof(msg));
if (!is_socks_selection_msg(&msg)) {
printf("scs_selction_msg_process: 有问题\n");
return 0;
}
// 剩下的全部读出来
read_and_drop_all(bev, inevb);
struct socks_selection_msg_reply reply;
memset(&reply, 0, sizeof(reply));
reply.version = DEFAULT_SOCKS_VERSION;
bufferevent_write(bev, &reply, sizeof(reply));
return 1;
}
/*
* 处理socks5命令
*/
void
connect_cmd_process(struct isshe_socks_parser_connection *spc,
struct bufferevent *bev, struct socks_request *request)
{
struct isshe_socks_connection *isc_from_user = spc->from_user_conn;
switch (request->atype)
{
case SOCKS_ADDR_TYPE_DOMAIN:
isc_from_user->opts->addr_type = ISSHE_SOCKS_ADDR_TYPE_DOMAIN;
bufferevent_read(bev, &isc_from_user->opts->dname_len,
sizeof(isc_from_user->opts->dname_len));
break;
case SOCKS_ADDR_TYPE_IPV4:
isc_from_user->opts->addr_type = ISSHE_SOCKS_ADDR_TYPE_IPV4;
isc_from_user->opts->dname_len = IPV4_ADDR_LEN;
break;
case SOCKS_ADDR_TYPE_IPV6:
isc_from_user->opts->addr_type = ISSHE_SOCKS_ADDR_TYPE_IPV6;
isc_from_user->opts->dname_len = IPV6_ADDR_LEN;
break;
default:
break;
}
// 复制到target
int len = evbuffer_get_length(bufferevent_get_input(bev));
if (isc_from_user->opts->dname_len + sizeof(isc_from_user->opts->port) > len) {
printf("Warning: expect len %d, get len %d\n", isc_from_user->opts->dname_len, len);
isc_from_user->opts->dname_len = len - sizeof(isc_from_user->opts->port);
}
isc_from_user->opts->dname = (uint8_t *)malloc(isc_from_user->opts->dname_len + 1);
if (!isc_from_user->opts->dname) {
printf("Error: malloc failed!\n");
// TODO:释放内存,关闭连接
}
bufferevent_read(bev, isc_from_user->opts->dname, isc_from_user->opts->dname_len);
isc_from_user->opts->dname[(int)isc_from_user->opts->dname_len] = '\0';
printf("Debug: target: %s\n", isc_from_user->opts->dname);
bufferevent_read(bev, &isc_from_user->opts->port, sizeof(isc_from_user->opts->port));
}
int scs_request_process(struct isshe_socks_parser_connection *sc, struct bufferevent *bev)
{
printf("---isshe---: scs_request_process---\n");
int len = evbuffer_get_length(bufferevent_get_input(bev));
struct socks_request request;
struct socks_reply reply;
printf("len = %d, sizeof(request) = %lu\n", len, sizeof(request));
if (len < sizeof(request)) {
return 0;
}
bufferevent_read(bev, &request, sizeof(request));
if (!is_socks_request(&request)) {
printf("scs_request_process: 有问题\n");
return 1;
}
switch (request.cmd) {
case SOCKS_CMD_CONNECT:
connect_cmd_process(sc, bev, &request);
break;
default:
break;
}
// 还有剩,就丢了吧
read_and_drop_all(bev, bufferevent_get_input(bev));
memset(&reply, 0, sizeof(reply));
reply.version = DEFAULT_SOCKS_VERSION;
reply.atype = SOCKS_ADDR_TYPE_IPV4;
//reply.port = htons(1080);
// TODO 由于对齐,发送回去的信息多了一些字节(4字节对齐时:原本10字节,现在12字节)
//bufferevent_write(bev, &reply, sizeof(reply) - 2);
bufferevent_write(bev, &reply, sizeof(reply));
return 1;
}
void
socks_parser_proto_opt_gen(struct evbuffer *dst,
struct isshe_socks_connection *isc, uint32_t len)
{
uint8_t mac[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
uint8_t buf[1024];
// 添加消息校验码
evbuffer_add(dst, mac, sizeof(mac));
// TODO 不需要每次都加选项,优化:去掉后续不需要的选项
// 添加选项
//memset(buf, 0, sizeof(buf)); // TODO 是否需要&优化
isshe_socks_opt_init(buf);
isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_DOMAIN,
isc->opts->dname_len, isc->opts->dname);
isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_PORT,
sizeof(isc->opts->port), &(isc->opts->port));
isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_USER_DATA_LEN, sizeof(len), &len);
//isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_CRYPTO_IVEC, )
//isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_CRYPTO_KEY, )
evbuffer_add(dst, buf, isshe_socks_opt_len(buf));
}
void
socks_parser_from_user_read_cb(struct bufferevent *bev, void *ctx)
{
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
struct isshe_socks_connection *isc_from_user = spc->from_user_conn;
struct isshe_socks_connection *isc_to_user = spc->to_user_conn;
uint8_t mac[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
//struct isshe_socks_opt opt;
struct bufferevent *partner = NULL; //isc_to_user->bev;
struct evbuffer *src, *dst;
uint32_t len;
uint8_t buf[128]; // temp
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
if (isc_to_user && isc_to_user->bev) {
partner = isc_to_user->bev;
}
if (!partner) {
evbuffer_drain(src, len);
return;
}
dst = bufferevent_get_output(partner);
if (isc_to_user->status != ISSHE_SCS_ESTABLISHED) {
// 添加消息校验码
evbuffer_add(dst, mac, sizeof(mac));
// TODO 不需要每次都加选项,优化:去掉后续不需要的选项
// 添加选项
memset(buf, 0, sizeof(buf)); // TODO 是否需要&优化
isshe_socks_opt_init(buf);
isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_DOMAIN,
isc_from_user->opts->dname_len, isc_from_user->opts->dname);
isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_PORT,
sizeof(isc_from_user->opts->port), &(isc_from_user->opts->port));
isshe_socks_opt_add(buf, ISSHE_SOCKS_OPT_USER_DATA_LEN, sizeof(len), &len);
evbuffer_add(dst, buf, sizeof(buf)); // TODO 这里固定128字节了
isc_to_user->status = ISSHE_SCS_ESTABLISHED;
}
printf("Debug: %p(%u) -> %p(%lu)\n", bev, len, partner, evbuffer_get_length(dst));
evbuffer_add_buffer(dst, src);
}
void
socks_parser_to_user_read_cb(struct bufferevent *bev, void *ctx)
{
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
struct isshe_socks_connection *isc_from_user = spc->from_user_conn;
struct bufferevent *partner = NULL;
struct evbuffer *src, *dst;
size_t len;
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
if (isc_from_user && isc_from_user->bev) {
partner = isc_from_user->bev;
}
if (!partner) {
printf("evbuffer_drain!!!\n");
evbuffer_drain(src, len);
return;
}
/*
// 读取消息校验码
bufferevent_read(bev, mac, sizeof(mac));
isshe_print_buffer(mac, sizeof(mac), sizeof(mac));
printf("\n---------isshe----------\n");
// 读取选项
bufferevent_read(bev, &opt, sizeof(opt.type) + sizeof(opt.len));
*/
printf("Debug: bev = %p, partner = %p\n", bev, partner);
dst = bufferevent_get_output(partner);
printf("Debug: %p(%lu) <- %p(%lu)\n", partner, evbuffer_get_length(dst), bev, len);
evbuffer_add_buffer(dst, src);
}
static void
socks_data_event_cb(struct bufferevent *bev, short what, void *ctx)
{
printf("-----socks_data_event_cb------");
/*
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
isshe_forward_data_event_cb(bev, what, spc->from_user_conn->bev);
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
printf("INFO: socks_parser_connection_free...\n");
socks_parser_connection_free(spc);
}
*/
}
void
socks_parser_common_event(
struct bufferevent *bev,
struct bufferevent *partner,
bufferevent_data_cb read_cb,
uint64_t bev_flag,
uint64_t partner_flag,
short what,
void *ctx)
{
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
if (errno) {
perror("connection error");
}
}
if (partner) {
// 把所有数据读出来,发给partner
read_cb(bev, ctx);
if (evbuffer_get_length(bufferevent_get_output(partner))) {
bufferevent_disable(partner, EV_READ);
} else {
socks_parser_connection_free(spc, partner_flag);
}
}
socks_parser_connection_free(spc, bev_flag);
}
}
void
socks_parser_from_user_event_cb(struct bufferevent *bev, short what, void *ctx)
{
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
struct bufferevent *partner = NULL;
if (spc->to_user_conn && spc->to_user_conn->bev) {
partner = spc->to_user_conn->bev;
}
socks_parser_common_event(bev, partner,
socks_parser_from_user_read_cb,
ISSHE_SOCKS_FLAG_FROM_USER,
ISSHE_SOCKS_FLAG_TO_USER, what, ctx);
}
void
socks_parser_to_user_event_cb(struct bufferevent *bev, short what, void *ctx)
{
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
struct bufferevent *partner = NULL;
if (spc->from_user_conn && spc->from_user_conn->bev) {
partner = spc->from_user_conn->bev;
}
socks_parser_common_event(bev, partner,
socks_parser_to_user_read_cb,
ISSHE_SOCKS_FLAG_TO_USER,
ISSHE_SOCKS_FLAG_FROM_USER, what, ctx);
}
static void
socks_data_read_cb(struct bufferevent *bev, void *ctx)
{
struct isshe_socks_parser_connection *spc = (struct isshe_socks_parser_connection *)ctx;
struct isshe_socks_connection *isc_from_user = spc->from_user_conn;
struct isshe_socks_connection *isc_to_user = spc->to_user_conn;
printf("fd: %d, ", isc_from_user->fd);
// TODO: 这个while的内容,放到各个case里面:读取并转发/回复
//while (evbuffer_get_length(bufferevent_get_input(bev))) {
// 这里的握手过程还需再捋一下:
// 为什么到了域名解析后,就完了?
// 是怎么知道request完成了的?
switch(isc_from_user->status) {
case SCS_WAITING_SELECTION_MSG:
if (scs_selction_msg_process(bev)) {
isc_from_user->status = SCS_WAITING_REQUEST;
}
break;
case SCS_WAITING_REQUEST:
if (scs_request_process(spc, bev)) {
isc_from_user->status = SCS_CONNECTED;
}
break;
case SCS_CONNECTED:
// TODO: 删除握手定时器
// 转发数据
if (!isc_to_user->bev) {
//connect_to_next(sc);
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY); // TODO 改成proxy的地址
sin.sin_port = htons(spc->sp->config->ps_config->port);
isc_to_user->bev = isshe_socks_connect_to_next(
spc->sp->evbase, (struct sockaddr*)&sin,
sizeof(sin), ntohs(sin.sin_port)); // TODO 这两个port的设置/使用
if (!isc_to_user->bev) {
printf("connect to next failed!\n");
// TODO 释放连接等
exit(1);
}
}
socks_parser_from_user_read_cb(bev, spc);
// 转发完本次的数据后,设置为直接转发数据的函数,不需再进行协议解析
bufferevent_setcb(bev, socks_parser_from_user_read_cb,
NULL, socks_parser_from_user_event_cb, spc);
bufferevent_setcb(isc_to_user->bev, socks_parser_to_user_read_cb,
NULL, socks_parser_to_user_event_cb, (void*)spc);
bufferevent_enable(isc_to_user->bev, EV_READ|EV_WRITE);
break;
default:
break;
}
}
// after accept
static void
socks_parser_accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sa, int socklen, void *user_data)
{
struct bufferevent *bev;
// 打印对端的信息
printf("\nfd: %d, addr:%s, port:%d\n", fd,
inet_ntoa(((struct sockaddr_in*)sa)->sin_addr),
ntohs(((struct sockaddr_in*)sa)->sin_port));
struct isshe_socks_parser_connection *spc = socks_parser_connection_new(fd);
if (!spc) {
return;
}
struct isshe_socks_parser *parser = (struct isshe_socks_parser *)user_data;
bev = isshe_bufferevent_socket_new(parser->evbase, fd);
assert(bev);
spc->from_user_conn->bev = bev;
spc->sp = parser;
bufferevent_setcb(bev, socks_data_read_cb,
NULL, socks_data_event_cb, (void*)spc);
bufferevent_enable(bev, EV_READ|EV_WRITE);
}
void
socks_parser_free(struct isshe_socks_parser *parser, struct isshe_socks_config *config)
{
// TODO
}
int
main(int argc, char *argv[])
{
struct isshe_socks_parser parser;
struct isshe_socks_config config;
// config parse
config_parse(&config);
// config print
config_print(&config);
socks_parser_init(&parser, &config);
parser.evbase = isshe_socks_event_new();
parser.evlistener = isshe_socks_listerner_new_bind(parser.evbase,
config.sp_config->port,
socks_parser_accept_cb, (void *)&parser);
event_base_dispatch(parser.evbase);
socks_parser_uninit(&parser);
config_free(&config);
socks_parser_free(&parser, &config);
printf("done\n");
return 0;
} |
isshe/code-library | B.Operating-System/Linux/Application/A.include/crypto/isshe_aes.h | <gh_stars>1-10
#ifndef _ISSHE_AES_H_
#define _ISSHE_AES_H_
#include <stdint.h>
//#define FULL_UNROLL 1
//#define OPENSSL_SMALL_FOOTPRINT 1
//#define STRICT_ALIGNMENT 1
#define ISSHE_AES_ENCRYPT 1
#define ISSHE_AES_DECRYPT 0
#define ISSHE_AES_MAX_ROUND 14
#define ISSHE_AES_BLOCK_SIZE 16
#define ISSHE_AES_BLOCK_SIZE_BIT 128
#define GETU32(pt) (((uint32_t)(pt)[0] << 24) ^ ((uint32_t)(pt)[1] << 16) ^ ((uint32_t)(pt)[2] << 8) ^ ((uint32_t)(pt)[3]))
#define PUTU32(ct, st) { (ct)[0] = (uint8_t)((st) >> 24); (ct)[1] = (uint8_t)((st) >> 16); (ct)[2] = (uint8_t)((st) >> 8); (ct)[3] = (uint8_t)(st); }
typedef struct isshe_aes_key_s {
int rounds;
uint32_t rd_key[sizeof(uint32_t) * (ISSHE_AES_MAX_ROUND + 1)];
} isshe_aes_key_t;
int isshe_aes_set_encrypt_key(const unsigned char *userKey, const int bits,
isshe_aes_key_t *key);
int isshe_aes_set_decrypt_key(const unsigned char *userKey, const int bits,
isshe_aes_key_t *key);
void isshe_aes_encrypt(const unsigned char *in, unsigned char *out,
const isshe_aes_key_t *key);
void isshe_aes_decrypt(const unsigned char *in, unsigned char *out,
const isshe_aes_key_t *key);
int isshe_aes_wrap_key(isshe_aes_key_t *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen);
int isshe_aes_unwrap_key(isshe_aes_key_t *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen);
#endif |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_decode.c |
#include "isout_decode.h"
#include "isout_encode.h"
#include "isshe_aes_cfg128.h"
#include "isout_protocol.h"
#include "isout_connection.h"
#include "isshe_common.h"
int is_valid_hmac(uint8_t *data, uint32_t len, uint8_t *hmac)
{
uint8_t expect_hmac[ISOUT_HMAC_LEN];
isout_encode_hmac(data, len, expect_hmac);
if (memcmp(hmac, expect_hmac, ISOUT_HMAC_LEN) != 0) {
return ISSHE_FALSE;
}
return ISSHE_TRUE;
}
int isout_decode_data(uint8_t *data, int len)
{
unsigned char ckey[ISSHE_AES_BLOCK_SIZE] = "session key";
unsigned char ivec[ISSHE_AES_BLOCK_SIZE] = "session iv"; // NOTE: ivec这个会被改变!
//unsigned char ivec_cp[ISSHE_AES_BLOCK_SIZE];
//memcpy(ivec_cp , ivec, ISSHE_AES_BLOCK_SIZE);
isshe_aes_key_t key;
int num = 0;
isshe_aes_set_encrypt_key(ckey, ISSHE_AES_BLOCK_SIZE_BIT, &key);
printf("num = %d, ivec = %s\n", num, ivec);
printf("src: %s\n", data);
isshe_aes_cfb128_encrypt(data, data, len, &key, ivec, &num, ISSHE_AES_DECRYPT);
printf("num = %d, ivec = %s\n", num, ivec);
printf("decrypt: %s\n", data);
return ISSHE_SUCCESS;
}
int isout_decode_opts_block(uint8_t *data, int len, isshe_aes_key_t *key, uint8_t *ivec, int *num)
{
printf("num = %d, ivec = %s\n", num, ivec);
printf("src: %s\n", data);
isshe_aes_cfb128_encrypt(data, data, len, &key, ivec, &num, ISSHE_AES_DECRYPT);
printf("num = %d, ivec = %s\n", num, ivec);
printf("decrypt: %s\n", data);
return len;
}
int isout_decode_opts(struct bufferevent *bev, uint8_t *buf)
{
// 一块一块解密,解密完一块,就找找是否存在结束选项标记
isout_opt_s *opt;
uint32_t decoded = 0;
uint32_t checked = 0;
unsigned char ckey[ISSHE_AES_BLOCK_SIZE] = "master key";
unsigned char ivec[ISSHE_AES_BLOCK_SIZE] = "master iv";
isshe_aes_key_t key;
int num = 0;
isshe_aes_set_encrypt_key(ckey, ISSHE_AES_BLOCK_SIZE_BIT, &key);
decoded += isout_decode_opts_block(buf + decoded, ISSHE_AES_BLOCK_SIZE, &key, ivec, &num);
while(checked < ISOUT_ALL_OPT_MAX_LEN) {
if (checked > decoded) {
// read && decode
// TODO 判断长度是否够
bufferevent_read(bev, buf + decoded, ISSHE_AES_BLOCK_SIZE);
decoded += isout_decode_opts_block(buf + decoded, ISSHE_AES_BLOCK_SIZE, &key, ivec, &num);
continue;
}
opt = (isout_opt_s *)(buf + checked);
checked += sizeof(opt->type) + sizeof(opt->len) + opt->len;
if (opt->type == ISOUT_OPT_END) {
return checked;
}
}
return ISSHE_FAILURE;
}
int isout_decode(isession_s *session)
{
isout_connection_s *outconn = (isout_connection_s *)session->out;
isout_connection_s *inconn = (isout_connection_s *)session->in;
struct bufferevent *outbev = outconn->bev;
struct bufferevent *inbev = inconn->bev;
uint8_t opts[ISOUT_ALL_OPT_MAX_LEN];
uint8_t hmac[ISOUT_HMAC_LEN];
uint8_t *data;
uint32_t data_len;
uint32_t opts_len;
// TODO 长度校验,不符合长度,就返回,等待数据到来。具体实现还需再考虑。(断点续跑- -)
// 读取HMAC及部分加密选项
bufferevent_read(inbev, hmac, sizeof(hmac));
bufferevent_read(inbev, opts, ISSHE_AES_BLOCK_SIZE);// TODO 先读16
// 校验HMAC
if (!is_valid_hmac(opts, ISSHE_AES_BLOCK_SIZE, hmac)) {
printf("ERROR: 无效的HMAC!!!\n");
// TODO 清理这个连接
return ISSHE_FAILURE;
}
// 解密
opts_len = isout_decode_opts(inbev, opts);
if (opts_len == ISSHE_FAILURE) {
printf("ERROR: isout_decode_opts\n");
// TODO 清理这个连接
return ISSHE_FAILURE;
}
// 解析选项
isout_opts_parse(inbev->opts, opts);
if (inbev->opts.user_data_len) {
// 分配内存,读数据
uint8_t *udata = (uint8_t *)malloc(inbev->opts.user_data_len);
if (!udata) {
printf("ERROR: isout_decode 分配内存失败!!!\n");
exit(0);
}
// TODO 判断长度是否够
bufferevent_read(inbev, udata, inbev->opts.user_data_len);
// 解密数据
isout_decode_data(udata, inbev->opts.user_data_len);
// 转发数据
bufferevent_write(outbev, udata, inbev->opts.user_data_len);
}
return ISSHE_SUCCESS;
} |
isshe/code-library | K.Tools/wantype/main.c | <reponame>isshe/code-library
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h> /* the L2 protocols */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <net/if.h> // for if_nametoindex
#include <linux/if_ether.h>
#include <linux/if_pppox.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include "dhcp.h"
#include "pppoe.h"
#include "common.h"
void display_help()
{
printf("Usage: wantype <interface> [OPTION...]\n");
printf("Examples:\n");
printf(" wantype eth0\n");
printf(" wantype eth0 -t 10 -s\n");
printf("Options:\n");
printf(" -s show config\n");
printf(" -t <timeout> set timeout\n");
printf(" -h help\n");
}
int parse_opt(int argc, char *argv[], struct wantype_config *cfg)
{
char c;
int len;
int res;
res = 0;
while((c = getopt(argc, argv, "sht:")) != -1 && !res) {
switch(c) {
case 's':
cfg->show_config = 1;
break;
case 'h':
res = -1;
break;
case 't':
cfg->timeout.tv_sec = atoi(optarg);
if (cfg->timeout.tv_sec <= 0) {
printf("invalid timeout\n");
res = -1;
}
break;
case '?':
res = -1;
break;
default:
break;
}
}
if (optind != argc - 1 || res == -1) {
display_help();
res = -1;
} else {
len = strlen(argv[optind]);
if (len > sizeof(cfg->ifname) - 1) {
printf("Warning: ifname to long!\n");
len = sizeof(cfg->ifname) - 1;
}
memset(cfg->ifname, 0, sizeof(cfg->ifname));
memcpy(cfg->ifname, argv[optind], len);
}
return res;
}
void init_config(struct wantype_config *cfg)
{
memset(cfg, 0, sizeof(struct wantype_config));
}
void fix_config(struct wantype_config *cfg)
{
if (cfg->timeout.tv_sec <= 0) {
cfg->timeout.tv_sec = DEFAULT_TIMEOUT;
}
}
void display_config(struct wantype_config *cfg)
{
printf("------config------\n");
printf("ifname: %s\n", cfg->ifname);
printf("timeout: %d\n", (int)(cfg->timeout.tv_sec));
printf("------------------\n");
}
void display_wantype(int wantype)
{
printf("wantype: %d (", wantype);
if (wantype == 0) {
printf("[unknown]");
}
if (wantype & WANTYPE_DHCP) {
printf("[dhcp]");
}
if (wantype & WANTYPE_PPPOE) {
printf("[pppoe]");
}
printf(")\n");
}
int main(int argc, char *argv[])
{
int pppoe_fd;
int dhcp_fd;
int maxfd;
fd_set rset, allset;
struct timeval st, et;
long long spend_time;
struct wantype_config cfg;
struct timeval timeout;
int wantype = 0;
init_config(&cfg);
if (parse_opt(argc, argv, &cfg) < 0) {
exit(1);
}
fix_config(&cfg);
if (cfg.show_config) {
display_config(&cfg);
}
pppoe_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_PPP_DISC));
if (pppoe_fd < 0) {
printf("socket error: %s\n", strerror(errno));
exit(1);
}
dhcp_fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
if (dhcp_fd < 0) {
printf("socket error: %s\n", strerror(errno));
exit(1);
}
send_PADI(pppoe_fd, &cfg);
send_dhcp_discovery(dhcp_fd, &cfg);
FD_ZERO(&allset);
FD_SET(pppoe_fd, &allset);
FD_SET(dhcp_fd, &allset);
if (gettimeofday(&st, NULL) < 0 ) {
printf("gettimeofday error: %s\n", strerror(errno));
exit(1);
}
maxfd = dhcp_fd > pppoe_fd ? dhcp_fd : pppoe_fd;
maxfd += 1;
memcpy(&timeout, &cfg.timeout, sizeof(struct timeval));
do {
rset = allset;
if (select(maxfd, &rset, NULL, NULL, &timeout) < 0) {
printf("select error: %s\n", strerror(errno));
exit(1);
}
if (FD_ISSET(pppoe_fd, &rset)) {
wantype |= WANTYPE_PPPOE;
FD_CLR(pppoe_fd, &allset);
maxfd = dhcp_fd + 1;
}
if (FD_ISSET(dhcp_fd, &rset) && is_dhcp_packet(dhcp_fd)) {
wantype |= WANTYPE_DHCP;
FD_CLR(dhcp_fd, &allset);
maxfd = pppoe_fd + 1;
}
if (!(FD_ISSET(pppoe_fd, &allset) || FD_ISSET(dhcp_fd, &allset))) {
break;
}
if (gettimeofday(&et, NULL) < 0 ) {
printf("gettimeofday error: %s\n", strerror(errno));
exit(1);
}
spend_time = (et.tv_sec - st.tv_sec) * SEC2USEC + et.tv_usec - st.tv_usec;
} while(spend_time < cfg.timeout.tv_sec * SEC2USEC);
display_wantype(wantype);
close(pppoe_fd);
close(dhcp_fd);
exit(0);
} |
isshe/code-library | K.Tools/issheSocks/src/isshe_proxy_server.c |
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include "isshe_config_parser.h"
#include "isshe_proxy_server.h"
#include "isshe_socks_common.h"
#include "isshe_socks_protocol.h"
#include "isout_decode.h"
#include "isout_encode.h"
void
proxy_server_init(struct isshe_proxy_server *server, struct isshe_socks_config *config)
{
server->evbase = NULL;
server->evlistener = NULL;
server->config = config;
}
void
proxy_server_uninit(struct isshe_proxy_server *server)
{
// free
evconnlistener_free(server->evlistener);
event_base_free(server->evbase);
}
struct isshe_proxy_server_connection *
proxy_server_connection_new(struct isshe_proxy_server *server)
{
struct isshe_proxy_server_connection *psc =
(struct isshe_proxy_server_connection*)
malloc(sizeof(struct isshe_proxy_server_connection));
if (!psc) {
printf("malloc isshe_proxy_server_connection failed!\n");
return psc;
}
memset(psc, 0, sizeof(struct isshe_proxy_server_connection));
psc->from_user_conn = isshe_socks_connection_new();
psc->to_user_conn = isshe_socks_connection_new();
psc->ps = server;
return psc;
}
void proxy_server_connection_free(struct isshe_proxy_server_connection *psc, uint64_t flag)
{
printf("---proxy_server_connection_free---\n");
if (psc) {
if (flag & ISSHE_SOCKS_FLAG_FROM_USER) {
printf("---free proxy_server_connection_free---free from user\n");
isshe_socks_connection_free(psc->from_user_conn);
psc->from_user_conn = NULL;
}
if (flag & ISSHE_SOCKS_FLAG_TO_USER) {
printf("---free proxy_server_connection_free---free to user\n");
isshe_socks_connection_free(psc->to_user_conn);
psc->to_user_conn = NULL;
}
if (!flag) {
free(psc);
psc = NULL;
}
}
}
void
proxy_server_to_user_read_cb(struct bufferevent *bev, void *ctx)
{
struct isshe_proxy_server_connection *psc = (struct isshe_proxy_server_connection *)ctx;
struct bufferevent *partner = NULL;
struct evbuffer *src, *dst;
size_t len;
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
if (psc && psc->from_user_conn && psc->from_user_conn->bev) {
partner = psc->from_user_conn->bev;
}
if (!partner) {
printf("evbuffer_drain!!!\n");
evbuffer_drain(src, len);
return;
}
dst = bufferevent_get_output(partner);
if (!dst) {
printf("dst == NULL!!!\n");
return;
}
/*
// 添加消息校验码
evbuffer_add(dst, mac, sizeof(mac));
// 添加选项
isshe_socks_opt_init((uint8_t *)&opt);
evbuffer_add(dst, &opt, sizeof(opt.type) + sizeof(opt.len));
*/
// 转发消息
printf("Debug: %p(%lu) <- %p(%lu)\n", partner, evbuffer_get_length(dst), bev, len);
evbuffer_add_buffer(dst, src);
}
struct bufferevent *
proxy_server_connect_to_next(struct isshe_proxy_server_connection *psc)
{
struct isshe_socks_connection *isc_from_user = psc->from_user_conn;
//struct isshe_socks_connection *isc_to_user = psc->to_user_conn;
struct sockaddr_storage connect_to_addr;
int connect_to_addrlen;
memset(&connect_to_addr, 0, sizeof(connect_to_addr));
connect_to_addrlen = sizeof(connect_to_addr);
// TODO 根据配置决定下一跳,当前暂为目标服务器
if (isc_from_user->opts->ipv4) {
printf("---isc->opts->ipv4---\n");
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
sin.sin_len = sizeof(sin);
#endif
sin.sin_family = AF_INET;
sin.sin_port = htons(isc_from_user->opts->port);
sin.sin_addr.s_addr = htonl(isc_from_user->opts->ipv4);
connect_to_addrlen = sizeof(sin);
memcpy(&connect_to_addr, &sin, connect_to_addrlen);
} else if (isc_from_user->opts->ipv6) {
// TODO
printf("unsupport ipv6\n");
} else if (isc_from_user->opts->dname) {
printf("---isc->opts->dname---\n");
struct addrinfo *ai = isc_from_user->target_ai;
while(ai) {
if (!ai->ai_addr) {
ai = ai->ai_next;
continue;
}
connect_to_addrlen = ai->ai_addrlen;
memcpy(&connect_to_addr,
ai->ai_addr,
connect_to_addrlen);
break;
}
} else {
printf("Error: invalid next partner\n");
return NULL;
}
struct bufferevent * bev_to_user =
isshe_socks_connect_to_next(psc->ps->evbase,
(struct sockaddr *)&connect_to_addr,
connect_to_addrlen, isc_from_user->opts->port);
return bev_to_user;
}
void
proxy_server_from_user_read_cb(struct bufferevent *bev, void *ctx)
{
struct isshe_proxy_server_connection *psc = (struct isshe_proxy_server_connection *)ctx;
struct isshe_socks_connection *isc_from_user = psc->from_user_conn;
struct isshe_socks_connection *isc_to_user = psc->to_user_conn;
struct bufferevent *partner = NULL;
struct evbuffer *src, *dst;
char mac[16] = {0};
uint8_t buf[128]; // TODO: 暂时写死选项长度,调试代理通过后再修改
size_t len;
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
// 连接目标服务器
if (isc_to_user->status != ISSHE_SCS_ESTABLISHED) {
// 读取消息验证码,进行消息验证
bufferevent_read(bev, mac, sizeof(mac));
//isshe_print_buffer(mac, sizeof(mac), sizeof(mac));
// TODO protocol_read_and_parse()
// TODO check_mac()
// TODO read_encode_opts()
// TODO decode_opts()
// 解析选项,有新的选项,就添加到配置结构中
bufferevent_read(bev, buf, sizeof(buf));
//isshe_print_buffer((char *)buf, sizeof(buf), sizeof(buf));
isshe_socks_opt_parse(buf, sizeof(buf), isc_from_user->opts);
if (!isc_from_user->opts->ipv4
&& !isc_from_user->opts->ipv6
&& isc_from_user->opts->dname) {
if (isshe_domain_name_resolution(
(char *)isc_from_user->opts->dname,
&isc_from_user->target_ai) != 0) {
printf("域名解析错误!!!\n");
return;
}
}
// 连接下一跳
isc_to_user->bev = proxy_server_connect_to_next(psc);
if (!isc_to_user->bev) {
// TODO 关闭、清除连接
printf("Error: connect to next failed!\n");
return;
}
isc_to_user->status = ISSHE_SCS_ESTABLISHED;
isc_to_user->fd = bufferevent_getfd(isc_to_user->bev);
// 设置回调
bufferevent_setcb(isc_to_user->bev,
proxy_server_to_user_read_cb, NULL,
proxy_server_to_user_event_cb, (void*)psc);
bufferevent_enable(isc_to_user->bev, EV_READ|EV_WRITE);
}
if (isc_to_user && isc_to_user->bev) {
partner = isc_to_user->bev;
}
if (!partner) {
printf("evbuffer_drain!!!\n");
evbuffer_drain(src, len);
return;
}
// 读取消息,发送给代理服务器
dst = bufferevent_get_output(partner);
printf("Debug: %p(%lu) -> %p(%lu)\n", bev, len, partner, evbuffer_get_length(dst));
evbuffer_add_buffer(dst, src);
}
void
proxy_server_common_event(
struct bufferevent *bev,
struct bufferevent *partner,
bufferevent_data_cb read_cb,
uint64_t bev_flag,
uint64_t partner_flag,
short what,
void *ctx)
{
struct isshe_proxy_server_connection *psc = (struct isshe_proxy_server_connection *)ctx;
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
if (errno) {
printf("bev = %p, partner = %p\n", bev, partner);
perror("connection error");
}
}
if (partner) {
// 把所有数据读出来,发给partner
read_cb(bev, ctx);
if (evbuffer_get_length(bufferevent_get_output(partner))) {
bufferevent_disable(partner, EV_READ);
} else {
proxy_server_connection_free(psc, partner_flag);
}
}
proxy_server_connection_free(psc, bev_flag);
}
}
void
proxy_server_from_user_event_cb(struct bufferevent *bev, short what, void *ctx)
{
struct isshe_proxy_server_connection *psc = (struct isshe_proxy_server_connection *)ctx;
struct bufferevent *partner = NULL;
if (psc && psc->to_user_conn && psc->to_user_conn->bev) {
partner = psc->to_user_conn->bev;
}
proxy_server_common_event(bev, partner,
proxy_server_from_user_read_cb,
ISSHE_SOCKS_FLAG_FROM_USER,
ISSHE_SOCKS_FLAG_TO_USER, what, ctx);
}
void
proxy_server_to_user_event_cb(struct bufferevent *bev, short what, void *ctx)
{
struct isshe_proxy_server_connection *psc = (struct isshe_proxy_server_connection *)ctx;
struct bufferevent *partner = NULL;
if (psc && psc->from_user_conn && psc->from_user_conn->bev) {
partner = psc->from_user_conn->bev;
}
proxy_server_common_event(bev, partner,
proxy_server_to_user_read_cb,
ISSHE_SOCKS_FLAG_TO_USER,
ISSHE_SOCKS_FLAG_FROM_USER, what, ctx);
}
void
proxy_server_accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sa, int socklen, void *user_data)
{
// 打印对端的信息
// TODO: DELETE
printf("\nfd: %d, addr:%s, port:%d\n", fd,
inet_ntoa(((struct sockaddr_in*)sa)->sin_addr),
ntohs(((struct sockaddr_in*)sa)->sin_port));
struct isshe_proxy_server *ps = (struct isshe_proxy_server *)user_data;
struct isshe_proxy_server_connection *psc = proxy_server_connection_new(ps);
psc->from_user_conn->bev = isshe_bufferevent_socket_new(ps->evbase, fd);
assert(psc->from_user_conn->bev);
bufferevent_setcb(psc->from_user_conn->bev,
proxy_server_from_user_read_cb, NULL,
proxy_server_from_user_event_cb, (void*)psc);
bufferevent_enable(psc->from_user_conn->bev, EV_READ|EV_WRITE);
}
int
main(int argc, char *argv[])
{
struct isshe_socks_config config;
struct isshe_proxy_server server;
// config parse
config_parse(&config);
// config print
config_print(&config);
proxy_server_init(&server, &config);
server.evbase = isshe_socks_event_new();
// TODO 支持TCP、UDP!当前只有TCP。(两个协议可同时开)
server.evlistener = isshe_socks_listerner_new_bind(server.evbase,
config.ps_config->port, proxy_server_accept_cb, (void *)&server);
event_base_dispatch(server.evbase);
proxy_server_uninit(&server);
config_free(&config);
printf("done\n");
return 0;
} |
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_common.c | <gh_stars>1-10
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include "isshe_socks_common.h"
struct event_base *
isshe_socks_event_new()
{
struct event_base *base = event_base_new();
if (!base) {
fprintf(stderr, "Could not initialize libevent!\n");
exit(1);
}
return base;
}
struct evconnlistener *
isshe_socks_listerner_new_bind(struct event_base *base,
uint16_t port, evconnlistener_cb cb, void *ptr)
{
// TODO IPV6支持: struct sockaddr_storage
struct sockaddr_in sin;
struct evconnlistener *listener;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
listener = evconnlistener_new_bind(base, cb, ptr,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1, (struct sockaddr*)&sin, sizeof(sin));
if (!listener) {
fprintf(stderr, "Could not create a listener!\n");
exit(1);
}
return listener;
}
void
isshe_forward_data_read_cb(struct bufferevent *bev, void *ctx)
{
struct bufferevent *partner = ctx;
struct evbuffer *src, *dst;
size_t len;
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
if (!partner) {
evbuffer_drain(src, len);
return;
}
dst = bufferevent_get_output(partner);
evbuffer_add_buffer(dst, src);
printf("Debug: %p(%lu) -> %p(%lu)\n", bev, len, partner, evbuffer_get_length(dst));
// 水位/速度调节
//isshe_drained_process(bev, partner, isshe_forward_data_read_cb,
// isshe_drained_write_cb, isshe_forward_data_event_cb, bev);
}
static void
isshe_close_on_finished_write_cb(struct bufferevent *bev, void *ctx)
{
struct evbuffer *b = bufferevent_get_output(bev);
if (evbuffer_get_length(b) == 0) {
bufferevent_free(bev);
}
}
void
isshe_common_event_cb(struct bufferevent *bev, short what, void *ctx)
{
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
if (errno)
perror("connection error");
}
//bufferevent_free(bev);
}
}
void
isshe_forward_data_event_cb(struct bufferevent *bev, short what, void *ctx)
{
struct bufferevent *partner = ctx;
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
if (errno)
perror("connection error");
}
if (partner) {
/* Flush all pending data */
isshe_forward_data_read_cb(bev, ctx);
if (evbuffer_get_length(bufferevent_get_output(partner))) {
/* We still have to flush data from the other
* side, but when that's done, close the other
* side. */
bufferevent_setcb(partner,
NULL, isshe_close_on_finished_write_cb,
isshe_forward_data_event_cb, NULL);
bufferevent_disable(partner, EV_READ);
} else {
/* We have nothing left to say to the other
* side; close it. */
//bufferevent_free(partner);
}
}
//bufferevent_free(bev);
}
}
static int
domain_name_resolution(const char *domain_name, struct addrinfo **res)
{
struct addrinfo hints;
printf("domain_name = %s\n", domain_name);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; // 协议族
hints.ai_flags = AI_CANONNAME;
//hints.ai_socktype = SOCK_STREAM;
//hints.ai_protocol = 0;
// 记得使用freeaddrinfo进行释放!
int ret = getaddrinfo(domain_name, NULL, &hints, res);
if (ret) {
gai_strerror(ret);
}
return ret;
}
int
isshe_domain_name_resolution(const char *domain_name, struct addrinfo **res)
{
int rc;
if ((rc = domain_name_resolution(domain_name, res)) != 0) {
printf("domain name resolution error: %s\n", gai_strerror(rc));
//exit(1);
}
return rc;
}
void
isshe_print_addrinfo(struct addrinfo *ai)
{
struct sockaddr_in *addr;
struct addrinfo *info;
for(info = ai; info != NULL; info = info->ai_next)
{
addr = (struct sockaddr_in*)(info->ai_addr);
printf("ip addresss: %s\n", inet_ntoa(addr->sin_addr));
}
}
void
isshe_print_buffer(char *buf, int buf_len, int print_len)
{
size_t n;
size_t i;
n = buf_len > print_len ? print_len : buf_len;
for (i=0; i<n; ++i) {
printf("%u(%x), ", buf[i], buf[i]);
}
}
struct bufferevent *
isshe_bufferevent_socket_new(struct event_base *base, evutil_socket_t fd)
{
struct bufferevent *bev;
bev = bufferevent_socket_new(base, fd,
BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
if (!bev) {
printf("Error: can not new bufferevent socket\n");
}
return bev;
} |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_file.h | <gh_stars>1-10
#ifndef _ISSHE_FILE_H_
#define _ISSHE_FILE_H_
#include <unistd.h>
#include <sys/stat.h>
#define LOCKMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
int isshe_lock_file(int fd);
int isshe_unlock_file(int fd);
// 简化fcntl锁相关的调用
int lock_reg(int, int, int, off_t, int, off_t); /* {Prog lockreg} */
pid_t lock_test(int, int, off_t, int, off_t); /* {Prog locktest} */
// 几个记录锁的宏
#define read_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLK, F_RDLCK, (offset), (whence), (len))
#define readw_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLKW, F_RDLCK, (offset), (whence), (len))
#define write_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLK, F_WRLCK, (offset), (whence), (len))
#define writew_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLKW, F_WRLCK, (offset), (whence), (len))
#define un_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLK, F_UNLCK, (offset), (whence), (len))
#define is_read_lockable(fd, offset, whence, len) \
(lock_test((fd), F_RDLCK, (offset), (whence), (len)) == 0)
#define is_write_lockable(fd, offset, whence, len) \
(lock_test((fd), F_WRLCK, (offset), (whence), (len)) == 0)
// 失败退出
void isshe_lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len);
pid_t isshe_lock_test(int fd, int type, off_t offset, int whence, off_t len);
#define isshe_read_lock(fd, offset, whence, len) \
isshe_lock_reg((fd), F_SETLK, F_RDLCK, (offset), (whence), (len))
#define isshe_readw_lock(fd, offset, whence, len) \
isshe_lock_reg((fd), F_SETLKW, F_RDLCK, (offset), (whence), (len))
#define isshe_write_lock(fd, offset, whence, len) \
isshe_lock_reg((fd), F_SETLK, F_WRLCK, (offset), (whence), (len))
#define isshe_writew_lock(fd, offset, whence, len) \
isshe_lock_reg((fd), F_SETLKW, F_WRLCK, (offset), (whence), (len))
#define isshe_un_lock(fd, offset, whence, len) \
isshe_lock_reg((fd), F_SETLK, F_UNLCK, (offset), (whence), (len))
#define isshe_is_read_lockable(fd, offset, whence, len) \
(isshe_lock_test((fd), F_RDLCK, (offset), (whence), (len)) == 0)
#define isshe_is_write_lockable(fd, offset, whence, len) \
(isshe_lock_test((fd), F_WRLCK, (offset), (whence), (len)) == 0)
int isshe_open(const char *pathname, int oflag, ...);
void isshe_close(int fd);
void isshe_unlink(const char *pathname);
ssize_t isshe_read(int fd, void *ptr, size_t nbytes);
void isshe_write(int fd, void *ptr, size_t nbytes);
ssize_t isshe_readline(int fd, void *ptr, size_t maxlen);
off_t isshe_lseek(int fd, off_t offset, int whence);
void isshe_ftruncate(int fd, off_t length);
void isshe_fstat(int fd, struct stat *ptr);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_error.h | #ifndef _ISSHE_ERROR_H_
#define _ISSHE_ERROR_H_
#define ISSHE_ERROR_MAX_LINE 4096
enum error_type {
UNIX_ERROR = 0,
POSIX_ERROR,
GAI_ERROR,
APP_ERROR,
DNS_ERROR,
};
/*
* 系统调用错误;不退出;
*/
void isshe_sys_error(const char *fmt, ...);
/*
* 系统调用错误;退出;core dump;
*/
void isshe_sys_error_dump(const char *fmt, ...);
/*
* 系统调用错误;不退出;
*/
void isshe_sys_error_exit(const char *fmt, ...);
/*
* 用户调用错误;不退出;
*/
void isshe_error(const char *fmt, ...);
/*
* 用户调用错误;退出;
*/
void isshe_error_exit(const char *fmt, ...);
/*
* 系统调用错误;INFO级别,不退出
*/
void isshe_sys_info(const char *fmt, ...);
/*
* 用户调用错误;INFO级别,不退出
*/
void isshe_info(const char *fmt, ...);
/*
* 和isshe_sys_error()相同
*/
void isshe_unix_error(const char *fmt, ...);
/*
* 和isshe_sys_error_exit()相同
*/
void isshe_unix_error_exit(const char *fmt, ...);
void isshe_posix_error(int code, const char *fmt, ...);
void isshe_posix_error_exit(int code, const char *fmt, ...);
void isshe_gai_error(int code, const char *fmt, ...);
void isshe_gai_error_exit(int code, const char *fmt, ...);
/*
* 和isshe_error()相同
*/
void isshe_app_error(const char *fmt, ...);
/*
* 和isshe_error_exit()相同
*/
void isshe_app_error_exit(const char *fmt, ...);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_rpc.h | <gh_stars>1-10
#ifndef _ISSHE_RPC_H_
#define _ISSHE_RPC_H_
#include <rpc/rpc.h>
CLIENT *isshe_clnt_create(char *host,
unsigned long prog, unsigned long vers, char *proto);
bool_t isshe_clnt_control(CLIENT *cl, int req, char *info);
#endif |
isshe/code-library | K.Tools/issheSocks/src/roles/isocks/isocks.h | #ifndef _ISSHE_ISOCKS_H_
#define _ISSHE_ISOCKS_H_
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_pthread.h | #ifndef _ISSHE_THREAD_H_
#define _ISSHE_THREAD_H_
#include <pthread.h>
int isshe_pthread_create(pthread_t *tid, const pthread_attr_t *attr, void * (*func)(void *), void *arg);
int isshe_pthread_join(pthread_t tid, void **status);
int isshe_pthread_cancel(pthread_t tid);
int isshe_pthread_detach(pthread_t tid);
void isshe_pthread_exit(void *retval);
pthread_t isshe_pthread_self(void);
void isshe_pthread_once(pthread_once_t *once_control, void (*init_function)());
int isshe_pthread_mutex_lock(pthread_mutex_t *mptr);
int isshe_pthread_mutex_unlock(pthread_mutex_t *mptr);
int isshe_pthread_cond_signal(pthread_cond_t *cptr);
int isshe_pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t *mptr);
int isshe_pthread_cond_timedwait(pthread_cond_t *cptr, pthread_mutex_t *mptr, const struct timespec *tsptr);
pthread_t isshe_thread_id(pthread_t *ptr);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/crypto/isshe_aes_cfg128.h |
#ifndef _ISSHE_AES_CFB128_H_
#define _ISSHE_AES_CFB128_H_
#include "isshe_aes.h"
typedef void (*block128_f) (const unsigned char in[16],
unsigned char out[16], const void *key);
void isshe_aes_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const isshe_aes_key_t *key,
unsigned char *ivec, int *num, const int enc);
#endif |
isshe/code-library | K.Tools/wantype/dhcp.h | #ifndef _DHCP_H_
#define _DHCP_H_
#include <linux/if_ether.h>
#include <stdint.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include "common.h"
#define HOST_NAME "isshe"
#define DHCP_MAGIC 0x63825363
#define BOOTREQUEST 1
#define BOOTREPLY 2
#define OPTION_CODE 0
#define OPTION_LEN 1
#define OPTION_DATA 2
#define SERVER_PORT 67
#define CLIENT_PORT 68
enum dhcp_message_type {
INIT_SELECTING = 0,
DHCP_DISCOVER = 1,
DHCP_OFFER = 2,
DHCP_REQUEST = 3,
DHCP_DECLINE = 4,
DHCP_ACK = 5,
DHCP_NAK = 6,
DHCP_RELEASE = 7,
DHCP_INFORM = 8,
};
enum dhcp_option_code {
DHCP_OPTION_PADDING = 0x00,
DHCP_OPTION_SUBNET = 0x01,
DHCP_OPTION_TIME_OFFSET = 0x02,
DHCP_OPTION_ROUTER = 0x03,
DHCP_OPTION_TIME_SERVER = 0x04,
DHCP_OPTION_NAME_SERVER = 0x05,
DHCP_OPTION_DNS_SERVER = 0x06,
DHCP_OPTION_LOG_SERVER = 0x07,
DHCP_OPTION_COOKIE_SERVER = 0x08,
DHCP_OPTION_LPR_SERVER = 0x09,
DHCP_OPTION_HOST_NAME = 0x0c,
DHCP_OPTION_BOOT_SIZE = 0x0d,
DHCP_OPTION_DOMAIN_NAME = 0x0f,
DHCP_OPTION_SWAP_SERVER = 0x10,
DHCP_OPTION_ROOT_PATH = 0x11,
DHCP_OPTION_IP_TTL = 0x17,
DHCP_OPTION_MTU = 0x1a,
DHCP_OPTION_BROADCAST = 0x1c,
DHCP_OPTION_NTP_SERVER = 0x2a,
DHCP_OPTION_WINS_SERVER = 0x2c,
DHCP_OPTION_REQUESTED_IP = 0x32,
DHCP_OPTION_LEASE_TIME = 0x33,
DHCP_OPTION_OPTION_OVER = 0x34,
DHCP_OPTION_MESSAGE_TYPE = 0x35,
DHCP_OPTION_SERVER_ID = 0x36,
DHCP_OPTION_PARAM_REQ = 0x37,
DHCP_OPTION_MESSAGE = 0x38,
DHCP_OPTION_MAX_SIZE = 0x39,
DHCP_OPTION_T1 = 0x3a,
DHCP_OPTION_T2 = 0x3b,
DHCP_OPTION_VENDOR = 0x3c,
DHCP_OPTION_CLIENT_ID = 0x3d,
DHCP_OPTION_END = 0xff,
};
struct dhcphdr {
uint8_t opcode; // operation code
uint8_t hw_type; // hardware type
uint8_t hw_addr_len; // hardware address length
uint8_t hops; // hop count
uint32_t tid; // transaction ID
uint16_t secs; // number of seconds
uint16_t flags; // flags
uint32_t ciaddr; // client IP address
uint32_t yiaddr; // your IP address
uint32_t siaddr; // server IP address
uint32_t giaddr; // gateway IP address
uint8_t chw_addr[16]; // client hardware address
uint8_t shname[64]; // server host name
uint8_t bfname[128]; // boot filename
uint32_t cookie; // magic cookie in option
uint8_t options[308]; // dhcp options
};
struct dhcp_packet {
struct iphdr ip;
struct udphdr udp;
struct dhcphdr dhcp;
};
struct dhcpopt {
uint8_t option;
uint8_t length;
uint8_t data[0];
};
int send_dhcp_discovery(int sockfd, struct wantype_config *cfg);
int is_dhcp_packet(int sockfd);
#endif
|
isshe/code-library | B.Operating-System/Linux/Kernel/Examples/2.isshe_hic/isshe_hic.c |
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/skbuff.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <net/netfilter/nf_conntrack.h>
#define DRV_VERSION "1.0.0"
#define DRV_DESC "Collect host info"
struct dhcphdr {
__u8 opcode; // operation code
__u8 hw_type; // hardware type
__u8 hw_addr_len; // hardware address length
__u8 hops; // hop count
__be32 tid; // transaction ID
__be16 secs; // number of seconds
__be16 flags; // flags
__be32 ciaddr; // client IP address
__be32 yiaddr; // your IP address
__be32 siaddr; // server IP address
__be32 giaddr; // gateway IP address
__u8 chw_addr[16]; // client hardware address
__u8 shname[64]; // server host name
__u8 bfname[128]; // boot filename
__u8 opmc[4]; // magic cookie in option
__u8 options[0]; // dhcp options
};
static unsigned char *skb_application_header(const struct sk_buff *skb)
{
return skb->head + skb->transport_header + sizeof(struct udphdr);
}
static struct dhcphdr *dhcp_hdr(const struct sk_buff *skb)
{
return (struct dhcphdr *)skb_application_header(skb);
}
static void print_dhcp_options(const unsigned char *options)
{
char buf[512];
const unsigned char *p = options;
int i = 0;
//p = options;
while (p && *p != 255 && i < 20) {
printk("option %d, length %d:\n", *p, *(p + 1));
if (*p == 12) {
memset(buf, 0, sizeof(buf));
memcpy(buf, p + 2, *(p + 1));
printk("----%s\n", buf);
} else if (*p == 53) {
printk("----%d\n", *(p + 2));
} else if (*p == 55) {
for (i = 0; i < *(p + 1); i++) {
printk("----0x%02x(%d)\n", *(p + 2 + i), *(p + 2 + i));
}
} else if (*p == 60) {
memset(buf, 0, sizeof(buf));
memcpy(buf, p + 2, *(p + 1));
printk("----%s\n", buf);
}
p += 2 + *(p + 1);
i += 1;
}
}
static void print_dhcp_header(const struct dhcphdr *hdr)
{
printk("opcode:%d\n", hdr->opcode);
printk("hw_type: %d\n", hdr->hw_type);
printk("hw_addr_len: %d\n", hdr->hw_addr_len);
printk("hops: %d\n", hdr->hops);
printk("tid: %d, to_cpu(tid): %d\n", hdr->tid, be32_to_cpu(hdr->tid));
printk("secs: %d\n", hdr->secs);
printk("flags: %d\n", hdr->flags);
printk("ciaddr: %pI4\n", &hdr->ciaddr);
printk("yiaddr: %pI4\n", &hdr->yiaddr);
printk("siaddr: %pI4\n", &hdr->siaddr);
printk("giaddr: %pI4\n", &hdr->giaddr);
printk("chw_addr: %02x:%02x:%02x:%02x:%02x:%02x\n", hdr->chw_addr[0], hdr->chw_addr[1], hdr->chw_addr[2], hdr->chw_addr[3], hdr->chw_addr[4], hdr->chw_addr[5]);
printk("shname: %s\n", hdr->shname);
printk("bfname: %s\n", hdr->bfname);
printk("opmc: %02x%02x%02x%02x\n", hdr->opmc[0], hdr->opmc[1], hdr->opmc[2], hdr->opmc[3]);
print_dhcp_options((const unsigned char*)hdr->options);
}
static unsigned int isshe_hic_nf_hook(void *priv,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
//struct net_device *in = state->in;
//struct net_device *out = state->out;
//struct udphdr *udp_header;
struct dhcphdr *dhcp_header;
if (0 == skb->len - skb->data_len) {
//printk("---isshe---: data len == 0, len = %d\n", skb->len);
return NF_ACCEPT;
}
// udp only
if (ip_hdr(skb)->protocol != IPPROTO_UDP) {
//printk("---isshe---: not udp\n");
return NF_ACCEPT;
}
//udp_header = udp_hdr(skb);
// dhcp client->server only
if (be16_to_cpu(udp_hdr(skb)->source) != 68 && be16_to_cpu(udp_hdr(skb)->dest) != 67
&& be16_to_cpu(udp_hdr(skb)->source) != 67 && be16_to_cpu(udp_hdr(skb)->dest) != 68) {
//printk("---isshe---: not 68/67, src = %d, dst = %d\n", be16_to_cpu(udp_hdr(skb)->source), be16_to_cpu(udp_hdr(skb)->dest));
return NF_ACCEPT;
}
printk("-----------------isshe-----------------\n");
dhcp_header = dhcp_hdr(skb);
if ((((unsigned char *)dhcp_header) + sizeof(struct dhcphdr)) > (skb->data + skb->len - skb->data_len)) {
printk("---isshe---: too small???\n");
return NF_ACCEPT;
}
print_dhcp_header(dhcp_header);
return NF_ACCEPT;
}
static struct nf_hook_ops isshe_hic_nf_hook_ops[] =
{
{
.hook = isshe_hic_nf_hook,
.pf = NFPROTO_IPV4,
.hooknum = NF_INET_PRE_ROUTING, // ubuntu 自测修改 NF_INET_PRE_ROUTING
.priority = NF_IP_PRI_FIRST, // ---优先级
},
};
/**
* module init
*/
static int __init isshe_hic_init(void)
{
int ret = 0;
//need_conntrack();
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,13,0)
ret = nf_register_net_hooks(&init_net, isshe_hic_nf_hook_ops, ARRAY_SIZE(isshe_hic_nf_hook_ops));
#else
ret = nf_register_hooks(isshe_hic_nf_hook_ops, ARRAY_SIZE(isshe_hic_nf_hook_ops));
#endif
if (ret != 0) {
printk("nf_register_hook failed: %d\n", ret);
return ret;
}
printk("isshe hic init OK\n");
return 0;
}
/**
* module uninit
*/
static void __exit isshe_hic_fini(void)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,13,0)
nf_unregister_net_hooks(&init_net, isshe_hic_nf_hook_ops, ARRAY_SIZE(isshe_hic_nf_hook_ops));
#else
nf_unregister_hooks(isshe_hic_nf_hook_ops, ARRAY_SIZE(isshe_hic_nf_hook_ops));
#endif
printk("isshe hic exit OK\n");
}
module_init(isshe_hic_init);
module_exit(isshe_hic_fini);
MODULE_DESCRIPTION(DRV_DESC);
MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR("isshe <<EMAIL>>");
MODULE_LICENSE("GPL v2");
|
isshe/code-library | K.Tools/issheSocks/src/roles/iproxy/iproxy.h | #ifndef _ISSHE_IPROXY_H_
#define _ISSHE_IPROXY_H_
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#endif |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_encode.c |
#include "isout_encode.h"
#include "isshe_common.h"
#include "isout_connection.h"
#include "isshe_aes_cfg128.h"
int isout_opts_to_string(uint8_t *buf, isout_conn_opts_s *opts, uint64_t flag)
{
int i = 0;
// 这两个放前面!HMAC生成依赖这两个的随机性
i += isout_opt_append(buf + i, ISOUT_OPT_COUNT, sizeof(opts->count), opts->count);
i += isout_opt_append(buf + i, ISOUT_OPT_RANDOM, sizeof(opts->random), opts->random);
if (flag & ISOUT_OPTS_FLAG_DNAME) {
if (!opts->dname_len) {
printf("ERROR: DNAME LEN = 0!!!\n");
exit(0); // TODO
}
i += isout_opt_append(buf + i, ISOUT_OPT_DOMAIN, opts->dname_len, opts->dname);
}
if (flag & ISOUT_OPTS_FLAG_IPV6) {
if (!opts->ipv6_len) {
printf("ERROR: IPV6 LEN = 0!!!\n");
exit(0); // TODO
}
i += isout_opt_append(buf + i, ISOUT_OPT_IPV6, opts->ipv6_len, opts->ipv6);
}
if (flag & ISOUT_OPTS_FLAG_IPV4) {
i += isout_opt_append(buf + i, ISOUT_OPT_IPV4, sizeof(opts->ipv4), opts->ipv4);
}
if (flag & ISOUT_OPTS_FLAG_ADDR_TYPE) {
i += isout_opt_append(buf + i, ISOUT_OPT_ADDR_TYPE, sizeof(opts->addr_type), opts->addr_type);
}
if (flag & ISOUT_OPTS_FLAG_PORT) {
i += isout_opt_append(buf + i, ISOUT_OPT_PORT, sizeof(opts->port), opts->port);
}
i += isout_opt_append(buf + i, ISOUT_OPT_END, 0, NULL);
// NOTE: padding一下
i += ISSHE_AES_BLOCK_SIZE - (i % ISSHE_AES_BLOCK_SIZE);
return i;
}
int isout_encode_opts(uint8_t *data, int len)
{
unsigned char ckey[ISSHE_AES_BLOCK_SIZE] = "master key";
unsigned char ivec[ISSHE_AES_BLOCK_SIZE] = "master iv"; // NOTE: ivec这个会被改变!
//unsigned char ivec_cp[ISSHE_AES_BLOCK_SIZE];
//memcpy(ivec_cp , ivec, ISSHE_AES_BLOCK_SIZE);
isshe_aes_key_t key;
int num;
int index;
assert((len % ISSHE_AES_BLOCK_SIZE) == 0); // Note
isshe_aes_set_encrypt_key(ckey, ISSHE_AES_BLOCK_SIZE_BIT, &key);
for (index = 0; index < len; index += ISSHE_AES_BLOCK_SIZE) {
printf("num = %d, ivec = %s\n", num, ivec);
printf("src: %s\n", data);
isshe_aes_cfb128_encrypt(data + index, data + index, len, &key, ivec, &num, ISSHE_AES_ENCRYPT);
printf("num = %d, ivec = %s\n", num, ivec);
printf("encrypt: %s\n", data);
}
return ISSHE_SUCCESS;
}
int isout_encode_data(uint8_t *data, int len)
{
unsigned char ckey[ISSHE_AES_BLOCK_SIZE] = "session key";
unsigned char ivec[ISSHE_AES_BLOCK_SIZE] = "session iv"; // NOTE: ivec这个会被改变!
//unsigned char ivec_cp[ISSHE_AES_BLOCK_SIZE];
//memcpy(ivec_cp , ivec, ISSHE_AES_BLOCK_SIZE);
isshe_aes_key_t key;
int num = 0;
isshe_aes_set_encrypt_key(ckey, ISSHE_AES_BLOCK_SIZE_BIT, &key);
printf("num = %d, ivec = %s\n", num, ivec);
printf("src: %s\n", data);
isshe_aes_cfb128_encrypt(data, data, len, &key, ivec, &num, ISSHE_AES_ENCRYPT);
printf("num = %d, ivec = %s\n", num, ivec);
printf("encrypt: %s\n", data);
return ISSHE_SUCCESS;
}
int isout_encode_hmac(uint8_t *data, int len, uint8_t *result)
{
uint8_t userpwd[32] = "abc"; // 实际是用户密码的md5
isshe_hmac_sha256(data, len, userpwd, strlen(userpwd), result); // TODO!!!
return ISSHE_SUCCESS;
}
// TODO 性能可能很差!多搞了两次内存复制,以及花了很多内存
int isout_encode(isession_s *session)
{
isout_connection_s *outconn = (isout_connection_s *)session->out;
isout_connection_s *inconn = (isout_connection_s *)session->in;
struct bufferevent *outbev = outconn->bev;
struct bufferevent *inbev = inconn->bev;
uint8_t opts[ISOUT_ALL_OPT_MAX_LEN];
uint8_t hmac[ISOUT_HMAC_LEN];
uint8_t *data;
int data_len;
int opts_len;
// 生成明文选项
memset(opts, 0, ISOUT_ALL_OPT_MAX_LEN);
opts_len = isout_opts_to_string(opts, &outconn->opts, outconn->opts_flag);
// 生成加密选项
isout_encode_opts(opts, opts_len);
assert(opts_len > ISSHE_AES_BLOCK_SIZE);
// 生成HMAC
isout_encode_hmac(opts, ISSHE_AES_BLOCK_SIZE, hmac); // TODO: 16
// 生成加密数据
data_len = evbuffer_get_length(bufferevent_get_input(inbev));
data = (uint8_t *)malloc(data_len);
if (!data) {
printf("ERROR: malloc data error!\n");
exit(0);
}
bufferevent_read(inbev, data, data_len);
data = isout_encode_data(data, data_len);
// 转发HMAC/加密选项/加密数据
bufferevent_write(outbev, hmac, sizeof(hmac));
bufferevent_write(outbev, opts, opts_len);
bufferevent_write(outbev, data, data_len);
free(data);
return ISSHE_SUCCESS;
}
|
isshe/code-library | B.Operating-System/Linux/Application/C.Test/test_isshe_sha2.c | #include <stdio.h>
#include <string.h>
#include "isshe_sha2.h"
void print_hex_buf(uint8_t *buf, int num)
{
int i;
for (i = 0; i < num; i++) {
printf("%02X ", buf[i]);
}
printf("\n");
}
int main(void)
{
char buf[32];
char data[3] = "123";
printf("data = %ld:%s\n", sizeof(data), data);
isshe_sha256((uint8_t *)data, sizeof(data), (uint8_t *)buf);
//isshe_sha256((unsigned char *)buf, (const unsigned char *)data, sizeof(data));
printf("buf = %s\n", buf);
print_hex_buf((uint8_t *)buf, sizeof(buf));
}
|
isshe/code-library | B.Operating-System/Linux/Application/A.include/crypto/isshe_rand.h | <reponame>isshe/code-library
#ifndef _ISSHE_RAND_H_
#define _ISSHE_RAND_H_
//#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
#define ISSHE_DEV_URANDOM "/dev/urandom"
//#endif
int isshe_rand_bytes(unsigned char *buf, int num);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_common.h | <reponame>isshe/code-library
#ifndef _ISSHE_COMMON_H_
#define _ISSHE_COMMON_H_
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <sys/errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdbool.h> // For bool type
//#include <endian.h>
#if defined(__bsdi__) || defined(__APPLE__)
#include <sys/syslimits.h> // for OPEN_MAX
#define va_mode_t int
#else
#define va_mode_t mode_t
#endif
#ifndef OPEN_MAX
#define OPEN_MAX FOPEN_MAX
#endif
#define ISSHE_SUCCESS 0
#define ISSHE_FAILURE (-1)
#define ISSHE_TRUE 1
#define ISSHE_FALSE 0
#define MAXLINE 4096
#define ISSHE_MAXLINE MAXLINE
#ifndef PATH_MAX /* should be in <limits.h> */
#define PATH_MAX 1024 /* max # of characters in a pathname */
#endif
/* default permissions for new files */
#define ISSHE_FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
/* default permissions for new directories */
#define ISSHE_DIR_MODE (FILE_MODE | S_IXUSR | S_IXGRP | S_IXOTH)
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
#define isshe_memzero(buf, size) memset(buf, 0, size)
#if __BYTE_ORDER == __LITTLE_ENDIAN__
#define ISSHE_LITTLE_ENDIAN
#else
#define ISSHE_BIG_ENDIAN
#endif
#endif
|
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_rio.c | #include "isshe_common.h"
#include "isshe_rio.h"
#include "isshe_error.h"
/****************************************
* 健壮I/O函数:标准I/O的包装函数
****************************************/
/*
* rio_readn - 健壮地读取n个字节 (unbuffered/无缓冲)
*/
ssize_t rio_readn(int fd, void *usrbuf, size_t n)
{
size_t nleft = n;
ssize_t nread;
char *bufp = usrbuf;
while (nleft > 0) {
if ((nread = read(fd, bufp, nleft)) < 0) {
if (errno == EINTR) { /* Interrupted by sig handler return */
nread = 0; /* and call read() again */
}
else {
return -1; /* errno set by read() */
}
}
else if (nread == 0) {
break; /* EOF */
}
nleft -= nread;
bufp += nread;
}
return (n - nleft); /* Return >= 0 */
}
/*
* rio_writen - 健壮地写n个字节 (unbuffered/无缓冲)
*/
ssize_t rio_writen(int fd, void *usrbuf, size_t n)
{
size_t nleft = n;
ssize_t nwritten;
char *bufp = usrbuf;
while (nleft > 0) {
if ((nwritten = write(fd, bufp, nleft)) <= 0) {
if (errno == EINTR) { /* Interrupted by sig handler return */
nwritten = 0; /* and call write() again */
}
else {
return -1; /* errno set by write() */
}
}
nleft -= nwritten;
bufp += nwritten;
}
return n;
}
/*
* rio_read - 这是Unix read()的包装函数。(非导出函数)
* 它将min(n, rio_cnt)字节从内部缓冲区传输到用户缓冲区。
* 其中n是用户请求字节数,rio_cnt是内部缓冲区的未读字节数。
* 如果内部缓冲区为空,通过调用read()重新填充内部缓冲区。
*/
static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n)
{
int cnt;
while (rp->rio_cnt <= 0) { /* Refill if buf is empty */
rp->rio_cnt = read(rp->rio_fd, rp->rio_buf, sizeof(rp->rio_buf));
if (rp->rio_cnt < 0) {
if (errno != EINTR) /* Interrupted by sig handler return */
return -1;
}
else if (rp->rio_cnt == 0) { /* EOF */
return 0;
}
else {
rp->rio_bufptr = rp->rio_buf; /* Reset buffer ptr */
}
}
/* Copy min(n, rp->rio_cnt) bytes from internal buf to user buf */
cnt = n;
if (rp->rio_cnt < n) {
cnt = rp->rio_cnt;
}
memcpy(usrbuf, rp->rio_bufptr, cnt);
rp->rio_bufptr += cnt;
rp->rio_cnt -= cnt;
return cnt;
}
/*
* rio_readinitb - 将一个描述符和读缓冲区、重置缓冲区关联。
*/
void rio_readinitb(rio_t *rp, int fd)
{
rp->rio_fd = fd;
rp->rio_cnt = 0;
rp->rio_bufptr = rp->rio_buf;
}
/*
* rio_readnb - 健壮地读n个字节 (buffered/缓冲)
*/
ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n)
{
size_t nleft = n;
ssize_t nread;
char *bufp = usrbuf;
while (nleft > 0) {
if ((nread = rio_read(rp, bufp, nleft)) < 0) {
return -1; /* errno set by read() */
}
else if (nread == 0) {
break; /* EOF */
}
nleft -= nread;
bufp += nread;
}
return (n - nleft); /* return >= 0 */
}
/*
* rio_readlineb - 健壮地读一行 (buffered/缓冲)
*/
ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen)
{
int n, rc;
char c, *bufp = usrbuf;
for (n = 1; n < maxlen; n++) {
if ((rc = rio_read(rp, &c, 1)) == 1) {
*bufp++ = c;
if (c == '\n') {
n++;
break;
}
} else if (rc == 0) {
if (n == 1) {
return 0; /* EOF, no data read */
}
else {
break; /* EOF, some data was read */
}
} else {
return -1; /* Error */
}
}
*bufp = 0;
return n-1;
}
/****************************************
* 健壮I/O的包装函数
****************************************/
ssize_t isshe_rio_readn(int fd, void *ptr, size_t nbytes)
{
ssize_t n;
if ((n = rio_readn(fd, ptr, nbytes)) < 0) {
isshe_sys_error_exit("rio_readn error");
}
return n;
}
void isshe_rio_writen(int fd, void *usrbuf, size_t n)
{
if (rio_writen(fd, usrbuf, n) != n) {
isshe_sys_error_exit("rio_writen error");
}
}
void isshe_rio_readinitb(rio_t *rp, int fd)
{
rio_readinitb(rp, fd);
}
ssize_t isshe_rio_readnb(rio_t *rp, void *usrbuf, size_t n)
{
ssize_t rc;
if ((rc = rio_readnb(rp, usrbuf, n)) < 0) {
isshe_sys_error_exit("rio_readnb error");
}
return rc;
}
ssize_t isshe_rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen)
{
ssize_t rc;
if ((rc = rio_readlineb(rp, usrbuf, maxlen)) < 0) {
isshe_sys_error_exit("rio_readlineb error");
}
return rc;
}
|
isshe/code-library | J.Dynamic-Tracing/Linux-Observability-with-BPF/3.BPF-Map/map-remove/main.c | #include <linux/bpf.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "bpf/bpf.h"
int main(int argc, char **argv)
{
int fd, result, key, value;
fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key),
sizeof(value), 256, 0);
if (fd < 0) {
printf("failed to create map '%s'\n", strerror(errno));
/* likely not run as root */
return 1;
}
key=1;
result = bpf_map_delete_elem(fd, &key);
if (result == 0)
{
printf("Element deleted from the map\n");
}
else
{
printf("Failed to delete element from the map: %d (%s)\n",
result, strerror(errno));
}
return 0;
}
|
isshe/code-library | K.Tools/wantype/pppoe.c |
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h> /* the L2 protocols */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <net/if.h> // for if_nametoindex
#include <sys/ioctl.h>
#include <sys/select.h>
#include "pppoe.h"
int send_PADI(int sockfd, struct wantype_config *cfg)
{
struct pppoe_hdr phdr;
struct pppoe_tag ptag;
struct sockaddr_ll dest;
struct pppoe_packet packet;
int send_len;
memset(packet.eth.h_dest, 0xff, ETH_ALEN);
hwaddr_get(sockfd, cfg->ifname, (char *)packet.eth.h_source);
packet.eth.h_proto = htons(ETH_P_PPP_DISC);
packet.phdr.type = PPPOE_TYPE;
packet.phdr.ver = PPPOE_VERSION;
packet.phdr.code = PADI_CODE;
packet.phdr.sid = 0;
packet.phdr.length = htons(sizeof(struct pppoe_tag));
packet.ptag.tag_type = htons(PPPOE_TAG_TYPE);
packet.ptag.tag_len = 0;
dest.sll_family = AF_PACKET;
dest.sll_halen = ETH_ALEN;
dest.sll_ifindex = if_nametoindex(cfg->ifname);
memset(dest.sll_addr, 0xff, sizeof(dest.sll_addr));
if (sendto(sockfd, &packet, sizeof(packet), 0, (const struct sockaddr *)&dest,sizeof(dest)) < 0) {
printf("sendto error: %s\n", strerror(errno));
exit(1);
}
return 0;
} |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/crypto/isshe_aes_cfb128.c | <reponame>isshe/code-library
#include <stdio.h>
#include "isshe_aes_cfg128.h"
void isshe_crypto_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], int *num,
int enc, block128_f block)
{
unsigned int n;
size_t l = 0;
n = *num;
if (enc) {
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
while (n && len) {
*(out++) = ivec[n] ^= *(in++);
--len;
n = (n + 1) % 16;
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out | (size_t)ivec) %
sizeof(size_t) != 0)
break;
# endif
while (len >= 16) {
(*block) (ivec, ivec, key);
for (; n < 16; n += sizeof(size_t)) {
*(size_t *)(out + n) =
*(size_t *)(ivec + n) ^= *(size_t *)(in + n);
}
len -= 16;
out += 16;
in += 16;
n = 0;
}
if (len) {
(*block) (ivec, ivec, key);
while (len--) {
out[n] = ivec[n] ^= in[n];
++n;
}
}
*num = n;
return;
} while (0);
}
/* the rest would be commonly eliminated by x86* compiler */
#endif
while (l < len) {
if (n == 0) {
(*block) (ivec, ivec, key);
}
out[l] = ivec[n] ^= in[l];
++l;
n = (n + 1) % 16;
}
*num = n;
} else {
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
while (n && len) {
unsigned char c;
*(out++) = ivec[n] ^ (c = *(in++));
ivec[n] = c;
--len;
n = (n + 1) % 16;
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out | (size_t)ivec) %
sizeof(size_t) != 0)
break;
# endif
while (len >= 16) {
(*block) (ivec, ivec, key);
for (; n < 16; n += sizeof(size_t)) {
size_t t = *(size_t *)(in + n);
*(size_t *)(out + n) = *(size_t *)(ivec + n) ^ t;
*(size_t *)(ivec + n) = t;
}
len -= 16;
out += 16;
in += 16;
n = 0;
}
if (len) {
(*block) (ivec, ivec, key);
while (len--) {
unsigned char c;
out[n] = ivec[n] ^ (c = in[n]);
ivec[n] = c;
++n;
}
}
*num = n;
return;
} while (0);
}
/* the rest would be commonly eliminated by x86* compiler */
#endif
while (l < len) {
unsigned char c;
if (n == 0) {
(*block) (ivec, ivec, key);
}
out[l] = ivec[n] ^ (c = in[l]);
ivec[n] = c;
++l;
n = (n + 1) % 16;
}
*num = n;
}
}
void isshe_aes_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const isshe_aes_key_t *key,
unsigned char *ivec, int *num, const int enc)
{
isshe_crypto_cfb128_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) isshe_aes_encrypt);
}
|
isshe/code-library | J.Dynamic-Tracing/Linux-Observability-with-BPF/4.Probes/6.DSDT/main.c | <gh_stars>1-10
#include <sys/sdt.h>
#include <sys/time.h>
int main() {
DTRACE_PROBE(hello-usdt, probe-main);
} |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_unistd.h | <filename>B.Operating-System/Linux/Application/A.include/isshe_unistd.h<gh_stars>1-10
#ifndef _ISSHE_UNISTD_H_
#define _ISSHE_UNISTD_H_
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/types.h>
#include <poll.h>
#ifdef __linux__
#include <sys/epoll.h>
#endif
#if defined(__bsdi__) || defined(__APPLE__)
#include <sys/event.h>
#endif
#ifndef INFTIM
#define INFTIM (-1) /* infinite poll timeout */
#endif
long isshe_pathconf(const char *pathname, int name);
long isshe_sysconf(int name);
int isshe_fcntl(int fd, int cmd, void *arg);
int isshe_getopt(int argc, char *const *argv, const char *str);
void *isshe_calloc(size_t n, size_t size);
void *isshe_malloc(size_t size);
void isshe_free(void *ptr);
void *isshe_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset);
void isshe_munmap(void *addr, size_t len);
void isshe_sleep_us(unsigned int nusecs);
int isshe_select(int nfds, fd_set *readfds,
fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
int isshe_poll(struct pollfd *fdarray, unsigned long nfds, int timeout);
#ifdef __linux__
int isshe_epoll_create(int flags);
int isshe_epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int isshe_epoll_wait(int epfd, struct epoll_event *events,
int maxevents, int timeout, const sigset_t *sigmask);
#endif
#if defined(__bsdi__) || defined(__APPLE__)
int isshe_kqueue(void);
int isshe_kevent(int kq, const struct kevent *changelist, int nchanges,
struct kevent *eventlist, int nevents,
const struct timespec *timeout);
int isshe_kevent64(int kq, const struct kevent64_s *changelist, int nchanges,
struct kevent64_s *eventlist, int nevents, unsigned int flags,
const struct timespec *timeout);
#endif
#endif |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_protocol.c | <gh_stars>1-10
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "isout_protocol.h"
#include "isshe_common.h"
/*
* 一次加一个,返回加的这个选项的长度。
* 预期用法是:
* buf = [], i = 0;
* i += append(buf + i);
*/
int isout_opt_append(uint8_t *buf, uint8_t type, uint8_t len, const void *data)
{
if (!buf) {
printf("ERROR: buf is NULL!!!\n");
return ISSHE_FAILURE;
}
isout_opt_s *opt = (isout_opt_s *)buf;
opt->type = type;
opt->len = len;
if (len) {
memcpy(opt->data, data, opt->len);
}
return sizeof(type) + sizeof(len) + len;
}
void isout_opt_init_with_end(uint8_t *buf)
{
isout_opt_s opt;
opt.type = ISOUT_OPT_END;
opt.len = 0;
memcpy(buf, &opt, sizeof(opt.type) + sizeof(opt.len));
}
// TODO 不够健壮,只考虑了正常已初始化的情况
int isout_opt_find(uint8_t *buf, uint8_t type)
{
int i;
isout_opt_s *opt;
struct isout_opt *opt;
i = 0;
while(i < ISOUT_ALL_OPT_MAX_LEN) {
opt = (isout_opt_s *)(buf + i);
if (opt->type == type) {
return i;
} else if (opt->type == ISOUT_OPT_END) {
return ISSHE_FAILURE;
}
i += opt->len + sizeof(opt->len) + sizeof(opt->type);
}
}
int isout_opt_find_end(uint8_t *buf)
{
return isout_opt_find(buf, ISOUT_OPT_END);
}
int isout_opts_len(uint8_t *buf)
{
isout_opt_s opt;
return isout_opt_find_end(buf) + sizeof(opt.len) + sizeof(opt.type);
}
/*
* 插入到end选项之前
*/
int isout_opt_insert(uint8_t *buf, uint8_t type, uint8_t len, const void *data)
{
int end_pos = isout_opt_find_end(buf);
if (end_pos == ISSHE_FAILURE) {
printf("find end error!!!\n");
return ;
}
end_pos += isout_opt_append(buf + end_pos, type, len, data);
end_pos += isout_opt_append(buf + end_pos, ISOUT_OPT_END, 0, NULL);
return end_pos
}
|
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_unistd.c | <gh_stars>1-10
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include "isshe_unistd.h"
#include "isshe_error.h"
#include "isshe_common.h"
long isshe_pathconf(const char *pathname, int name)
{
long val;
errno = 0; /* in case pathconf() does not change this */
if ( (val = pathconf(pathname, name)) == ISSHE_FAILURE) {
if (errno != 0) {
isshe_sys_error_exit("pathconf error");
}
else {
isshe_sys_error_exit("pathconf: %d not defined", name);
}
}
return(val);
}
long isshe_sysconf(int name)
{
long val;
errno = 0; /* in case sysconf() does not change this */
if ( (val = sysconf(name)) == ISSHE_FAILURE) {
if (errno != 0) {
isshe_sys_error_exit("sysconf error");
}
else {
isshe_sys_error_exit("sysconf: %d not defined", name);
}
}
return(val);
}
int isshe_fcntl(int fd, int cmd, void *arg)
{
int n;
if ( (n = fcntl(fd, cmd, arg)) == ISSHE_FAILURE) {
isshe_sys_error_exit("fcntl error");
}
return(n);
}
pid_t lock_test(int fd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type; /* F_RDLCK or F_WRLCK */
lock.l_start = offset; /* byte offset, relative to l_whence */
lock.l_whence = whence; /* SEEK_SET, SEEK_CUR, SEEK_END */
lock.l_len = len; /* #bytes (0 means to EOF) */
if (fcntl(fd, F_GETLK, &lock) == ISSHE_FAILURE)
return(ISSHE_FAILURE); /* unexpected error */
if (lock.l_type == F_UNLCK)
return(0); /* false, region not locked by another proc */
return(lock.l_pid); /* true, return positive PID of lock owner */
}
pid_t isshe_lock_test(int fd, int type, off_t offset, int whence, off_t len)
{
pid_t pid;
if ( (pid = lock_test(fd, type, offset, whence, len)) == ISSHE_FAILURE) {
isshe_sys_error_exit("lock_test error");
}
return(pid);
}
int isshe_getopt(int argc, char *const *argv, const char *str)
{
int opt;
if ( ( opt = getopt(argc, argv, str)) == '?') {
exit(1); /* getopt() has already written to stderr */
}
return(opt);
}
void *isshe_calloc(size_t n, size_t size)
{
void *ptr;
if ( (ptr = calloc(n, size)) == NULL) {
isshe_sys_error_exit("calloc error");
}
return(ptr);
}
void *isshe_malloc(size_t size)
{
void *ptr;
if ( (ptr = malloc(size)) == NULL) {
isshe_sys_error_exit("malloc error");
}
return(ptr);
}
void isshe_free(void *ptr)
{
if (ptr) {
free(ptr);
} else {
isshe_error("want to free(NULL)");
}
}
void *isshe_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset)
{
void *ptr;
if ( (ptr = mmap(addr, len, prot, flags, fd, offset)) == MAP_FAILED ) {
isshe_sys_error_exit("mmap error");
}
return(ptr);
}
void isshe_munmap(void *addr, size_t len)
{
if (munmap(addr, len) == -1) {
isshe_sys_error_exit("munmap error");
}
}
int sleep_us(unsigned int nusecs)
{
struct timeval tval;
if (nusecs == 0) {
return(0);
}
for ( ; ; ) {
tval.tv_sec = nusecs / 1000000;
tval.tv_usec = nusecs % 1000000;
if (select(0, NULL, NULL, NULL, &tval) == 0) {
return(0); /* all OK */
}
/*
* Note that on an interrupted system call there's not
* much we can do, since the timeval{} isn't updated with the time
* remaining. We could obtain the clock time before the call, and
* then obtain the clock time here, subtracting them to determine
* how long select() blocked before it was interrupted, but that
* seems like too much work :-)
*/
if (errno != EINTR)
return(-1);
/* else go around again */
}
}
void isshe_sleep_us(unsigned int nusecs)
{
if (sleep_us(nusecs) == -1) {
isshe_sys_error_exit("sleep_us error");
}
}
int isshe_select(int nfds, fd_set *readfds,
fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
int n;
again_select:
if ( (n = select(nfds, readfds, writefds, exceptfds, timeout)) < 0) {
if (errno == EINTR) {
goto again_select;
} else {
isshe_sys_error_exit("select error");
}
} else if (n == 0 && timeout == NULL) {
isshe_error_exit("select returned 0 with no timeout");
}
return(n); /* can return 0 on timeout */
}
int isshe_poll(struct pollfd *fdarray, unsigned long nfds, int timeout)
{
int n;
if ( (n = poll(fdarray, nfds, timeout)) < 0) {
isshe_error_exit("poll error");
}
return(n);
}
#ifdef __linux__
int isshe_epoll_create(int flags)
{
int rc;
if ( (rc = epoll_create1(flags)) < 0 ) {
isshe_sys_error_exit("epoll_create1 error");
}
return(rc);
}
int isshe_epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)
{
int rc;
if ( (rc = epoll_ctl(epfd, op, fd, event)) < 0 ) {
isshe_sys_error_exit("epoll_ctl error");
}
return(rc);
}
int isshe_epoll_wait(int epfd, struct epoll_event *events,
int maxevents, int timeout,
const sigset_t *sigmask)
{
int rc;
if (sigmask) {
if ( (rc = epoll_pwait(epfd, events, maxevents, timeout, sigmask)) < 0 ) {
isshe_sys_error_exit("epoll_pwait error");
}
} else {
if ( (rc = epoll_wait(epfd, events, maxevents, timeout)) < 0 ) {
isshe_sys_error_exit("epoll_wait error");
}
}
return(rc);
}
#endif
#if defined(__bsdi__) || defined(__APPLE__)
int isshe_kqueue(void)
{
int rc;
if ((rc = kqueue()) == ISSHE_FAILURE){
isshe_sys_error_exit("kqueue error");
}
return rc;
}
int isshe_kevent(int kq, const struct kevent *changelist, int nchanges,
struct kevent *eventlist, int nevents,
const struct timespec *timeout)
{
int rc;
if ((rc = kevent(kq, changelist, nchanges, eventlist, nevents, timeout)) == ISSHE_FAILURE){
isshe_sys_error_exit("kevent error");
}
return rc;
}
int isshe_kevent64(int kq, const struct kevent64_s *changelist, int nchanges,
struct kevent64_s *eventlist, int nevents, unsigned int flags,
const struct timespec *timeout)
{
int rc;
if ((rc = kevent64(kq, changelist, nchanges, eventlist, nevents, flags, timeout)) == ISSHE_FAILURE){
isshe_sys_error_exit("kevent64 error");
}
return rc;
}
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/crypto/isshe_hmac.h | <filename>B.Operating-System/Linux/Application/A.include/crypto/isshe_hmac.h
#ifndef _ISSHE_HMAC_H_
#define _ISSHE_HMAC_H_
#include <stdint.h>
#define HMAC_IPAD 0x36
#define HMAC_OPAD 0x5c
#define HMAC_PADKEY_LEN 64
#define HMAC_MD5_DIGEST_LEN 16
#define HMAC_SHA256_DIGEST_LEN 32
void isshe_hmac_md5(uint8_t* text, uint64_t text_len,
uint8_t* key, uint64_t key_len, uint8_t digest[HMAC_MD5_DIGEST_LEN]);
void isshe_hmac_sha256(unsigned char* text, int text_len,
unsigned char* key, int key_len, uint8_t digest[HMAC_SHA256_DIGEST_LEN]);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_file.c | <filename>B.Operating-System/Linux/Application/B.lib/isshe_file.c
#include <syslog.h>
#include <fcntl.h>
#include "isshe_file.h"
#include "isshe_error.h"
#include "isshe_common.h"
static int isshe_lock_unlock(int fd, short type) {
struct flock fl;
fl.l_type = type;
fl.l_start = 0;
fl.l_whence = SEEK_SET;
fl.l_len = 0;
return(fcntl(fd, F_SETLK, &fl));
}
int isshe_lock_file(int fd)
{
return isshe_lock_unlock(fd, F_WRLCK);
}
int isshe_unlock_file(int fd)
{
return isshe_lock_unlock(fd, F_UNLCK);
}
int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type; /* F_RDLCK, F_WRLCK, F_UNLCK */
lock.l_start = offset; /* byte offset, relative to l_whence */
lock.l_whence = whence; /* SEEK_SET, SEEK_CUR, SEEK_END */
lock.l_len = len; /* #bytes (0 means to EOF) */
return( fcntl(fd, cmd, &lock) ); /* -1 upon error */
}
void isshe_lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
if (lock_reg(fd, cmd, type, offset, whence, len) == ISSHE_FAILURE) {
isshe_sys_error_exit("lock_reg error");
}
}
int isshe_open(const char *pathname, int oflag, ...)
{
int fd;
va_list ap;
mode_t mode;
if (oflag & O_CREAT) {
va_start(ap, oflag);
mode = va_arg(ap, va_mode_t);
if ( (fd = open(pathname, oflag, mode)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("open error for %s", pathname);
}
va_end(ap);
} else {
if ( (fd = open(pathname, oflag)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("open error for %s", pathname);
}
}
return fd;
}
void isshe_close(int fd)
{
if (close(fd) == ISSHE_FAILURE) {
isshe_sys_error_exit("close error");
}
}
ssize_t isshe_read(int fd, void *ptr, size_t nbytes)
{
ssize_t n;
if ( (n = read(fd, ptr, nbytes)) == ISSHE_FAILURE) {
isshe_sys_error_exit("read error");
}
return(n);
}
void isshe_write(int fd, void *ptr, size_t nbytes)
{
if (write(fd, ptr, nbytes) != nbytes){
isshe_sys_error_exit("write error");
}
}
void isshe_unlink(const char *pathname)
{
if (unlink(pathname) == ISSHE_FAILURE) {
isshe_sys_error_exit("unlink error for %s", pathname);
}
}
static ssize_t restart_read(int fd, char *ptr)
{
static int read_cnt = 0;
static char *read_ptr;
static char read_buf[ISSHE_MAXLINE];
if (read_cnt <= 0) {
while(1) {
if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
if (errno == EINTR) {
continue;
}
return(-1);
} else if (read_cnt == 0) {
return(0);
}
read_ptr = read_buf;
break;
}
}
read_cnt--;
*ptr = *read_ptr++;
return(1);
}
static ssize_t readline(int fd, void *vptr, size_t maxlen)
{
int n, rc;
char c, *ptr;
ptr = vptr;
for (n = 1; n < maxlen; n++) {
if ( (rc = restart_read(fd, &c)) == 1) {
*ptr++ = c;
if (c == '\n')
break; /* newline is stored, like fgets() */
} else if (rc == 0) {
if (n == 1)
return(0); /* EOF, no data read */
else
break; /* EOF, some data was read */
} else
return(-1); /* error, errno set by read() */
}
*ptr = 0; /* null terminate like fgets() */
return(n);
}
/* end readline */
ssize_t isshe_readline(int fd, void *ptr, size_t maxlen)
{
ssize_t n;
if ( (n = readline(fd, ptr, maxlen)) < 0) {
isshe_sys_error_exit("readline error");
}
return(n);
}
off_t isshe_lseek(int fd, off_t offset, int whence)
{
off_t pos;
if ( (pos = lseek(fd, offset, whence)) == (off_t) ISSHE_FAILURE) {
isshe_sys_error_exit("lseek error");
}
return(pos);
}
void isshe_ftruncate(int fd, off_t length)
{
if (ftruncate(fd, length) == ISSHE_FAILURE) {
isshe_sys_error_exit("ftruncate error");
}
}
void isshe_fstat(int fd, struct stat *ptr)
{
if (fstat(fd, ptr) == -1) {
isshe_sys_error_exit("fstat error");
}
}
|
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_ipc.h | <reponame>isshe/code-library
#ifndef _ISSHE_IPC_H_
#define _ISSHE_IPC_H_
#include <sys/msg.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h> // system v
#include <sys/shm.h> // system v
#ifndef SEM_FAILED
#define SEM_FAILED ((sem_t *)(-1))
#endif
#ifdef __linux__
#define SEM_R (0400)
#define SEM_A (0200)
union semun { /* define union for semctl() */
int val;
struct semid_ds *buf;
unsigned short *array;
};
#endif
/* default permissions for new SV semaphores */
/* $$.ix [SVSEM_MODE]~constant,~definition~of$$ */
#define ISSHE_SVSEM_MODE (SEM_R | SEM_A | SEM_R>>3 | SEM_R>>6)
/* default permissions for new SV shared memory */
/* $$.ix [SVSHM_MODE]~constant,~definition~of$$ */
#define ISSHE_SVSHM_MODE (SHM_R | SHM_W | SHM_R>>3 | SHM_R>>6)
/*
* Posix IPC对象使用路径名进行标识,此函数的作用就是生成完整路径名
*/
char *isshe_posix_ipc_name(const char *);
key_t isshe_ftok(const char *pathname, int id);
/* system v 4个消息队列函数*/
int isshe_msgget(key_t key, int flag);
void isshe_msgctl(int id, int cmd, struct msqid_ds *buf);
void isshe_msgsnd(int id, const void *ptr, size_t len, int flag);
ssize_t isshe_msgrcv(int id, void *ptr, size_t len, int type, int flag);
// Posix信号量相关函数
sem_t * isshe_sem_open(const char *pathname, int oflag, ...);
int isshe_sem_close(sem_t *sem);
int isshe_sem_unlink(const char *pathname);
int isshe_sem_wait(sem_t *sem);
int isshe_sem_trywait(sem_t *sem);
int isshe_sem_post(sem_t *sem);
// macos 已经弃用了这几个
#ifdef __linux__
void isshe_sem_getvalue(sem_t *sem, int *valp);
void isshe_sem_init(sem_t *sem, int pshared, unsigned int value);
void isshe_sem_destroy(sem_t *sem);
#endif
// System V信号量
int isshe_semget(key_t key, int nsems, int flag);
int isshe_semop(int id, struct sembuf *opsptr, size_t nops);
int isshe_semctl(int id, int semnum, int cmd, ...);
// 管道
int isshe_pipe(int *fds);
// FIFO
int isshe_mkfifo(const char *pathname, mode_t mode);
// Posix共享内存
int isshe_shm_open(const char *pathname, int oflag, mode_t mode);
int isshe_shm_unlink(const char *pathname);
// System V共享内存
int isshe_shmget(key_t key, size_t size, int flags);
void * isshe_shmat(int id, const void *shmaddr, int flags);
int isshe_shmdt(const void *shmaddr);
int isshe_shmctl(int id, int cmd, struct shmid_ds *buff);
#endif |
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_crypt.h | #ifndef _ISSHE_SOCKS_CRYPT_H_
#define _ISSHE_SOCKS_CRYPT_H_
#endif |
isshe/code-library | J.Dynamic-Tracing/Linux-Observability-with-BPF/3.BPF-Map/map-update/main.c | #include <linux/bpf.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
// for function declare
#include "bpf/bpf.h" // /kernel-src/tools/lib/bpf/bpf.h
int main(int argc, char **argv)
{
int my_map, result, key, value;
key = 1, value = 1234;
my_map = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key),
sizeof(value), 256, 0);
if (my_map < 0) {
printf("failed to create map '%s'\n", strerror(errno));
/* likely not run as root */
return 1;
}
result = bpf_map_update_elem(my_map, &key, &value, BPF_ANY);
if (result == 0)
{
printf("Map updated with new element BPF_ANY\n");
}
else
{
printf("Failed to update map with new value: %d (%s) BPF_ANY\n\n", result, strerror(errno));
}
value = 5678;
// create an element with the same key
result = bpf_map_update_elem(my_map, &key, &value, BPF_NOEXIST);
if (result == 0)
{
printf("Map updated with new element BPF_NOEXIST \n");
}
else
{
printf("Failed to update map with new value: %d (%s) BPF_NOEXIST\n", result, strerror(errno));
}
// update an element that doesn’t exist yet
key = 12, value = 5678;
result = bpf_map_update_elem(my_map, &key, &value, BPF_EXIST);
if (result == 0)
{
printf("Map updated with new element BPF_EXIST\n");
}
else
{
printf("Failed to update map with new value: %d (%s) BPF_EXIST \n", result, strerror(errno));
}
return 0;
}
|
isshe/code-library | J.Dynamic-Tracing/Linux-Observability-with-BPF/3.BPF-Map/rate-limit/rate_limit_kern.c | #include <linux/version.h>
#include <linux/ptrace.h>
#include <uapi/linux/bpf.h>
#include "bpf_helpers.h"
#define SEC(NAME) __attribute__((section(NAME), used))
// static int (*bpf_trace_printk)(const char *fmt, int fmt_size,
// ...) = (void *)BPF_FUNC_trace_printk;
#define IPV4_FAMILY 1
struct ip_key
{
union
{
__u32 v4_addr;
__u8 v6_addr[16];
};
__u8 family;
};
struct bpf_map_def SEC("maps") counters = {
.type = BPF_MAP_TYPE_HASH,
.key_size = sizeof(struct ip_key),
.value_size = sizeof(uint64_t),
.max_entries = 100,
.map_flags = BPF_F_NO_PREALLOC,
};
uint64_t update_counter(uint32_t ipv4)
{
uint64_t *value;
struct ip_key key = {};
key.v4_addr = ipv4;
key.family = IPV4_FAMILY;
value = bpf_map_lookup_elem((void *)&counters, &key);
(*value) += 1;
return *value;
};
SEC("tracepoint/syscalls/sys_enter_execve")
int bpf_prog(void *ctx)
{
char msg[] = "Hello, BPF World!";
bpf_trace_printk(msg, sizeof(msg));
return 0;
}
char _license[] SEC("license") = "GPL";
|
isshe/code-library | K.Tools/wantype/pppoe.h | <gh_stars>1-10
#ifndef _PPPOE_H_
#define _PPPOE_H_
#include <linux/if_ether.h>
#include <linux/if_pppox.h>
#include "common.h"
#define PPPOE_TYPE 0x01
#define PPPOE_VERSION 0x01
#define PPPOE_TAG_TYPE 0x0101
struct pppoe_packet {
struct ethhdr eth;
struct pppoe_hdr phdr;
struct pppoe_tag ptag;
};
int send_PADI(int sockfd, struct wantype_config *cfg);
#endif |
isshe/code-library | K.Tools/issheSocks/src/protocol/isout/isout_connection.c |
#include "isshe_common.h"
#include "isout_connection.h"
#include "isout_protocol.h"
void *isout_opts_malloc_copy(isout_opt_s *opt)
{
void *temp = malloc(opt->len);
if (!temp) {
printf("ERROR: isout_opts_copy malloc!!!\n");
exit(0);
}
memcpy(temp, opt->data, opt->len);
return temp;
}
int isout_opts_parse(isout_conn_opts_s *opts, uint8_t *opts_str)
{
isout_opt_s *opt;
int index;
if (!opts || !opts_str) {
printf("ERROR: !opts && !opts_str!!!\n");
return ISSHE_FAILURE;
}
do {
opt = (isout_opt_s *)opts_str + index;
switch (opt->type)
{
case ISOUT_OPT_COUNT:
opts->count = ntohll(*(uint64_t *)opt->data);
break;
case ISOUT_OPT_RANDOM:
opts->random = ntohl(*(uint32_t *)opt->data);
break;
case ISOUT_OPT_DOMAIN:
opts->dname_len = opt->len;
opts->dname = (uint8_t *)isout_opts_malloc_copy(opt);
break;
case ISOUT_OPT_IPV6:
opts->ipv6_len = opt->len;
opts->ipv6 = (uint8_t *)isout_opts_malloc_copy(opt);
break;
case ISOUT_OPT_IPV4:
opts->ipv4 = ntohl(*(uint32_t *)opt->data); // 大端转主机
break;
case ISOUT_OPT_PORT:
opts->port = ntohs(*(uint16_t *)opt->data);
break;
case ISOUT_OPT_ADDR_TYPE:
opts->addr_type = opt->data[0];
break;
case ISOUT_OPT_DATA_LEN:
opts->user_data_len = ntohs(*(uint16_t *)opt->data);
break;
case ISOUT_OPT_CRYPTO_ALGO:
break;
case ISOUT_OPT_CRYPTO_KEY:
break;
case ISOUT_OPT_CRYPTO_IV:
break;
default:
break;
}
index += sizeof(opt->type) + sizeof(opt->len) + opt->len;
} while(opt->type != ISOUT_OPT_END);
return ISSHE_SUCCESS;
} |
isshe/code-library | K.Tools/issheSocks/src/isshe_socks_parser.h | #ifndef _ISSHE_SOCKS_PARSER_H_
#define _ISSHE_SOCKS_PARSER_H_
// 标准
#include <stdint.h>
// 第三方
#include <event2/event.h>
#include <event2/listener.h>
// 自定义
#include "isshe_config_parser.h"
#define BUFFER_LEN 1500
#define IPV4_ADDR_LEN 4
#define IPV6_ADDR_LEN 16
#define DEFAULT_SOCKS_VERSION 5
#define SOCKS_METHOD_NO_AUTH_REQ 0x00
#define SOCKS_METHOD_GSSAPI 0x01
#define SOCKS_METHOD_USERNAME_PWD 0x02
#define SOCKS_METHOD_NO_SUPPORT_METHOD 0xff
#define SOCKS_CMD_CONNECT 0x01
#define SOCKS_CMD_BIND 0x02
#define SOCKS_CMD_UDP_ASSOCIATE 0x03
#define SOCKS_ADDR_TYPE_IPV4 0x01
#define SOCKS_ADDR_TYPE_DOMAIN 0x03
#define SOCKS_ADDR_TYPE_IPV6 0x04
#define ISSHE_SOCKS_ADDR_TYPE_IPV4 0x01
#define ISSHE_SOCKS_ADDR_TYPE_IPV6 0x02
#define ISSHE_SOCKS_ADDR_TYPE_DOMAIN 0x03
#define SOCKS_REPLY_SUCCEEDED 0x00
#define SOCKS_REPLY_GENERAL_SVR_FAILURE 0x01
#define SOCKS_REPLY_CONN_NOT_ALLOWED 0x02
#define SOCKS_REPLY_NETWORK_UNREACHABLE 0x03
#define SOCKS_REPLY_HOST_UNREACHABLE 0x04
#define SOCKS_REPLY_CONNECTION_REFUSED 0x05
#define SOCKS_REPLY_TTL_EXPIRED 0x06
#define SOCKS_REPLY_CMD_NOT_SUPPORTED 0x07
#define SOCKS_REPLY_ATYPE_NOT_SUPPORTED 0x08
// 0x09-0xff: unassigned
// socks5的连接状态
enum socks5_connection_status {
SCS_UNKNOWN = -1,
SCS_WAITING_SELECTION_MSG = 0,
SCS_WAITING_REQUEST = 1,
SCS_CONNECTED = 2,
};
struct socks_selection_msg {
uint8_t version;
uint8_t nmethods;
uint8_t methods;
};
struct socks_selection_msg_reply {
uint8_t version;
uint8_t method;
};
struct socks_request {
uint8_t version;
uint8_t cmd;
uint8_t rsv;
uint8_t atype;
uint8_t remain[0];
};
#pragma pack(2)
struct socks_reply {
uint8_t version;
uint8_t rep;
uint8_t rsv;
uint8_t atype;
uint32_t addr;
uint16_t port;
};
#pragma pack()
struct isshe_socks_parser
{
struct event_base *evbase;
struct evconnlistener *evlistener;
struct isshe_socks_config *config;
};
struct isshe_socks_parser_connection
{
uint64_t flag;
struct isshe_socks_connection *to_user_conn;
struct isshe_socks_connection *from_user_conn;
struct isshe_socks_parser *sp;
// evtimer: 定时清理状态没有转换的连接
};
#endif |
isshe/code-library | B.Operating-System/Linux/Application/A.include/isshe_socket.h | <filename>B.Operating-System/Linux/Application/A.include/isshe_socket.h
#ifndef _ISSHE_SOCKET_H_
#define _ISSHE_SOCKET_H_
#define LISTENQ 1024 /* Second argument to listen() */
#define SA struct sockaddr
int isshe_socket(int domain, int type, int protocol);
int isshe_setsockopt(int s, int level, int optname, const void *optval, int optlen);
int isshe_bind(int sockfd, struct sockaddr *my_addr, int addrlen);
int isshe_listen(int s, int backlog);
int isshe_accept(int s, struct sockaddr *addr, socklen_t *addrlen);
int isshe_connect(int sockfd, struct sockaddr *serv_addr, int addrlen);
/*
* 一些协议无关包裹函数
*/
int isshe_getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res);
int isshe_getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host,
size_t hostlen, char *serv, size_t servlen, int flags);
void isshe_freeaddrinfo(struct addrinfo *res);
const char * isshe_inet_ntop(int af, const void *src, char *dst, socklen_t size);
int isshe_inet_pton(int af, const char *src, void *dst);
/*
* open_client_fd - 在<hostname,port>处打开与服务器的连接,并返回准备读取和写入的套接字描述符。
* 这个函数是可重入和协议无关的。
*
* On error, returns:
* -2 for getaddrinfo error
* -1 with errno set for other errors.
*/
int open_client_fd(char *hostname, char *port);
/*
* open_listen_fd - 打开并返回port上的listening套接字; 这个函数是可重入和协议无关的
* 错误返回:
* -2: getaddrinfo error
* -1: with errno set for other errors.
*/
int open_listen_fd(char *port);
int isshe_open_client_fd(char *hostname, char *port);
int isshe_open_listen_fd(char *port);
ssize_t isshe_sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
ssize_t isshe_recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_ipc.c |
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#include <fcntl.h> /* For O_* constants */
#include "isshe_ipc.h"
#include "isshe_error.h"
#include "isshe_common.h"
static char *posix_ipc_name(const char *name)
{
char *dir, *dst, *slash;
if ((dst = malloc(PATH_MAX)) == NULL) {
return NULL;
}
if ((dir = getenv("PX_IPC_NAME")) == NULL) {
dir = "/tmp/";
}
slash = (dir[strlen(dir) - 1] == '/') ? "" : "/";
snprintf(dst, PATH_MAX, "%s%s%s", dir, slash, name);
return dst;
}
char *isshe_posix_ipc_name(const char *name)
{
char *ptr;
ptr = posix_ipc_name(name);
if (ptr == NULL) {
isshe_error_exit("isshe_px_ipc_name error for %s", name);
}
return ptr;
}
key_t isshe_ftok(const char *pathname, int id)
{
key_t key;
if ( (key = ftok(pathname, id)) == ISSHE_FAILURE) {
isshe_sys_error_exit("ftok error for pathname \"%s\" and id %d", pathname, id);
}
return(key);
}
// System V message queue
int isshe_msgget(key_t key, int flag)
{
int rc;
if ( (rc = msgget(key, flag)) == ISSHE_FAILURE) {
isshe_sys_error_exit("msgget error");
}
return(rc);
}
void isshe_msgctl(int id, int cmd, struct msqid_ds *buf)
{
if (msgctl(id, cmd, buf) == ISSHE_FAILURE) {
isshe_sys_error_exit("msgctl error");
}
}
void isshe_msgsnd(int id, const void *ptr, size_t len, int flag)
{
if (msgsnd(id, ptr, len, flag) == ISSHE_FAILURE){
isshe_sys_error_exit("msgsnd error");
}
}
ssize_t isshe_msgrcv(int id, void *ptr, size_t len, int type, int flag)
{
ssize_t rc;
if ( (rc = msgrcv(id, ptr, len, type, flag)) == ISSHE_FAILURE){
isshe_sys_error_exit("msgrcv error");
}
return(rc);
}
// Posix semaphore
sem_t * isshe_sem_open(const char *pathname, int oflag, ...)
{
sem_t *sem;
va_list ap;
mode_t mode;
unsigned int value;
if (oflag & O_CREAT) {
va_start(ap, oflag); /* init ap to final named argument */
mode = va_arg(ap, va_mode_t);
value = va_arg(ap, unsigned int);
if ( (sem = sem_open(pathname, oflag, mode, value)) == SEM_FAILED) {
isshe_sys_error_exit("sem_open error for %s", pathname);
}
va_end(ap);
} else {
if ( (sem = sem_open(pathname, oflag)) == SEM_FAILED) {
isshe_sys_error_exit("sem_open error for %s", pathname);
}
}
return(sem);
}
int isshe_sem_close(sem_t *sem)
{
int rc;
if ((rc = sem_close(sem)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("sem_close error");
}
return(rc);
}
int isshe_sem_unlink(const char *pathname)
{
int rc;
if ( (rc = sem_unlink(pathname)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("sem_unlink error");
}
return(rc);
}
int isshe_sem_wait(sem_t *sem)
{
int rc;
if ( (rc = sem_wait(sem)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("sem_wait error");
}
return(rc);
}
int isshe_sem_trywait(sem_t *sem)
{
int rc;
if ( (rc = sem_trywait(sem)) == ISSHE_FAILURE && errno != EAGAIN) {
isshe_sys_error_exit("sem_trywait error");
}
return(rc);
}
int isshe_sem_post(sem_t *sem)
{
int rc;
if ( (rc = sem_post(sem)) == ISSHE_FAILURE ) {
isshe_sys_error_exit("sem_post error");
}
return(rc);
}
#ifdef __linux__
void isshe_sem_init(sem_t *sem, int pshared, unsigned int value)
{
if (sem_init(sem, pshared, value) == ISSHE_FAILURE) {
isshe_sys_error_exit("sem_init error");
}
}
void isshe_sem_destroy(sem_t *sem)
{
if (sem_destroy(sem) == ISSHE_FAILURE) {
isshe_sys_error_exit("sem_destroy error");
}
}
void isshe_sem_getvalue(sem_t *sem, int *valp)
{
if (sem_getvalue(sem, valp) == ISSHE_FAILURE) {
isshe_sys_error_exit("sem_getvalue error");
}
}
#endif
// system V 信号量
int isshe_semget(key_t key, int nsems, int flag)
{
int rc;
if ( (rc = semget(key, nsems, flag)) == ISSHE_FAILURE) {
isshe_sys_error_exit("semget error");
}
return(rc);
}
int isshe_semop(int id, struct sembuf *opsptr, size_t nops)
{
int rc;
if ( (rc = semop(id, opsptr, nops)) == ISSHE_FAILURE) {
isshe_sys_error_exit("semctl error");
}
return(rc);
}
int isshe_semctl(int id, int semnum, int cmd, ...)
{
int rc;
va_list ap;
union semun arg;
if (cmd == GETALL || cmd == SETALL || cmd == SETVAL ||
cmd == IPC_STAT || cmd == IPC_SET) {
va_start(ap, cmd); /* init ap to final named argument */
arg = va_arg(ap, union semun);
if ( (rc = semctl(id, semnum, cmd, arg)) == ISSHE_FAILURE) {
isshe_sys_error_exit("semctl error");
}
va_end(ap);
} else {
if ( (rc = semctl(id, semnum, cmd)) == ISSHE_FAILURE) {
isshe_sys_error_exit("semctl error");
}
}
return(rc);
}
// 管道
int isshe_pipe(int *fds)
{
int rc;
if ((rc = pipe(fds)) < 0) {
isshe_sys_error_exit("pipe error");
}
return(rc);
}
// FIFO
// mkfifo -- make a fifo file
int isshe_mkfifo(const char *pathname, mode_t mode)
{
int rc;
if ((rc = mkfifo(pathname, mode)) == -1) {
isshe_sys_error_exit("mkfifo error for %s", pathname);
}
return(rc);
}
// posix共享内存区
int isshe_shm_open(const char *pathname, int oflag, mode_t mode)
{
int fd;
if ( (fd = shm_open(pathname, oflag, mode)) == -1) {
isshe_sys_error_exit("shm_open error for %s", pathname);
}
return(fd);
}
int isshe_shm_unlink(const char *pathname)
{
int rc;
if ( (rc = shm_unlink(pathname)) == -1) {
isshe_sys_error_exit("shm_unlink error");
}
return(rc);
}
// system V共享内存区
int isshe_shmget(key_t key, size_t size, int flags)
{
int rc;
if ( (rc = shmget(key, size, flags)) == -1) {
isshe_sys_error_exit("shmget error");
}
return(rc);
}
void * isshe_shmat(int id, const void *shmaddr, int flags)
{
void *ptr;
if ( (ptr = shmat(id, shmaddr, flags)) == (void *) -1) {
isshe_sys_error_exit("shmat error");
}
return(ptr);
}
int isshe_shmdt(const void *shmaddr)
{
int rc;
if ((rc = shmdt(shmaddr)) == -1) {
isshe_sys_error_exit("shmdt error");
}
return(rc);
}
int isshe_shmctl(int id, int cmd, struct shmid_ds *buff)
{
int rc;
if ((rc = shmctl(id, cmd, buff)) == -1) {
isshe_sys_error_exit("shmctl error");
}
return(rc);
}
|
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_rpc.c | #include "isshe_rpc.h"
#include "isshe_error.h"
CLIENT *isshe_clnt_create(char *host,
unsigned long prog, unsigned long vers, char *proto)
{
CLIENT *cl;
if ( (cl = clnt_create(host, prog, vers, proto)) == NULL) {
clnt_pcreateerror(host);
isshe_error_exit("clnt_create error");
}
return(cl);
}
bool_t isshe_clnt_control(CLIENT *cl, int req, char *info)
{
bool_t ret;
if ( (ret = clnt_control(cl, req, info)) == FALSE) {
isshe_error_exit("clnt_control error");
}
return(ret);
}
|
isshe/code-library | K.Tools/issheSocks/src/isshe_config_parser.h | <gh_stars>1-10
#ifndef _ISSHE_CONFIG_PARSER_H_
#define _ISSHE_CONFIG_PARSER_H_
#include <stdint.h>
struct socks_parser_config
{
uint8_t enable;
uint8_t dns_enable;
uint8_t outproto;
uint16_t port;
};
struct proxy_server_config
{
uint8_t enable;
uint8_t dns_enable;
uint8_t inproto;
uint8_t outproto;
uint16_t port;
};
struct isshe_socks_config
{
int remote_dns;
struct socks_parser_config *sp_config;
struct proxy_server_config *ps_config;
};
void config_parse(struct isshe_socks_config *config);
void config_print(struct isshe_socks_config *config);
void config_free(struct isshe_socks_config *config);
#endif |
isshe/code-library | B.Operating-System/Linux/Application/B.lib/isshe_error.c | #include <stdio.h>
#include <errno.h> // for "errno"
#include <stdarg.h> // for "可变参"
#include <string.h>
#include <stdlib.h>
#include <syslog.h> // for syslog()
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h> // for inet_ntop()/inet_pton()
#include "isshe_error.h"
int daemon_proc; /* 被daemon_init()设置为非0,表示守护进程 */
/*
* 打印一个信息,并返回到调用者。
* 调用者指定"errno_flag"。
* 改变这个函数,就能实现打印到文件中或者其他地方。
*/
static void err_doit(enum error_type type,
int error_code, int level, const char *fmt, va_list ap)
{
int n;
char buf[ISSHE_ERROR_MAX_LINE];
vsnprintf(buf, sizeof(buf), fmt, ap);
n = strlen(buf);
if (type == UNIX_ERROR || type == POSIX_ERROR ) {
snprintf(buf+n, sizeof(buf)-n, ": %s", strerror(error_code));
} else if (type == GAI_ERROR) {
snprintf(buf+n, sizeof(buf)-n, ": %s", gai_strerror(error_code));
}
strcat(buf, "\n");
if (daemon_proc) {
syslog(level, "%s", buf);
} else {
fflush(stdout); // in case stdout and stderr are the same
fputs(buf, stderr);
fflush(NULL); // flushes all stdio output streams
}
return;
}
void isshe_sys_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(UNIX_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
}
void isshe_sys_error_dump(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(UNIX_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
abort(); // dump core and terminate
exit(0); // shouldn't get here
}
void isshe_sys_error_exit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(UNIX_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
exit(0);
}
void isshe_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(APP_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
}
void isshe_error_exit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(APP_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
exit(0);
}
void isshe_sys_info(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(UNIX_ERROR, errno, LOG_INFO, fmt, ap);
va_end(ap);
}
void isshe_info(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(APP_ERROR, errno, LOG_INFO, fmt, ap);
va_end(ap);
}
void isshe_unix_error(const char *fmt, ...) /* Unix-style error */
{
va_list ap;
va_start(ap, fmt);
err_doit(UNIX_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
}
void isshe_unix_error_exit(const char *fmt, ...) /* Unix-style error */
{
va_list ap;
va_start(ap, fmt);
err_doit(UNIX_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
exit(0);
}
void isshe_posix_error(int code, const char *fmt, ...) /* Posix-style error */
{
va_list ap;
va_start(ap, fmt);
err_doit(POSIX_ERROR, code, LOG_ERR, fmt, ap);
va_end(ap);
}
void isshe_posix_error_exit(int code, const char *fmt, ...) /* Posix-style error */
{
va_list ap;
va_start(ap, fmt);
err_doit(POSIX_ERROR, code, LOG_ERR, fmt, ap);
va_end(ap);
exit(0);
}
void isshe_gai_error(int code, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(GAI_ERROR, code, LOG_ERR, fmt, ap);
va_end(ap);
}
void isshe_gai_error_exit(int code, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(GAI_ERROR, code, LOG_ERR, fmt, ap);
va_end(ap);
exit(0);
}
void isshe_app_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(APP_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
}
void isshe_app_error_exit(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(APP_ERROR, errno, LOG_ERR, fmt, ap);
va_end(ap);
exit(0);
} |
isshe/code-library | K.Tools/issheSocks/src/roles/irelay/irelay.h | #ifndef _ISSHE_IRELAY_H_
#define _ISSHE_IRELAY_H_
#endif |
isshe/code-library | K.Tools/issheSocks/src/roles/iproxy/iproxy.c | <filename>K.Tools/issheSocks/src/roles/iproxy/iproxy.c<gh_stars>1-10
#include "iproxy.h"
#include "isession.h"
void iproxy_left_read_cb(struct bufferevent *bev, void *ctx)
{
}
void iproxy_right_read_cb(struct bufferevent *bev, void *ctx)
{
}
void iproxy_left_event_cb(
struct bufferevent *bev, short what, void *ctx)
{
}
void iproxy_right_event_cb(
struct bufferevent *bev, short what, void *ctx)
{
}
void iproxy_left_accept_cb(struct evconnlistener *listener,
evutil_socket_t fd, struct sockaddr *sa, int socklen, void *ctx)
{
// TODO xxx = ctx;
struct isshe_proxy_server_connection *psc = proxy_server_connection_new(ps);
psc->from_user_conn->bev = isshe_bufferevent_socket_new(ps->evbase, fd);
assert(psc->from_user_conn->bev);
bufferevent_setcb(psc->from_user_conn->bev,
proxy_server_from_user_read_cb, NULL,
proxy_server_from_user_event_cb, (void*)psc);
bufferevent_enable(psc->from_user_conn->bev, EV_READ|EV_WRITE);
} |
illej/opengl-app | src/vertex_buffer.h | #ifndef VERTEX_BUFFER_H
#define VERTEX_BUFFER_H
#include "renderer.h"
struct vertex_buffer
{
unsigned int renderer_id;
};
struct vb_element
{
struct vertex_buffer *vbo; // TODO: this is bad lol
unsigned int count;
unsigned int type;
unsigned char normalised;
};
struct vb_layout
{
unsigned int element_count;
struct vb_element elements[256];
unsigned int stride;
};
unsigned int
vb_element_type_size (unsigned int type)
{
switch (type)
{
case GL_FLOAT: return 4;
case GL_UNSIGNED_INT: return 4;
case GL_UNSIGNED_BYTE: return 1;
default:
ASSERT (!"unknown type");
return 0;
}
}
void
vb_layout_create (struct vb_layout *layout)
{
layout->element_count = 0;
layout->stride = 0;
}
static bool
__vb_layout_push (struct vb_layout *layout, struct vertex_buffer *vbo, unsigned int count, unsigned int type, unsigned char normalised)
{
bool ok = false;
if (layout->element_count + 1 < ARRAY_LEN (layout->elements))
{
struct vb_element *e = &layout->elements[layout->element_count++];
e->vbo = vbo;
e->count = count;
e->type = type;
e->normalised = normalised;
ok = true;
}
else
{
ASSERT (!"max vb elements reached");
}
return ok;
}
void
vb_layout_push_f (struct vb_layout *layout, struct vertex_buffer *vbo, unsigned int count)
{
if (__vb_layout_push (layout, vbo, count, GL_FLOAT, GL_FALSE))
{
layout->stride += vb_element_type_size (GL_FLOAT) * count;
}
}
void
vb_layout_push_uint (struct vb_layout *layout, unsigned int count)
{
if (__vb_layout_push (layout, 0, count, GL_UNSIGNED_INT, GL_FALSE))
{
layout->stride += vb_element_type_size (GL_UNSIGNED_INT) * count;
}
}
void
vb_layout_push_uchar (struct vb_layout *layout, unsigned int count)
{
if (__vb_layout_push (layout, 0, count, GL_UNSIGNED_BYTE, GL_TRUE))
{
layout->stride += vb_element_type_size (GL_UNSIGNED_BYTE) * count;
}
}
unsigned int
vb_layout_stride_get (struct vb_layout *layout)
{
return layout->stride;
}
void
vb_create (struct vertex_buffer *vb, void *data, unsigned int len)
{
GLCALL (glGenBuffers (1, &vb->renderer_id));
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, vb->renderer_id));
GLCALL (glBufferData (GL_ARRAY_BUFFER, len, data, GL_STATIC_DRAW));
}
void
vb_delete (struct vertex_buffer *vb)
{
GLCALL (glDeleteBuffers (1, &vb->renderer_id));
}
void
vb_bind (struct vertex_buffer *vb)
{
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, vb->renderer_id));
}
void
vb_unbind (void)
{
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, 0));
}
#endif /* VERTEX_BUFFER_H */
|
illej/opengl-app | src/texture.h | #ifndef TEXTURE_H
#define TEXTURE_H
struct texture
{
unsigned int id;
unsigned char *data;
int width;
int height;
int bytes_per_pixel;
};
static void
texture_create (struct texture *tex, char *file)
{
stbi_set_flip_vertically_on_load (1);
tex->data = stbi_load (file, &tex->width, &tex->height, &tex->bytes_per_pixel, 4);
if (tex->data)
{
GLCALL (glGenTextures (1, &tex->id));
GLCALL (glBindTexture (GL_TEXTURE_2D, tex->id));
GLCALL (glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCALL (glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
GLCALL (glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GLCALL (glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
GLCALL (glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, tex->width, tex->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex->data));
GLCALL (glBindTexture (GL_TEXTURE_2D, 0));
stbi_image_free (tex->data);
}
else
{
printf ("failed to load image \"%s\"\n", file);
ASSERT (!"failed to texture");
}
}
static void
texture_delete (struct texture *tex)
{
GLCALL (glDeleteTextures (1, &tex->id));
}
void
texture_bind (struct texture *tex, unsigned int slot)
{
GLCALL (glActiveTexture (GL_TEXTURE0 + slot));
GLCALL (glBindTexture (GL_TEXTURE_2D, tex->id));
}
texture_unbind (void)
{
GLCALL (glBindTexture (GL_TEXTURE_2D, 0));
}
#endif
|
illej/opengl-app | tests/test.c | #include "test_clear_colour.h"
#include "test_texture.h"
#include "test_3d_cube.h"
// TODO: may be able to put this back into test.h??? do we want to??
void
test_setup (enum test_type type, struct test_data *d)
{
d->type = type;
switch (d->type)
{
case TEST_CLEAR_COLOUR: { test_clear_colour_setup (d); break; }
case TEST_TEXTURE: { test_texture_setup (d); break; }
case TEST_3D_CUBE: { test_3d_cube_setup (d); break; }
default:
ASSERT (!"unknown setup type");
}
}
void
test_update (struct test_data *t, float dt)
{
}
void
test_render (struct test_data *t)
{
switch (t->type)
{
case TEST_CLEAR_COLOUR: { test_clear_colour_render (t); break; }
case TEST_TEXTURE: { test_texture_render (t); break; }
case TEST_3D_CUBE: { test_3d_cube_render (t); break; }
default:
ASSERT (!"unknown render type");
}
}
void
test_render_gui (struct test_data *t, struct nk_context *nk)
{
switch (t->type)
{
case TEST_CLEAR_COLOUR: { test_clear_colour_render_gui (t, nk); break; }
case TEST_TEXTURE: { test_texture_render_gui (t, nk); break; }
case TEST_3D_CUBE: { test_3d_cube_render_gui (t, nk); break; }
default:
ASSERT (!"unknown render gui type");
}
}
void
test_teardown (struct test_data *t)
{
switch (t->type)
{
case TEST_CLEAR_COLOUR: { test_clear_colour_teardown (t); break; }
case TEST_TEXTURE: { test_texture_teardown (t); break; }
case TEST_3D_CUBE: { test_3d_cube_teardown (t); break; }
default:
ASSERT (!"unknown teardown type");
}
}
|
illej/opengl-app | src/renderer.h | #ifndef RENDERER_H
#define RENDERER_H
#include "common.h"
#include "vertex_buffer.h"
#include "vertex_array.h"
#include "index_buffer.h"
#include "shader.h"
#include "texture.h"
struct renderer
{
unsigned int id;
};
static void
renderer_clear (void)
{
GLCALL (glClearColor (0.0f, 0.15f, 0.3f, 1.0f));
GLCALL (glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
};
static void
renderer_draw (struct renderer *r, struct vertex_array *vao, struct index_buffer *ibo, struct shader *shader)
{
shader_bind (shader);
va_bind (vao);
ib_bind (ibo);
GLCALL (glDrawElements (GL_TRIANGLES, ib_count_get (ibo), GL_UNSIGNED_INT, NULL));
}
#endif /* RENDERER_H */
|
illej/opengl-app | src/shader.h | #ifndef SHADER_H
#define SHADER_H
#include "renderer.h"
struct uniform_location_cache_entry
{
char name[32];
int location;
};
struct shader
{
unsigned int id;
unsigned int cache_len;
struct uniform_location_cache_entry uniform_location_cache[256];
};
static char *
read_file_to_str (char *file)
{
size_t len = 0;
char *buf = NULL;
FILE *fp = fopen (file, "r");
if (fp)
{
fseek (fp, 0, SEEK_END);
len = ftell (fp);
fseek (fp, 0, SEEK_SET);
buf = malloc (len + 1);
memset (buf, 0, len + 1);
if (buf)
{
fread (buf, 1, len, fp);
buf[len] = '\0';
#if 0
for (int i = 0; i < len; i++)
{
char c = buf[i];
if (c == '\0') c = '!';
printf ("[%c]", c);
}
printf ("\n");
#endif
}
fclose (fp);
}
if (!buf)
{
printf ("failed to read file \"%s\"\n", file);
}
return buf;
}
static unsigned int
shader_compile (unsigned int type, char *source)
{
GLCALL (unsigned int id = glCreateShader (type));
GLCALL (glShaderSource (id, 1/* count */, &source, NULL/* length */));
GLCALL (glCompileShader (id));
int result;
glGetShaderiv (id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int len;
glGetShaderiv (id, GL_INFO_LOG_LENGTH, &len);
char *message = alloca (len * sizeof (char));
glGetShaderInfoLog (id, len, NULL, message);
printf ("failed to compile %s shader: \"%s\"\n",
(type == GL_VERTEX_SHADER ? "vertex" : "fragment"),
message);
glDeleteShader (id);
id = 0;
}
return id;
}
void
shader_create (struct shader *shader, char *vertex_file, char *fragment_file)
{
unsigned int vert_id = 0;
unsigned int frag_id = 0;
unsigned int program_id = 0;
char *vertex_source = read_file_to_str (vertex_file);
char *fragment_source = read_file_to_str (fragment_file);
if (vertex_source && fragment_source)
{
vert_id = shader_compile (GL_VERTEX_SHADER, vertex_source);
frag_id = shader_compile (GL_FRAGMENT_SHADER, fragment_source);
program_id = glCreateProgram ();
glAttachShader (program_id, vert_id);
glAttachShader (program_id, frag_id);
glLinkProgram (program_id);
glValidateProgram (program_id);
int result;
glGetProgramiv (program_id, GL_LINK_STATUS, &result);
if (result == GL_FALSE)
{
int len;
glGetProgramiv (program_id, GL_INFO_LOG_LENGTH, &len);
char *message = alloca (len * sizeof (char));
glGetProgramInfoLog (program_id, len, NULL, message);
printf ("failed to link shader program: \"%s\"\n", message);
program_id = 0;
}
glDetachShader (program_id, vert_id);
glDetachShader (program_id, frag_id);
glDeleteShader (vert_id);
glDeleteShader (frag_id);
}
if (vertex_source) free (vertex_source);
if (fragment_source) free (fragment_source);
shader->id = program_id;
ASSERT (program_id != 0);
}
void
shader_delete (struct shader *shader)
{
GLCALL (glDeleteProgram (shader->id));
}
void
shader_bind (struct shader *shader)
{
GLCALL (glUseProgram (shader->id));
}
void
shader_unbind (void)
{
GLCALL (glUseProgram (0));
}
static int
shader_get_uniform_location (struct shader *shader, char *name)
{
int location = -1;
bool found = false;
for (unsigned int i = 0; i < shader->cache_len; i++)
{
if (strcmp (name, shader->uniform_location_cache[i].name) == 0)
{
location = shader->uniform_location_cache[i].location;
found = true;
// printf ("cache entry found for %s %d\n", name, location);
break;
}
}
if (!found)
{
GLCALL (int location = glGetUniformLocation (shader->id, name));
if (location == -1)
{
printf ("Warning: uniform %s does not exist\n", name);
}
if (shader->cache_len + 1 < ARRAY_LEN (shader->uniform_location_cache))
{
// printf ("cache entry not found for %s\n", name);
struct uniform_location_cache_entry *e = &shader->uniform_location_cache[shader->cache_len++];
snprintf (e->name, 32, "%s", name);
e->location = location;
// printf ("entry added (%u)\n", shader->cache_len);
}
else
{
ASSERT (!"uniform location cache full");
}
}
return location;
}
void
shader_set_uniform_4f (struct shader *shader, char *name, float v0, float v1, float v2, float v3)
{
GLCALL (glUniform4f (shader_get_uniform_location (shader, name), v0, v1, v2, v3));
}
void
shader_set_uniform_m4f (struct shader *shader, char *name, float *fptr)
{
GLCALL (glUniformMatrix4fv (shader_get_uniform_location (shader, name), 1, GL_FALSE, fptr));
}
void
shader_set_uniform_1f (struct shader *shader, char *name, float value)
{
GLCALL (glUniform1f (shader_get_uniform_location (shader, name), value));
}
void
shader_set_uniform_1i (struct shader *shader, char *name, int value)
{
GLCALL (glUniform1i (shader_get_uniform_location (shader, name), value));
}
#endif /* SHADER_H */
|
illej/opengl-app | src/common.h | <reponame>illej/opengl-app
#ifndef COMMON_H
#define COMMON_H
#include <stdio.h>
#include <GL/glew.h>
#define ARRAY_LEN(arr) (sizeof ((arr)) / sizeof ((arr)[0]))
#if DEBUG
#define ASSERT(expr) if (!(expr)) { printf ("Assertion failed at %s %s(%d): %s\n", __FILE__, __func__, __LINE__, #expr); *(int *) 0 = 0; }
#define GLCALL(expr) expr; ASSERT (gl_check_error (#expr, __FILE__, __LINE__))
#else
#define ASSERT(expr)
#define GLCALL(expr) expr
#endif
bool
gl_check_error (char *func, char *file, int line)
{
bool ok = true;
GLenum error;
while ((error = glGetError ()) != GL_NO_ERROR)
{
printf ("[OpenGL Error] (%d) %s [%s:%d]\n", error, func, file, line);
ok = false;
}
return ok;
}
#endif /* COMMON_H */
|
illej/opengl-app | src/index_buffer.h | <filename>src/index_buffer.h
#ifndef INDEX_BUFFER_H
#define INDEX_BUFFER_H
#include "renderer.h"
struct index_buffer
{
unsigned int renderer_id;
unsigned int count;
};
void
ib_create (struct index_buffer *ib, unsigned int *data, unsigned int count)
{
ASSERT (sizeof (unsigned int) == sizeof (GLuint));
ib->count = count;
GLCALL (glGenBuffers (1, &ib->renderer_id));
GLCALL (glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ib->renderer_id));
GLCALL (glBufferData (GL_ELEMENT_ARRAY_BUFFER, ib->count * sizeof (unsigned int), data, GL_STATIC_DRAW));
}
void
ib_delete (struct index_buffer *ib)
{
GLCALL (glDeleteBuffers (1, &ib->renderer_id));
}
void
ib_bind (struct index_buffer *ib)
{
GLCALL (glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ib->renderer_id));
}
void
ib_unbind (void)
{
GLCALL (glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0));
}
inline unsigned int
ib_count_get (struct index_buffer *ib)
{
return ib->count;
}
#endif /* INDEX_BUFFER_H */
|
illej/opengl-app | tests/test_texture.h | <filename>tests/test_texture.h<gh_stars>0
#ifndef TEST_TEXTURE_H
#define TEST_TEXTURE_H
void test_texture_setup (struct test_data *t)
{
unsigned int i = 0;
t->vert_data[i++] = -0.5f; // bottom-left of view (x, y)
t->vert_data[i++] = -0.5f;
t->vert_data[i++] = 0.0f; // bottom-left of texture (u, v)
t->vert_data[i++] = 0.0f;
t->vert_data[i++] = 0.5f; // bottom-right (x, y)
t->vert_data[i++] = -0.5f;
t->vert_data[i++] = 1.0f; // bottom-right (u, v)
t->vert_data[i++] = 0.0f;
t->vert_data[i++] = 0.5f; // top-right (x, y)
t->vert_data[i++] = 0.5f;
t->vert_data[i++] = 1.0f; // top-right (u, v)
t->vert_data[i++] = 1.0f;
t->vert_data[i++] = -0.5f; // top-left (x, y)
t->vert_data[i++] = 0.5f;
t->vert_data[i++] = 0.0f; // top-left (u, v)
t->vert_data[i++] = 1.0f;
t->vert_size = i * sizeof (float);
va_create (&t->vao);
vb_create (&t->vbo, t->vert_data, t->vert_size);
vb_layout_create (&t->layout);
vb_layout_push_f (&t->layout, &t->vbo,2); // xy
vb_layout_push_f (&t->layout, &t->vbo, 2); // uv
va_add_vb_layout (&t->vao, &t->layout);
t->n_indices = 0;
t->indices[t->n_indices++] = 0;
t->indices[t->n_indices++] = 1;
t->indices[t->n_indices++] = 2;
t->indices[t->n_indices++] = 2;
t->indices[t->n_indices++] = 3;
t->indices[t->n_indices++] = 0;
ib_create (&t->ibo, t->indices, t->n_indices);
shader_create (&t->shader, "data/texture.vs", "data/texture.fs");
shader_bind (&t->shader);
t->mvp = m4_ortho (-2.0f, 2.0f, -1.5f, 1.5f, -1.0f, 1.0f);
shader_set_uniform_m4f (&t->shader, "u_mvp", &t->mvp.m[0][0]);
texture_create (&t->texture, "data/tifa.png");
texture_bind (&t->texture, 0);
shader_set_uniform_1i (&t->shader, "u_texture", 0);
}
void test_texture_update (struct test_data *t, float dt) {}
void test_texture_render (struct test_data *t)
{
renderer_clear ();
shader_bind (&t->shader);
shader_set_uniform_m4f (&t->shader, "u_mvp", &t->mvp.m[0][0]);
renderer_draw (&t->renderer, &t->vao, &t->ibo, &t->shader);
}
void test_texture_render_gui (struct test_data *t, struct nk_context *nk) {}
void
test_texture_teardown (struct test_data *t)
{
shader_delete (&t->shader);
}
#endif /* TEST_TEXTURE_H */
|
illej/opengl-app | src/main.c | <reponame>illej/opengl-app
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <GL/glew.h> // Always include before gl.h and glfw3.h
#include <SDL2/SDL.h>
#define MATH_3D_IMPLEMENTATION
#include <math_3d.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_SDL_GL3_IMPLEMENTATION
#include <nuklear.h>
#include <nuklear_sdl_gl3.h>
#define WIDTH 800
#define HEIGHT 600
#define DT 1000.0f / 60.0f
#define MAX_VERTEX_MEMORY 512 * 1024
#define MAX_ELEMENT_MEMORY 128 * 1024
#define kilobytes(x) ((x) * 1024)
#define megabytes(x) (kilobytes(x) * 1024)
#define gigabytes(x) (megabytes(x) * 1024)
#define terabytes(x) (gigabytes(x) * 1024)
#include "renderer.h"
#include <test.h>
#include <test.c>
/*
* TODO: replace 'unsigned int' with 'u32'
*/
static bool g__running = true;
static float g__triangle_vertices[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
struct cube
{
struct shader shader;
GLuint triangle_count;
GLuint vao;
GLuint vert_vbo;
GLuint colour_vbo;
};
typedef struct
{
float x, y;
} vec2_t;
static vec2_t vec2 (float x, float y) { return (vec2_t) { x, y }; }
typedef struct
{
unsigned int x, y, z;
} vec3u_t;
static vec3u_t vec3u (unsigned int x, unsigned int y, unsigned int z) { return (vec3u_t) { x, y, z }; }
struct input
{
vec3_t position;
float horizontal_angle;
float vertical_angle;
float initial_fov;
float speed;
float mouse_speed;
vec3_t direction;
vec3_t right;
vec3_t up;
mat4_t projection;
mat4_t model;
mat4_t view;
};
#define OBJ_MAX megabytes (6)
unsigned int vertex_indices[OBJ_MAX];
unsigned int uv_indices[OBJ_MAX];
unsigned int normal_indices[OBJ_MAX];
unsigned int vert_count = 0;
unsigned int uv_count = 0;
unsigned int normal_count = 0;
vec3_t temp_vertices[OBJ_MAX];
vec2_t temp_uvs[OBJ_MAX];
vec3_t temp_normals[OBJ_MAX];
unsigned int temp_vertex_count = 0;
unsigned int temp_uv_count = 0;
unsigned int temp_normal_count = 0;
vec3_t final_vertices[OBJ_MAX];
vec2_t final_uvs[OBJ_MAX];
vec3_t final_normals[OBJ_MAX];
unsigned int final_vert_count = 0;
unsigned int final_uv_count = 0;
unsigned int final_normal_count = 0;
static GLfloat cube_verts[] = {
-1.0f,-1.0f,-1.0f, // triangle 1 : begin
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f, // triangle 1 : end
1.0f, 1.0f,-1.0f, // triangle 2 : begin
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f, // triangle 2 : end
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f
};
static GLfloat cube_colours[] = {
0.583f, 0.771f, 0.014f,
0.609f, 0.115f, 0.436f,
0.327f, 0.483f, 0.844f,
0.822f, 0.569f, 0.201f,
0.435f, 0.602f, 0.223f,
0.310f, 0.747f, 0.185f,
0.597f, 0.770f, 0.761f,
0.559f, 0.436f, 0.730f,
0.359f, 0.583f, 0.152f,
0.483f, 0.596f, 0.789f,
0.559f, 0.861f, 0.639f,
0.195f, 0.548f, 0.859f,
0.014f, 0.184f, 0.576f,
0.771f, 0.328f, 0.970f,
0.406f, 0.615f, 0.116f,
0.676f, 0.977f, 0.133f,
0.971f, 0.572f, 0.833f,
0.140f, 0.616f, 0.489f,
0.997f, 0.513f, 0.064f,
0.945f, 0.719f, 0.592f,
0.543f, 0.021f, 0.978f,
0.279f, 0.317f, 0.505f,
0.167f, 0.620f, 0.077f,
0.347f, 0.857f, 0.137f,
0.055f, 0.953f, 0.042f,
0.714f, 0.505f, 0.345f,
0.783f, 0.290f, 0.734f,
0.722f, 0.645f, 0.174f,
0.302f, 0.455f, 0.848f,
0.225f, 0.587f, 0.040f,
0.517f, 0.713f, 0.338f,
0.053f, 0.959f, 0.120f,
0.393f, 0.621f, 0.362f,
0.673f, 0.211f, 0.457f,
0.820f, 0.883f, 0.371f,
0.982f, 0.099f, 0.879f
};
static void
handle_input (SDL_Window *window, struct input *input, SDL_Keycode key, float dt)
{
int x = 0;
int y = 0;
SDL_GetMouseState (&x, &y);
SDL_WarpMouseInWindow (window, WIDTH / 2, HEIGHT / 2);
input->horizontal_angle += input->mouse_speed * dt * (float) (WIDTH / 2 - x);
input->vertical_angle += input->mouse_speed * dt * (float) (HEIGHT / 2 - y);
input->direction = vec3 (cos (input->vertical_angle) * sin (input->horizontal_angle),
sin (input->vertical_angle),
cos (input->vertical_angle) * cos (input->horizontal_angle));
input->right = vec3 (sin (input->horizontal_angle - 3.14f / 2.0f),
0,
cos (input->horizontal_angle - 3.14f / 2.0f));
input->up = v3_cross (input->right, input->direction);
float step = dt * input->speed;
if (key == SDLK_w)
{
input->position = v3_add(input->position, v3_muls (input->direction, step));
}
if (key == SDLK_s)
{
input->position = v3_sub(input->position, v3_muls (input->direction, step));
}
if (key == SDLK_a)
{
input->position = v3_sub(input->position, v3_muls (input->right, step));
}
if (key == SDLK_d)
{
input->position = v3_add(input->position, v3_muls (input->right, step));
}
}
static void
cube_3d_setup (struct cube *cube, int width, int height)
{
printf ("creating vao\n");
GLuint vao;
GLCALL (glGenVertexArrays (1, &vao));
GLCALL (glBindVertexArray (vao));
cube->vao = vao;
printf ("creating vert vbo\n");
GLuint vert_vbo;
GLCALL (glGenBuffers (1, &vert_vbo));
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, vert_vbo));
GLCALL (glBufferData (GL_ARRAY_BUFFER, final_vert_count * sizeof (vec3_t), final_vertices, GL_STATIC_DRAW));
cube->vert_vbo = vert_vbo;
printf ("creating colour vbo\n");
GLuint colour_vbo;
GLCALL (glGenBuffers (1, &colour_vbo));
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, colour_vbo));
GLCALL (glBufferData (GL_ARRAY_BUFFER, final_uv_count * sizeof (vec2_t), final_uvs, GL_STATIC_DRAW));
cube->colour_vbo = colour_vbo;
printf ("enabling vao 0\n");
GLCALL (glEnableVertexAttribArray (0));
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, vert_vbo));
GLCALL (glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, 0));
printf ("enabling vao 1\n");
GLCALL (glEnableVertexAttribArray (1));
GLCALL (glBindBuffer (GL_ARRAY_BUFFER, colour_vbo));
GLCALL (glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, 0));
printf ("creating shader\n");
shader_create (&cube->shader, "data/cube.vs", "data/cube.fs");
shader_bind (&cube->shader);
cube->triangle_count = 12 * 3;
}
static void
cube_3d_render (struct cube *cube, struct input *input)
{
GLCALL (glEnable (GL_DEPTH_TEST));
GLCALL (glDepthFunc (GL_LESS));
GLCALL (glEnable (GL_CULL_FACE));
GLCALL (glClearColor (0.1f, 0.1f, 0.1f, 1.0f));
GLCALL (glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
GLCALL (glBindVertexArray (cube->vao));
shader_bind (&cube->shader);
mat4_t projection = m4_perspective (45.0f, (float) WIDTH / (float) HEIGHT, 0.1f, 100.0f);
mat4_t view = m4_look_at (input->position,
v3_add (input->position, input->direction),
input->up);
mat4_t model = m4_identity ();
mat4_t mvp = m4_mul(m4_mul (projection, view), model);
shader_set_uniform_m4f (&cube->shader, "u_mvp", &mvp.m[0][0]);
GLCALL (glDrawArrays (GL_TRIANGLES, 0, cube->triangle_count));
GLCALL (glDisable (GL_DEPTH_TEST));
}
static void
handle_os_events (struct nk_context *nk, SDL_Keycode *key)
{
SDL_Event event;
nk_input_begin (nk);
while (SDL_PollEvent(&event) != 0)
{
switch (event.type)
{
case SDL_QUIT:
{
// SDL_Log ("quit received");
g__running = false;
} break;
case SDL_KEYDOWN:
{
SDL_Keycode code = event.key.keysym.sym;
// SDL_Log ("keydown: %d", code);
if (code == SDLK_ESCAPE)
{
g__running = false;
}
*key = code;
} break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEMOTION:
{
// SDL_Log ("mouse input");
} break;
case SDL_TEXTINPUT:
{
// SDL_Log("TEXTINPUT event received");
} break;
case SDL_TEXTEDITING:
{
// SDL_Log("TEXTEDITING event received");
} break;
}
nk_sdl_handle_event (&event);
}
nk_input_end (nk);
}
static void
load_obj (char *file)
{
FILE *fp = fopen (file, "r");
if (fp)
{
while (true)
{
char word[256];
int res = fscanf (fp, "%s", word);
if (res == EOF) break;
if (strcmp (word, "v") == 0)
{
vec3_t v;
fscanf (fp, "%f %f %f\n", &v.x, &v.y, &v.z);
ASSERT (temp_vertex_count + 1 < ARRAY_LEN (temp_vertices));
temp_vertices[temp_vertex_count++] = v;
}
else if (strcmp (word, "vt") == 0)
{
vec2_t v;
fscanf (fp, "%f %f\n", &v.x, &v.y);
ASSERT (temp_uv_count + 1 < ARRAY_LEN (temp_uvs));
temp_uvs[temp_uv_count++] = v;
}
else if (strcmp (word, "vn") == 0)
{
vec3_t v;
fscanf (fp, "%f %f %f\n", &v.x, &v.y, &v.z);
ASSERT (temp_normal_count + 1 < ARRAY_LEN (temp_normals));
temp_normals[temp_normal_count++] = v;
}
else if (strcmp (word, "f") == 0)
{
unsigned int vert_index[3];
unsigned int uv_index[3];
unsigned int normal_index[3];
int matches = fscanf (fp, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
&vert_index[0], &uv_index[0], &normal_index[0],
&vert_index[1], &uv_index[1], &normal_index[1],
&vert_index[2], &uv_index[2], &normal_index[2]);
ASSERT (matches == 9);
if (vert_count + 1 >= ARRAY_LEN (vertex_indices))
{
printf ("reached max vert_count: %u\n", vert_count);
break;
}
if (uv_count + 1 >= ARRAY_LEN (uv_indices))
{
printf ("reached max uv_count: %u\n", uv_count);
break;
}
if (normal_count + 1 >= ARRAY_LEN (normal_indices))
{
printf ("reach max normal_count: %u\n", normal_count);
break;
}
vertex_indices[vert_count++] = vert_index[0];
vertex_indices[vert_count++] = vert_index[1];
vertex_indices[vert_count++] = vert_index[2];
uv_indices[uv_count++] = uv_index[0];
uv_indices[uv_count++] = uv_index[1];
uv_indices[uv_count++] = uv_index[2];
normal_indices[normal_count++] = normal_index[0];
normal_indices[normal_count++] = normal_index[1];
normal_indices[normal_count++] = normal_index[2];
}
}
printf ("finished reading\n", file);
printf (" vert_count : %u\n", vert_count);
printf (" uv_count : %u\n", uv_count);
printf (" normal_count : %u\n", normal_count);
printf ("parsing data\n");
for (unsigned int i = 0; i < vert_count; i++)
{
unsigned int vert_index = vertex_indices[i];
vec3_t vertex = temp_vertices[vert_index - 1];
// printf (" adding [%u] %f %f %f\n", i, vertex.x, vertex.y, vertex.z);
if (final_vert_count + 1 >= ARRAY_LEN (final_vertices))
{
printf ("max final verts reached: %u\n", final_vert_count);
ASSERT (!"blah verts");
}
final_vertices[final_vert_count++] = vertex;
}
for (unsigned int i = 0; i < uv_count; i++)
{
unsigned int uv_index = uv_indices[i];
vec2_t uv = temp_uvs[uv_index - 1];
final_uvs[final_uv_count++] = uv;
}
for (unsigned int i = 0; i < normal_count; i++)
{
unsigned int normal_index = normal_indices[i];
vec3_t normal = temp_normals[normal_index - 1];
final_normals[final_normal_count++] = normal;
}
printf ("finished parsing\n");
printf (" final_vert_count : %u\n", final_vert_count);
printf (" final_uv_count : %u\n", final_uv_count);
printf (" final_normal_count : %u\n", final_normal_count);
fclose (fp);
}
else
{
ASSERT (!"failed to read file");
}
}
int
main (int argc, char **argv)
{
/* Init SDL */
SDL_Init (SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute (SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
SDL_Window *window = SDL_CreateWindow ("opengl-app",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WIDTH, HEIGHT,
SDL_WINDOW_OPENGL);
SDL_GLContext *glctx = SDL_GL_CreateContext (window);
SDL_GL_SetSwapInterval (1); // vsync
/* Init OpenGL */
ASSERT (glewInit () == GLEW_OK);
/* Init GUI */
struct nk_context *nkctx = nk_sdl_init (window);
struct nk_colorf bg;
{
struct nk_font_atlas *atlas;
nk_sdl_font_stash_begin (&atlas);
nk_sdl_font_stash_end ();
bg.r = 0.10f;
bg.g = 0.18f;
bg.b = 0.24f;
bg.a = 1.0f;
}
printf ("hello opengl (%s)\n", glGetString (GL_VERSION));
struct input input = {0};
input.position = vec3 (0, 0, 5);
input.horizontal_angle = 3.14f;
input.initial_fov = 45.0f;
input.speed = 0.005f;
input.mouse_speed = 0.0005f;
load_obj ("data/cube.obj");
struct cube cube = {0};
cube_3d_setup (&cube, WIDTH, HEIGHT);
while (g__running)
{
SDL_Keycode key = 0;
handle_os_events (nkctx, &key);
handle_input (window, &input, key, DT);
cube_3d_render (&cube, &input);
SDL_GL_SwapWindow (window);
}
nk_sdl_shutdown ();
SDL_GL_DeleteContext (glctx);
SDL_DestroyWindow (window);
SDL_Quit ();
return 0;
}
|
illej/opengl-app | src/vertex_array.h | <filename>src/vertex_array.h
#ifndef VERTEX_ARRAY_H
#define VERTEX_ARRAY_H
#include "renderer.h"
struct vertex_array
{
unsigned int renderer_id;
};
static void
va_create (struct vertex_array *vao)
{
GLCALL (glGenVertexArrays (1, &vao->renderer_id));
}
static void
va_delete (struct vertex_array *vao)
{
GLCALL (glDeleteVertexArrays (1, &vao->renderer_id));
}
static void
va_bind (struct vertex_array *vao)
{
GLCALL (glBindVertexArray (vao->renderer_id));
}
static void
va_unbind (void)
{
GLCALL (glBindVertexArray (0));
}
static void
va_add_vb_layout (struct vertex_array *vao, struct vb_layout *layout)
{
unsigned int element_count = layout->element_count;
unsigned int offset = 0;
va_bind (vao);
for (unsigned int i = 0; i < element_count; i++)
{
struct vb_element *e = &layout->elements[i];
vb_bind (e->vbo);
printf ("enabling vertex attrib array index=%u vbo=%u\n", i, e->vbo->renderer_id);
printf (" count=%u type=%u norm=%u stride=%u offset=%u\n",
e->count, e->type, e->normalised, vb_layout_stride_get (layout), offset);
GLCALL (glEnableVertexAttribArray (i));
GLCALL (glVertexAttribPointer (i, e->count, e->type, e->normalised, 0, 0));
//GLCALL (glVertexAttribPointer (i, e->count, e->type, e->normalised, vb_layout_stride_get (layout),
// (GLvoid *) ((char *) 0 + offset)));
offset += e->count * vb_element_type_size (e->type);
}
}
#endif /* VERTEX_ARRAY_H */
|
illej/opengl-app | tests/test_clear_colour.h | <gh_stars>0
#ifndef TEST_CLEAR_COLOUR_H
#define TEST_CLEAR_COLOUR_H
#include "test.h"
void
test_clear_colour_setup (struct test_data *t)
{
unsigned int i = 0;
t->colour[i++] = 0.2f;
t->colour[i++] = 0.3f;
t->colour[i++] = 0.8f;
t->colour[i++] = 1.0f;
}
void
test_clear_colour_update (struct test_data *t, float dt)
{
}
void
test_clear_colour_render (struct test_data *t)
{
GLCALL (glClearColor (t->colour[0], t->colour[1], t->colour[2], t->colour[3]));
GLCALL (glClear (GL_COLOR_BUFFER_BIT));
}
void
test_clear_colour_render_gui (struct test_data *t, struct nk_context *ctx)
{
if (nk_begin (ctx, "Clear Colour", nk_rect (50, 50, 220, 220),
NK_WINDOW_MOVABLE | NK_WINDOW_BORDER | NK_WINDOW_CLOSABLE))
{
nk_layout_row_begin (ctx, NK_STATIC, 30, 2);
{
nk_layout_row_push (ctx, 50);
nk_label (ctx, "R:", NK_TEXT_LEFT);
nk_layout_row_push (ctx, 110);
nk_slider_float (ctx, 0, &t->colour[0], 1.0f, 0.1f);
}
nk_layout_row_end (ctx);
nk_layout_row_begin (ctx, NK_STATIC, 30, 2);
{
nk_layout_row_push (ctx, 50);
nk_label (ctx, "G:", NK_TEXT_LEFT);
nk_layout_row_push (ctx, 110);
nk_slider_float (ctx, 0, &t->colour[1], 1.0f, 0.1f);
}
nk_layout_row_end (ctx);
nk_layout_row_begin (ctx, NK_STATIC, 30, 2);
{
nk_layout_row_push (ctx, 50);
nk_label (ctx, "B:", NK_TEXT_LEFT);
nk_layout_row_push (ctx, 110);
nk_slider_float (ctx, 0, &t->colour[2], 1.0f, 0.1f);
}
nk_layout_row_end (ctx);
nk_layout_row_begin (ctx, NK_STATIC, 30, 2);
{
nk_layout_row_push (ctx, 50);
nk_label (ctx, "A:", NK_TEXT_LEFT);
nk_layout_row_push (ctx, 110);
nk_slider_float (ctx, 0, &t->colour[3], 1.0f, 0.1f);
}
nk_layout_row_end (ctx);
}
nk_end (ctx);
nk_sdl_render (NK_ANTI_ALIASING_ON, MAX_VERTEX_MEMORY, MAX_ELEMENT_MEMORY);
}
void test_clear_colour_teardown (struct test_data *t) {}
#endif /* TEST_CLEAR_COLOUR_H */
|
illej/opengl-app | tests/test_3d_cube.h | #ifndef TEST_3D_CUBE_H
#define TEST_3D_CUBE_H
static float g_cube_vert_data[] = {
-1.0f,-1.0f,-1.0f, // triangle 1 : begin
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f, // triangle 1 : end
1.0f, 1.0f,-1.0f, // triangle 2 : begin
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f, // triangle 2 : end
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f
};
static float g_cube_colour_data[] = {
0.583f, 0.771f, 0.014f,
0.609f, 0.115f, 0.436f,
0.327f, 0.483f, 0.844f,
0.822f, 0.569f, 0.201f,
0.435f, 0.602f, 0.223f,
0.310f, 0.747f, 0.185f,
0.597f, 0.770f, 0.761f,
0.559f, 0.436f, 0.730f,
0.359f, 0.583f, 0.152f,
0.483f, 0.596f, 0.789f,
0.559f, 0.861f, 0.639f,
0.195f, 0.548f, 0.859f,
0.014f, 0.184f, 0.576f,
0.771f, 0.328f, 0.970f,
0.406f, 0.615f, 0.116f,
0.676f, 0.977f, 0.133f,
0.971f, 0.572f, 0.833f,
0.140f, 0.616f, 0.489f,
0.997f, 0.513f, 0.064f,
0.945f, 0.719f, 0.592f,
0.543f, 0.021f, 0.978f,
0.279f, 0.317f, 0.505f,
0.167f, 0.620f, 0.077f,
0.347f, 0.857f, 0.137f,
0.055f, 0.953f, 0.042f,
0.714f, 0.505f, 0.345f,
0.783f, 0.290f, 0.734f,
0.722f, 0.645f, 0.174f,
0.302f, 0.455f, 0.848f,
0.225f, 0.587f, 0.040f,
0.517f, 0.713f, 0.338f,
0.053f, 0.959f, 0.120f,
0.393f, 0.621f, 0.362f,
0.673f, 0.211f, 0.457f,
0.820f, 0.883f, 0.371f,
0.982f, 0.099f, 0.879f
};
void test_3d_cube_setup (struct test_data *t)
{
va_create (&t->vao);
vb_layout_create (&t->layout);
vb_create (&t->vert_vbo, g_cube_vert_data, sizeof (g_cube_vert_data));
printf ("vert_vbo id=%u\n", t->vert_vbo.renderer_id);
vb_layout_push_f (&t->layout, &t->vert_vbo, 3); // xyz
vb_create (&t->colour_vbo, g_cube_colour_data, sizeof (g_cube_colour_data));
printf ("colour_vbo id=%u\n", t->colour_vbo.renderer_id);
vb_layout_push_f (&t->layout, &t->colour_vbo, 3); // rgb
va_add_vb_layout (&t->vao, &t->layout);
shader_create (&t->shader, "data/cube.vs", "data/cube.fs");
shader_bind (&t->shader);
mat4_t projection = m4_perspective (45.0f, 800.0f / 600.0f, 0.01f, 100.0f);
mat4_t view = m4_look_at (vec3 (4, 3, 3),
vec3 (0, 0, 0),
vec3 (0, 1, 0));
mat4_t model = m4_identity ();
t->mvp = m4_mul (m4_mul (projection, view), model);
shader_set_uniform_m4f (&t->shader, "u_mvp", &t->mvp.m[0][0]);
}
void test_3d_cube_update (struct test_data *t, float dt) {}
void test_3d_cube_render (struct test_data *t)
{
renderer_clear ();
shader_bind (&t->shader);
shader_set_uniform_m4f (&t->shader, "u_mvp", &t->mvp.m[0][0]);
va_bind (&t->vao);
GLCALL (glDrawArrays (GL_TRIANGLES, 0, 12 * 3));
}
void test_3d_cube_render_gui (struct test_data *t, struct nk_context *nk) {}
void
test_3d_cube_teardown (struct test_data *t)
{
shader_delete (&t->shader);
}
#endif /* TEST_3D_CUBE_H */
|
illej/opengl-app | tests/test.h | #ifndef TEST_H
#define TEST_H
//#include "renderer.h"
//
enum test_type
{
TEST_INALID = 0,
TEST_CLEAR_COLOUR,
TEST_TEXTURE,
TEST_3D_CUBE,
};
struct test_data
{
enum test_type type;
/* CLEAR COLOUR */
float colour[4];
/* TEXTURE */
float vert_data[16];
unsigned int vert_size;
unsigned int indices[6];
unsigned int n_indices;
struct vertex_array vao;
struct vertex_buffer vbo;
struct vb_layout layout;
struct index_buffer ibo;
struct shader shader;
mat4_t mvp;
struct texture texture;
struct renderer renderer;
/* 3D CUBE */
struct vertex_buffer vert_vbo;
struct vertex_buffer colour_vbo;
struct vb_layout layout_vert;
struct vb_layout layout_colour;
};
void test_setup (enum test_type type, struct test_data *d);
void test_update (struct test_data *t, float dt);
void test_render (struct test_data *t);
void test_render_gui (struct test_data *t, struct nk_context *nk);
void test_teardown (struct test_data *t);
#endif /* TEST_H */
|
KeilChris/VHT | interface/include/arm_vsocket.h | /*
* Copyright (c) 2021-2022 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Virtual Socket (VSocket) - IoT Socket
*/
#ifndef __ARM_VSOCKET_H
#define __ARM_VSOCKET_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/**** VSocket function identifiers ****/
#define VSOCKET_CREATE 1 ///< iotSocketCreate
#define VSOCKET_BIND 2 ///< iotSocketBind
#define VSOCKET_LISTEN 3 ///< iotSocketListen
#define VSOCKET_ACCEPT 4 ///< iotSocketAccept
#define VSOCKET_CONNECT 5 ///< iotSocketConnect
#define VSOCKET_RECV 6 ///< iotSocketRecv
#define VSOCKET_RECV_FROM 7 ///< iotSocketRecvFrom
#define VSOCKET_SEND 8 ///< iotSocketSend
#define VSOCKET_SEND_TO 9 ///< iotSocketSendTo
#define VSOCKET_GET_SOCK_NAME 10 ///< iotSocketGetSockName
#define VSOCKET_GET_PEER_NAME 11 ///< iotSocketGetPeerName
#define VSOCKET_GET_OPT 12 ///< iotSocketGetOpt
#define VSOCKET_SET_OPT 13 ///< iotSocketSetOpt
#define VSOCKET_CLOSE 14 ///< iotSocketClose
#define VSOCKET_GET_HOST_BY_NAME 15 ///< iotSocketGetHostByName
/**
\brief I/O structure for iotSocketCreate.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketCreate
struct {
int32_t af; /*!< address family */
int32_t type; /*!< socket type */
int32_t protocol; /*!< socket protocol */
} param;
} vSocketCreateIO_t;
/**
\brief I/O structure for iotSocketBind.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketBind
struct {
int32_t socket; /*!< socket identification number */
const uint8_t * ip; /*!< pointer to local IP address */
uint32_t ip_len; /*!< length of 'ip' address in bytes */
uint16_t port; /*!< local port number */
uint16_t padding;
} param;
} vSocketBindIO_t;
/**
\brief I/O structure for iotSocketListen.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketListen
struct {
int32_t socket; /*!< socket identification number */
int32_t backlog; /*!< number of connection requests that can be queued */
} param;
} vSocketListenIO_t;
/**
\brief I/O structure for iotSocketAccept.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketAccept
struct {
int32_t socket; /*!< socket identification number */
uint8_t * ip; /*!< pointer to buffer where address of connecting socket shall be returned (NULL for none) */
uint32_t * ip_len; /*!< pointer to length of 'ip' (or NULL if 'ip' is NULL) */
uint16_t * port; /*!< pointer to buffer where port of connecting socket shall be returned (NULL for none) */
} param;
} vSocketAcceptIO_t;
/**
\brief I/O structure for iotSocketConnect.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketConnect
struct {
int32_t socket; /*!< socket identification number */
const uint8_t * ip; /*!< pointer to remote IP address */
uint32_t ip_len; /*!< length of 'ip' address in bytes */
uint16_t port; /*!< remote port number */
uint16_t padding;
} param;
} vSocketConnectIO_t;
/**
\brief I/O structure for iotSocketRecv.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketRecv
struct {
int32_t socket; /*!< socket identification number */
void * buf; /*!< pointer to buffer where data should be stored */
uint32_t len; /*!< length of buffer (in bytes) */
} param;
} vSocketRecvIO_t;
/**
\brief I/O structure for iotSocketRecvFrom.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketRecvFrom
struct {
int32_t socket; /*!< socket identification number */
void * buf; /*!< pointer to buffer where data should be stored */
uint32_t len; /*!< length of buffer (in bytes) */
uint8_t * ip; /*!< pointer to buffer where remote source address shall be returned (NULL for none) */
uint32_t * ip_len; /*!< pointer to length of 'ip' (or NULL if 'ip' is NULL) */
uint16_t * port; /*!< pointer to buffer where remote source port shall be returned (NULL for none) */
} param;
} vSocketRecvFromIO_t;
/**
\brief I/O structure for iotSocketSend.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketSend
struct {
int32_t socket; /*!< socket identification number */
const void * buf; /*!< pointer to buffer containing data to send */
uint32_t len; /*!< length of data (in bytes) */
} param;
} vSocketSendIO_t;
/**
\brief I/O structure for iotSocketSendTo.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketSendTo
struct {
int32_t socket; /*!< socket identification number */
const void * buf; /*!< pointer to buffer containing data to send */
uint32_t len; /*!< length of data (in bytes) */
const uint8_t * ip; /*!< pointer to remote destination IP address */
uint32_t ip_len; /*!< length of 'ip' address in bytes */
uint16_t port; /*!< remote destination port number */
uint16_t padding;
} param;
} vSocketSendToIO_t;
/**
\brief I/O structure for iotSocketGetSockName.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketGetSockName
struct {
int32_t socket; /*!< socket identification number */
uint8_t * ip; /*!< pointer to buffer where local address shall be returned (NULL for none) */
uint32_t * ip_len; /*!< pointer to length of 'ip' (or NULL if 'ip' is NULL) */
uint16_t * port; /*!< pointer to buffer where local port shall be returned (NULL for none) */
} param;
} vSocketGetSockNameIO_t;
/**
\brief I/O structure for iotSocketGetPeerName.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketGetPeerName
struct {
int32_t socket; /*!< socket identification number */
uint8_t * ip; /*!< pointer to buffer where remote address shall be returned (NULL for none) */
uint32_t * ip_len; /*!< pointer to length of 'ip' (or NULL if 'ip' is NULL) */
uint16_t * port; /*!< pointer to buffer where remote port shall be returned (NULL for none) */
} param;
} vSocketGetPeerNameIO_t;
/**
\brief I/O structure for iotSocketGetOpt.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketGetOpt
struct {
int32_t socket; /*!< socket identification number */
int32_t opt_id; /*!< option identifier */
void * opt_val; /*!< pointer to the buffer that will receive the option value */
uint32_t * opt_len; /*!< pointer to length of the option value */
} param;
} vSocketGetOptIO_t;
/**
\brief I/O structure for iotSocketSetOpt.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketSetOpt
struct {
int32_t socket; /*!< socket identification number */
int32_t opt_id; /*!< option identifier */
const void * opt_val; /*!< pointer to the option value */
uint32_t opt_len; /*!< length of the option value in bytes */
} param;
} vSocketSetOptIO_t;
/**
\brief I/O structure for iotSocketClose.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketClose
struct {
int32_t socket; /*!< socket identification number */
} param;
} vSocketCloseIO_t;
/**
\brief I/O structure for iotSocketGetHostByName.
*/
typedef struct {
int32_t ret_val; /*!< return value */
/// arguments for iotSocketGetHostByName
struct {
const char * name; /*!< host name */
uint32_t len; /*!< length of host name */
int32_t af; /*!< address family */
uint8_t * ip; /*!< pointer to buffer where resolved IP address shall be returned */
uint32_t * ip_len; /*!< pointer to length of 'ip' */
} param;
} vSocketGetHostByNameIO_t;
/**
\brief Structure type to access the VSocket.
*/
typedef struct
{
volatile uint32_t reserved;
volatile vSocketCreateIO_t * vSocketCreateIO; /*!< Structure for socket create */
volatile vSocketBindIO_t * vSocketBindIO; /*!< Structure for socket bind */
volatile vSocketListenIO_t * vSocketListenIO; /*!< Structure for socket listen */
volatile vSocketAcceptIO_t * vSocketAcceptIO; /*!< Structure for socket accept */
volatile vSocketConnectIO_t * vSocketConnectIO; /*!< Structure for socket connect */
volatile vSocketRecvIO_t * vSocketRecvIO; /*!< Structure for socket receive */
volatile vSocketRecvFromIO_t * vSocketRecvFromIO; /*!< Structure for socket receive from */
volatile vSocketSendIO_t * vSocketSendIO; /*!< Structure for socket send */
volatile vSocketSendToIO_t * vSocketSendToIO; /*!< Structure for socket send to */
volatile vSocketGetSockNameIO_t * vSocketGetSockNameIO; /*!< Structure for get socket name */
volatile vSocketGetPeerNameIO_t * vSocketGetPeerNameIO; /*!< Structure for get peer name */
volatile vSocketGetOptIO_t * vSocketGetOptIO; /*!< Structure for socket get options */
volatile vSocketSetOptIO_t * vSocketSetOptIO; /*!< Structure for socket set options */
volatile vSocketCloseIO_t * vSocketCloseIO; /*!< Structure for socket close */
volatile vSocketGetHostByNameIO_t * vSocketGetHostByNameIO; /*!< Structure for socket get host by name */
} ARM_VSocket_Type;
// Memory mapping of VSocket peripheral
#define ARM_VSOCKET_BASE (0x4FEE0000UL) /*!< VSocket Base Address */
#define ARM_VSOCKET ((ARM_VSocket_Type *)ARM_VSOCKET_BASE) /*!< VSocket struct */
#ifdef __cplusplus
}
#endif
#endif /* __ARM_VSOCKET_H */
|
danielsundfeld/cuda_sankoff | src/read_fasta.h | /*!
* \author <NAME>
* \copyright MIT License
*/
#ifndef _READ_FASTA_FILE
#define _READ_FASTA_FILE
#include <string>
int read_fasta_file(const std::string &name, const int &check = 0);
#endif
|
danielsundfeld/cuda_sankoff | src/Cost.h | <reponame>danielsundfeld/cuda_sankoff
#ifndef _COST_H
#define _COST_H
#ifdef __CUDACC__
#define CUDAFLAGS __device__ __host__
#else
#define CUDAFLAGS
#endif
#define _RIBOSUM_8560 1
class Cost {
public:
static constexpr float gap = -13;
static constexpr float unpaired = 5;
static constexpr float match = 0.05;
CUDAFLAGS static int base_score(const char &a, const char &b); //'alpha' score
CUDAFLAGS static float match_score(const char &a, const char &b); // 'beta' score
CUDAFLAGS static float compensation_score(const char &a1, const char &a2, const char &b1, const char &b2); // 'tau' score
};
CUDAFLAGS inline int Cost::base_score(const char &a, const char &b)
{
/* In the BP scores, this function only checks if it is a base pair */
if ((a == 'C' && b == 'G') ||
(a == 'G' && b == 'C') ||
(a == 'A' && b == 'U') ||
(a == 'U' && b == 'A') ||
(a == 'G' && b == 'U') ||
(a == 'U' && b == 'G')
)
return 1;
return 0;
}
#ifdef _RIBOSUM_8560
CUDAFLAGS inline float Cost::match_score(const char &a, const char &b)
{
int x, y;
const float ribosum_85_60_substitution[4][4] = {
//A C G U
{ 2.22, -1.86, -1.46, -1.39 }, //A
{-1.86, 1.16, -2.48, -1.05 }, //C
{-1.46, -2.48, 1.03, -1.74 }, //G
{-1.39, -1.05, -1.74, 1.65 }, //U
};
if (a == 'A')
x = 0;
else if (a == 'C')
x = 1;
else if (a == 'G')
x = 2;
else if (a == 'U')
x = 3;
else
return -1024;
if (b == 'A')
y = 0;
else if (b == 'C')
y = 1;
else if (b == 'G')
y = 2;
else if (b == 'U')
y = 3;
else
return -1024;
return ribosum_85_60_substitution[x][y];
}
CUDAFLAGS inline float Cost::compensation_score(const char &a1, const char &a2, const char &b1, const char &b2)
{
const float ribosum_85_60_compensation[16][16] = {
// AA AC, AG, AU, CA, CC, CG, CU, GA, GC, GG, GU, UA, UC, UG, UU
{ -2.49, -7.04, -8.24, -4.32, -8.84, -14.37, -4.68, -12.64, -6.86, -5.03, -8.39, -5.84, -4.01, -11.32, -6.16, -9.05}, //AA
{ -7.04, -2.11, -8.89, -2.04, -9.37, -9.08, -5.86, -10.45, -9.73, -3.81, -11.05, -4.72 , -5.33, -8.67, -6.93, -7.83}, //AC
{ -8.24, -8.89, -0.80, -5.13, -10.41, -14.53, -4.57, -10.14, -8.61, -5.77, -5.38 , -6.60 , -5.43, -8.87, -5.94 , -11.07}, //AG
{ -4.32, -2.04, -5.13, 4.49, -5.56, -6.71, 1.67, -5.17, -5.33, 2.70, -5.61 , 0.59 , 1.61, -4.81 , -0.51, -2.98}, //AU
{ -8.84, -9.37, -10.41, -5.56, -5.13, -10.45, -3.57, -8.49, -7.98, -5.95, -11.36, -7.93 , -2.42, -7.08, -5.63, -8.39}, //CA
{-14.37, -9.08, -14.53, -6.71, -10.45, -3.59, -5.71, -5.77, -12.43, -3.70, -12.58, -7.88, -6.88, -7.40, -8.41, -5.41}, //CC
{ -4.68, -5.86, -4.57, 1.67, -3.57, -5.71, 5.36, -4.96, -6.00, 2.11, -4.66, -0.27, 2.75, -4.91, 1.32 , -3.67}, //CG
{-12.64, -10.45, -10.14, -5.17 , -8.49, -5.77, -4.96, -2.28, -7.71, -5.84, -13.69, -5.61, -4.72, -3.83, -7.36, -5.21}, //CU
{-6.86 , -9.73, -8.61, -5.33, -7.98,-12.43 , -6.00, -7.71, -1.05, -4.88, -8.67, -6.10 , -5.85, -6.63, -7.55, -11.54}, //GA
{ -5.03, -3.81, -5.77, 2.70, -5.95, -3.70, 2.11, -5.84, -4.88, 5.62, -4.13, 1.21 , 1.60 , -4.49, -0.08, -3.90}, //GC
{ -8.39, -11.05, -5.38, -5.61, -11.36, -12.58, -4.66, -13.69, -8.67, -4.13, -1.98, -5.77, -5.75, -12.01, -4.27, -10.79}, //GG
{ -5.84, -4.72, -6.60, 0.59, -7.93, -7.88, -0.27 , -5.61, -6.10, 1.21, -5.77, 3.47, -0.57, -5.30, -2.09, -4.45}, //GU
{ -4.01, -5.33, -5.43, 1.61, -2.42, -6.88, 2.75, -4.72, -5.85, 1.60, -5.75, -0.57, 4.97, -2.98, 1.14, -3.39}, //UA
{-11.32, -8.67, -8.87, -4.81, -7.08, -7.40, -4.91, -3.83, -6.63, -4.49, -12.01, -5.30, -2.98, -3.21, -4.76, -5.97}, //UC
{ -6.16, -6.93, -5.94, -0.51, -5.63, -8.41, 1.32, -7.36, -7.55, -0.08, -4.27, -2.09, 1.14, -4.76, 3.36, -4.28}, //UG
{ -9.05, -7.83, -11.07, -2.98, -8.39, -5.41, -3.67, -5.21, -11.54, -3.90, -10.79, -4.45, -3.39, -5.97, -4.28, -0.02}, //UU
};
int x, y;
if (a1 == 'A' && a2 == 'A')
x = 0;
else if (a1 == 'A' && a2 == 'C')
x = 1;
else if (a1 == 'A' && a2 == 'G')
x = 2;
else if (a1 == 'A' && a2 == 'U')
x = 3;
else if (a1 == 'C' && a2 == 'A')
x = 4;
else if (a1 == 'C' && a2 == 'C')
x = 5;
else if (a1 == 'C' && a2 == 'G')
x = 6;
else if (a1 == 'C' && a2 == 'U')
x = 7;
else if (a1 == 'G' && a2 == 'A')
x = 8;
else if (a1 == 'G' && a2 == 'C')
x = 9;
else if (a1 == 'G' && a2 == 'G')
x = 10;
else if (a1 == 'G' && a2 == 'U')
x = 11;
else if (a1 == 'U' && a2 == 'A')
x = 12;
else if (a1 == 'U' && a2 == 'C')
x = 13;
else if (a1 == 'U' && a2 == 'G')
x = 14;
else if (a1 == 'U' && a2 == 'U')
x = 15;
else
return -1024;
if (b1 == 'A' && b2 == 'A')
y = 0;
else if (b1 == 'A' && b2 == 'C')
y = 1;
else if (b1 == 'A' && b2 == 'G')
y = 2;
else if (b1 == 'A' && b2 == 'U')
y = 3;
else if (b1 == 'C' && b2 == 'A')
y = 4;
else if (b1 == 'C' && b2 == 'C')
y = 5;
else if (b1 == 'C' && b2 == 'G')
y = 6;
else if (b1 == 'C' && b2 == 'U')
y = 7;
else if (b1 == 'G' && b2 == 'A')
y = 8;
else if (b1 == 'G' && b2 == 'C')
y = 9;
else if (b1 == 'G' && b2 == 'G')
y = 10;
else if (b1 == 'G' && b2 == 'U')
y = 11;
else if (b1 == 'U' && b2 == 'A')
y = 12;
else if (b1 == 'U' && b2 == 'C')
y = 13;
else if (b1 == 'U' && b2 == 'G')
y = 14;
else if (b1 == 'U' && b2 == 'U')
y = 15;
else
return -1024;
return ribosum_85_60_compensation[x][y];
}
#else
CUDAFLAGS inline float Cost::match_score(const char &a, const char &b)
{
if (a == b)
return Cost::match;
return 0;
}
CUDAFLAGS inline float Cost::compensation_score(const char &a1, const char &a2, const char &b1, const char &b2)
{
// Give a score if they have the same structure
if (base_score(a1, a2) == base_score(b1, b2))
return Cost::match;
return 0; // Otherwise, no donuts for you
}
#endif
#endif
|
danielsundfeld/cuda_sankoff | src/DPMatrix_GPU.h | <reponame>danielsundfeld/cuda_sankoff<filename>src/DPMatrix_GPU.h
#ifndef _DPMATRIX_GPU_H
#define _DPMATRIX_GPU_H
#include "dp_matrix_cell.h"
#define MAX_SEQ_SIZE 1024
struct sequences {
char s1[MAX_SEQ_SIZE];
int s1_l;
char s2[MAX_SEQ_SIZE];
int s2_l;
};
long long int dp_matrix_calc_total_size(long long int s1, long long int s2);
#ifdef __CUDACC__
__device__ __host__ int dp_matrix_calc_delta(int i, int j, int k, int l, sequences* seq_ctx);
__device__ __host__ dp_matrix_cell dp_matrix_get_pos(dp_matrix_cell *dp_matrix, const int &i, const int &j, const int &k, const int &l, sequences* seq_ctx);
__device__ __host__ void dp_matrix_put_pos(dp_matrix_cell *dp_matrix, const int &i, const int &j, const int &k, const int &l, const float &val, sequences* seq_ctx);
__host__ float dp_matrix_get_val(dp_matrix_cell *dp_matrix, const int &i, const int &j, const int &k, const int &l, sequences* seq_ctx);
__device__ __host__ inline bool dp_matrix_check_border(const int &i, const int &j, const int &k, const int &l, sequences* seq_ctx)
{
const int &s1_l = seq_ctx->s1_l;
const int &s2_l = seq_ctx->s2_l;
if (j < i)
return false;
if (l < k)
return false;
if (i < 0 || j < 0 || k < 0 || l < 0)
return false;
if (i >= s1_l || j >= s1_l || k >= s2_l || l >= s2_l)
return false;
return true;
}
#endif
#endif
|
danielsundfeld/cuda_sankoff | src/sankoff_args.h | <filename>src/sankoff_args.h
#ifndef _SANKOFF_ARGS
#define _SANKOFF_ARGS
int load_args(int argc, char *argv[], int *threads_num = 0);
#endif
|
danielsundfeld/cuda_sankoff | src/dp_matrix_cell.h | <gh_stars>0
#ifndef _DP_MATRIX_CELL_H
#define _DP_MATRIX_CELL_H
struct dp_matrix_cell {
float score;
char parent;
};
enum Parent {
NullParent = 0,
FirstCell,
GapI,
GapK,
GapJ,
GapL,
UnpairedIK,
UnpairedJL,
PairedGapS1,
PairedGapS2,
Paired,
Multibranch,
LastParent
};
const char parent_str[][LastParent] = {
"NullParent",
"FirstCell",
"GapI",
"GapK",
"GapJ",
"GapL",
"UnpairedIK",
"UnpairedJL",
"PairedGapS1",
"PairedGapS2",
"Paired",
"Multibranch",
"LastParent"
};
#endif
|
danielsundfeld/cuda_sankoff | src/Sankoff_GPU.h | #ifndef _SANKOFF_GPU_H
#define _SANKOFF_GPU_H
#include <string>
#include "bp_probs.h"
#include "dp_matrix_cell.h"
#include "DPMatrix_GPU.h"
class Sankoff_GPU {
public:
Sankoff_GPU(const std::string &seq1, const std::string &seq2);
virtual ~Sankoff_GPU();
int diag_sankoff(); //Run a pure sankoff algorithm
private:
#ifdef __CUDACC__
void check_kernel_execution();
void check_gpu_code(cudaError_t code);
#endif
void backtrace();
//host members
sequences h_seq_ctx;
struct bp_prob *h_bp1, *h_bp2;
//device_members
dp_matrix_cell *dp_matrix;
sequences *d_seq_ctx;
struct bp_prob *d_bp1, *d_bp2;
};
#ifdef __CUDACC__
__device__ void max(dp_matrix_cell &score1, dp_matrix_cell score2, int parent);
__device__ void calculate_pos(dp_matrix_cell *dp_matrix, sequences* seq_ctx, dp_matrix_cell &score1, int i, int j, int k, int l, float extra_score, int parent);
__device__ void calculate_pos_mb(dp_matrix_cell *dp_matrix, sequences* seq_ctx, dp_matrix_cell &score1, int i, int j, int k, int l, int m, int n);
__device__ void sankoff_gpu_expand_inner_matrix_diag(dp_matrix_cell *dp_matrix, const int &i, const int &k, sequences* seq_ctx, struct bp_prob* bp1, struct bp_prob* bp2);
__device__ void sankoff_gpu_expand_pos(dp_matrix_cell *dp_matrix, const int &i, const int &j, const int &k, const int &l, sequences* seq_ctx, struct bp_prob* bp1, struct bp_prob* bp2);
__global__ void sankoff_gpu_expand_outer_matrix_diagonal_phase1(dp_matrix_cell *dp_matrix, int outer_diag, sequences* seq_ctx, struct bp_prob* bp1, struct bp_prob* bp2);
__global__ void sankoff_gpu_expand_outer_matrix_diagonal_phase2(dp_matrix_cell *dp_matrix, int outer_diag, sequences* seq_ctx, struct bp_prob* bp1, struct bp_prob* bp2);
__device__ void sankoff_gpu_expand_inner_matrix_diagonal_phase1(dp_matrix_cell *dp_matrix, int outer_diag, int i, int k, sequences* seq_ctx, struct bp_prob* bp1, struct bp_prob* bp2);
__device__ void sankoff_gpu_expand_inner_matrix_diagonal_phase2(dp_matrix_cell *dp_matrix, int outer_diag, int i, int k, sequences* seq_ctx, struct bp_prob* bp1, struct bp_prob* bp2);
#endif
#endif
|
danielsundfeld/cuda_sankoff | src/TimeCounter.h | /*!
* \class TimeCounter
* \author <NAME>
* \copyright MIT License
*
* \brief Class that count elapsed time between the creation and destruction
*/
#ifndef _TIMECOUNTER_H
#define _TIMECOUNTER_H
#include <sys/time.h>
#include <iostream>
#include <string>
class TimeCounter
{
public:
TimeCounter(const std::string &msg = "");
~TimeCounter();
private:
struct timeval m_begin;
std::string m_msg;
};
#endif
|
danielsundfeld/cuda_sankoff | src/Sequences.h | <reponame>danielsundfeld/cuda_sankoff<gh_stars>0
/*!
* \class Sequences
* \author <NAME>
* \copyright MIT License
*
* \brief Singleton that holds all sequences being aligned
*/
#ifndef _SEQUENCES_H
#define _SEQUENCES_H
#include <string>
#include <vector>
class Sequences
{
public:
static Sequences* get_instance() { return &instance; };
int set_seq(const std::string &x);
const std::string& get_seq(int x) const { return seqs.at(x); };
static int get_nseq() { return n_seq; };
private:
static int n_seq;
static Sequences instance;
std::vector<std::string> seqs;
Sequences() { };
};
#endif
|
danielsundfeld/cuda_sankoff | src/DPMatrix.h | <filename>src/DPMatrix.h<gh_stars>0
#ifndef _DPMATRIX_H
#define _DPMATRIX_H
#include <string>
#include "Backtrace.h"
#include "dp_matrix_cell.h"
class DPMatrix {
public:
DPMatrix(const int &s1_l, const int &s2_l);
~DPMatrix();
dp_matrix_cell get_pos(const int &i, const int &j, const int &k, const int &l) const;
void put_pos(const int &i, const int &j, const int &k, const int &l, const dp_matrix_cell &val);
long long int get_total_size() const;
bool check_border(const int &i, const int &j, const int &k, const int &l) const;
void backtrace(const std::string &s1, const std::string &s2);
dp_matrix_cell* get_dp_matrix() { return dp_matrix; };
private:
int calc_delta(int i, int j, int k, int l) const;
long long int calc_total_size(long long int s1, long long int s2) const;
dp_matrix_cell get_parent(const dp_matrix_cell c, int &i, int &j, int &k, int &l, const std::string &s1, const std::string &s2);
void add_last(const dp_matrix_cell c, int &i, int &k, const std::string &s1, const std::string &s2);
dp_matrix_cell *dp_matrix;
const int s1_l;
const int s2_l;
};
#endif
|
danielsundfeld/cuda_sankoff | src/bp_probs.h | <filename>src/bp_probs.h
#ifndef _BP_PROBS
#define _BP_PROBS
#include <string>
#include "DPMatrix_GPU.h"
struct bp_prob {
int size;
float m[MAX_SEQ_SIZE][MAX_SEQ_SIZE];
};
int get_bp_prob(const std::string &seq, struct bp_prob *bp);
#endif
|
danielsundfeld/cuda_sankoff | src/Sankoff.h | <gh_stars>0
#ifndef _SANKOFF_H
#define _SANKOFF_H
#include <string>
#include "bp_probs.h"
#include "DPMatrix.h"
#include "dp_matrix_cell.h"
class Sankoff {
public:
Sankoff(const std::string &seq1, const std::string &seq2);
virtual ~Sankoff();
int sankoff(); //Run a pure sankoff algorithm
int diag_sankoff(); //Run a pure sankoff algorithm
static void max(dp_matrix_cell &score1, dp_matrix_cell score2, int parent);
void calculate_pos(dp_matrix_cell &score1, int i, int j, int k, int l, float extra_score, int parent);
void calculate_pos_mb(dp_matrix_cell &score1, int i, int j, int k, int l, int m, int n);
void print_score_dep(int i, int j, int k, int l) const;
void print_mb_dep(int i, int j, int k, int l, int m, int n) const;
void print_orig(int i, int j, int k, int l) const;
void print_index(int i, int j, int k, int l) const;
protected:
DPMatrix dp_matrix;
std::string s1;
int s1_l;
std::string s2;
int s2_l;
private:
struct bp_prob *bp1, *bp2;
void expand_inner_matrix(const int &i, const int &k);
void expand_inner_matrix_diag(const int &i, const int &k);
void expand_pos(const int &i, const int &j, const int &k, const int &l);
};
#endif
|
danielsundfeld/cuda_sankoff | src/Backtrace.h | #ifndef _BACKTRACE_H
#define _BACKTRACE_H
#include <string>
#include "DPMatrix.h"
#include "dp_matrix_cell.h"
class DPMatrix;
class Backtrace {
public:
Backtrace(DPMatrix *dp_matrix, int i, int j, int k, int l, const std::string &s1, const std::string &s2);
void run();
void print(std::string &alignment_s1, std::string &alignment_structure, std::string &alignment_s2);
private:
dp_matrix_cell get_parent(const dp_matrix_cell c);
void calculate_mb_position(float score);
void do_backtrace_mb(int i, int j, int k, int l);
DPMatrix *dp_matrix;
int i, j, k, l;
int m, n;
const std::string s1, s2;
std::string list_i, list_j, list_k, list_l, list_bp_left, list_bp_right;
};
#endif
|
Subsets and Splits