/* * call-seq: * Raindrops::Linux.tcp_listener_stats([addrs[, sock]]) => hash * * If specified, +addr+ may be a string or array of strings representing * listen addresses to filter for. Returns a hash with given addresses as * keys and ListenStats objects as the values or a hash of all addresses. * * addrs = %w(0.0.0.0:80 127.0.0.1:8080) * * If +addr+ is nil or not specified, all (IPv4) addresses are returned. * If +sock+ is specified, it should be a Raindrops::InetDiagSock object. */ static VALUE tcp_listener_stats(int argc, VALUE *argv, VALUE self) { VALUE rv = rb_hash_new(); struct nogvl_args args; VALUE addrs, sock; rb_scan_args(argc, argv, "02", &addrs, &sock); /* * allocating page_size instead of OP_LEN since we'll reuse the * buffer for recvmsg() later, we already checked for * OPLEN <= page_size at initialization */ args.iov[2].iov_len = OPLEN; args.iov[2].iov_base = alloca(page_size); args.table = NULL; if (NIL_P(sock)) sock = rb_funcall(cIDSock, id_new, 0); args.fd = my_fileno(sock); switch (TYPE(addrs)) { case T_STRING: rb_hash_aset(rv, addrs, tcp_stats(&args, addrs)); return rv; case T_ARRAY: { long i; long len = RARRAY_LEN(addrs); VALUE cur; if (len == 1) { cur = rb_ary_entry(addrs, 0); rb_hash_aset(rv, cur, tcp_stats(&args, cur)); return rv; } for (i = 0; i < len; i++) { union any_addr check; VALUE cur = rb_ary_entry(addrs, i); parse_addr(&check, cur); rb_hash_aset(rv, cur, Qtrue); } /* fall through */ } case T_NIL: args.table = st_init_strtable(); gen_bytecode_all(&args.iov[2]); break; default: rb_raise(rb_eArgError, "addr must be an array of strings, a string, or nil"); } nl_errcheck(rb_thread_io_blocking_region(diag, &args, args.fd)); st_foreach(args.table, NIL_P(addrs) ? st_to_hash : st_AND_hash, rv); st_free_table(args.table); /* let GC deal with corner cases */ if (argc < 2) rb_io_close(sock); return rv; }
int main(int argc, char **argv) { srand(time(NULL)); int i, c; int pid_flags = 0; int mptcp = 0; int mtu = 0; char *user = NULL; char *local_port = NULL; char *local_addr = NULL; char *password = NULL; char *key = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; char *plugin = NULL; char *plugin_opts = NULL; char *plugin_host = NULL; char *plugin_port = NULL; char tmp_port[8]; int remote_num = 0; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; ss_addr_t tunnel_addr = { .host = NULL, .port = NULL }; char *tunnel_addr_str = NULL; static struct option long_options[] = { { "mtu", required_argument, NULL, GETOPT_VAL_MTU }, { "mptcp", no_argument, NULL, GETOPT_VAL_MPTCP }, { "plugin", required_argument, NULL, GETOPT_VAL_PLUGIN }, { "plugin-opts", required_argument, NULL, GETOPT_VAL_PLUGIN_OPTS }, { "reuse-port", no_argument, NULL, GETOPT_VAL_REUSE_PORT }, { "password", required_argument, NULL, GETOPT_VAL_PASSWORD }, { "key", required_argument, NULL, GETOPT_VAL_KEY }, { "help", no_argument, NULL, GETOPT_VAL_HELP }, { NULL, 0, NULL, 0 } }; opterr = 0; USE_TTY(); #ifdef ANDROID while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:huUvV6A", long_options, NULL)) != -1) { #else while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:huUv6A", long_options, NULL)) != -1) { #endif switch (c) { case GETOPT_VAL_MTU: mtu = atoi(optarg); LOGI("set MTU to %d", mtu); break; case GETOPT_VAL_MPTCP: mptcp = 1; LOGI("enable multipath TCP"); break; case GETOPT_VAL_PLUGIN: plugin = optarg; break; case GETOPT_VAL_PLUGIN_OPTS: plugin_opts = optarg; break; case GETOPT_VAL_KEY: key = optarg; break; case GETOPT_VAL_REUSE_PORT: reuse_port = 1; break; case 's': if (remote_num < MAX_REMOTE_NUM) { remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; } break; case 'p': remote_port = optarg; break; case 'l': local_port = optarg; break; case GETOPT_VAL_PASSWORD: case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'b': local_addr = optarg; break; case 'u': mode = TCP_AND_UDP; break; case 'U': mode = UDP_ONLY; break; case 'L': tunnel_addr_str = optarg; break; case 'a': user = optarg; break; #ifdef HAVE_SETRLIMIT case 'n': nofile = atoi(optarg); break; #endif case 'v': verbose = 1; break; case GETOPT_VAL_HELP: case 'h': usage(); exit(EXIT_SUCCESS); case '6': ipv6first = 1; break; #ifdef ANDROID case 'V': vpn = 1; break; #endif case 'A': FATAL("One time auth has been deprecated. Try AEAD ciphers instead."); break; case '?': // The option character is not recognized. LOGE("Unrecognized option: %s", optarg); opterr = 1; break; } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (argc == 1) { if (conf_path == NULL) { conf_path = DEFAULT_CONF_PATH; } } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (remote_num == 0) { remote_num = conf->remote_num; for (i = 0; i < remote_num; i++) remote_addr[i] = conf->remote_addr[i]; } if (remote_port == NULL) { remote_port = conf->remote_port; } if (local_addr == NULL) { local_addr = conf->local_addr; } if (local_port == NULL) { local_port = conf->local_port; } if (password == NULL) { password = conf->password; } if (key == NULL) { key = conf->key; } if (method == NULL) { method = conf->method; } if (timeout == NULL) { timeout = conf->timeout; } if (user == NULL) { user = conf->user; } if (plugin == NULL) { plugin = conf->plugin; } if (plugin_opts == NULL) { plugin_opts = conf->plugin_opts; } if (tunnel_addr_str == NULL) { tunnel_addr_str = conf->tunnel_address; } if (mode == TCP_ONLY) { mode = conf->mode; } if (mtu == 0) { mtu = conf->mtu; } if (mptcp == 0) { mptcp = conf->mptcp; } if (reuse_port == 0) { reuse_port = conf->reuse_port; } #ifdef HAVE_SETRLIMIT if (nofile == 0) { nofile = conf->nofile; } #endif } if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL || local_port == NULL || (password == NULL && key == NULL)) { usage(); exit(EXIT_FAILURE); } if (plugin != NULL) { uint16_t port = get_local_port(); if (port == 0) { FATAL("failed to find a free port"); } snprintf(tmp_port, 8, "%d", port); plugin_host = "127.0.0.1"; plugin_port = tmp_port; LOGI("plugin \"%s\" enabled", plugin); } if (method == NULL) { method = "rc4-md5"; } if (timeout == NULL) { timeout = "60"; } #ifdef HAVE_SETRLIMIT /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile > 1024) { if (verbose) { LOGI("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif if (local_addr == NULL) { local_addr = "127.0.0.1"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } if (ipv6first) { LOGI("resolving hostname to IPv6 address first"); } // parse tunnel addr parse_addr(tunnel_addr_str, &tunnel_addr); if (tunnel_addr.port == NULL) { FATAL("tunnel port is not defined"); } if (plugin != NULL) { int len = 0; size_t buf_size = 256 * remote_num; char *remote_str = ss_malloc(buf_size); snprintf(remote_str, buf_size, "%s", remote_addr[0].host); for (int i = 1; i < remote_num; i++) { snprintf(remote_str + len, buf_size - len, "|%s", remote_addr[i].host); len = strlen(remote_str); } int err = start_plugin(plugin, plugin_opts, remote_str, remote_port, plugin_host, plugin_port, MODE_CLIENT); if (err) { FATAL("failed to start the plugin"); } } // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); ev_signal_init(&sigint_watcher, signal_cb, SIGINT); ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM); ev_signal_init(&sigchld_watcher, signal_cb, SIGCHLD); ev_signal_start(EV_DEFAULT, &sigint_watcher); ev_signal_start(EV_DEFAULT, &sigterm_watcher); ev_signal_start(EV_DEFAULT, &sigchld_watcher); // Setup keys LOGI("initializing ciphers... %s", method); crypto = crypto_init(password, key, method); if (crypto == NULL) FATAL("failed to initialize ciphers"); // Setup proxy context struct listen_ctx listen_ctx; memset(&listen_ctx, 0, sizeof(struct listen_ctx)); listen_ctx.tunnel_addr = tunnel_addr; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = ss_malloc(sizeof(struct sockaddr *) * remote_num); memset(listen_ctx.remote_addr, 0, sizeof(struct sockaddr *) * remote_num); for (i = 0; i < remote_num; i++) { char *host = remote_addr[i].host; char *port = remote_addr[i].port == NULL ? remote_port : remote_addr[i].port; if (plugin != NULL) { host = plugin_host; port = plugin_port; } struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) { FATAL("failed to resolve the provided hostname"); } listen_ctx.remote_addr[i] = (struct sockaddr *)storage; if (plugin != NULL) break; } listen_ctx.timeout = atoi(timeout); listen_ctx.iface = iface; listen_ctx.mptcp = mptcp; struct ev_loop *loop = EV_DEFAULT; if (mode != UDP_ONLY) { // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); if (listenfd == -1) { FATAL("bind() error"); } if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error"); } setnonblocking(listenfd); listen_ctx.fd = listenfd; ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx.io); } // Setup UDP if (mode != TCP_ONLY) { LOGI("UDP relay enabled"); char *host = remote_addr[0].host; char *port = remote_addr[0].port == NULL ? remote_port : remote_addr[0].port; struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) { FATAL("failed to resolve the provided hostname"); } struct sockaddr *addr = (struct sockaddr *)storage; init_udprelay(local_addr, local_port, addr, get_sockaddr_len(addr), tunnel_addr, mtu, crypto, listen_ctx.timeout, iface); } if (mode == UDP_ONLY) { LOGI("TCP relay disabled"); } LOGI("listening at %s:%s", local_addr, local_port); // setuid if (user != NULL && !run_as(user)) { FATAL("failed to switch user"); } if (geteuid() == 0) { LOGI("running from root user"); } ev_run(loop, 0); if (plugin != NULL) { stop_plugin(); } return 0; }
int main(int argc, char * argv[]) { int i; int localport=0,remoteport=0,payload=0; char ip[50]; const char *fmtp=NULL; int jitter=50; int bitrate=0; MSVideoSize vs; bool_t ec=FALSE; bool_t agc=FALSE; bool_t eq=FALSE; /*create the rtp session */ ortp_init(); ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); rtp_profile_set_payload(&av_profile,115,&payload_type_lpc1015); rtp_profile_set_payload(&av_profile,110,&payload_type_speex_nb); rtp_profile_set_payload(&av_profile,111,&payload_type_speex_wb); rtp_profile_set_payload(&av_profile,112,&payload_type_ilbc); rtp_profile_set_payload(&av_profile,113,&payload_type_amr); #ifdef VIDEO_ENABLED rtp_profile_set_payload(&av_profile,26,&payload_type_jpeg); rtp_profile_set_payload(&av_profile,98,&payload_type_h263_1998); rtp_profile_set_payload(&av_profile,97,&payload_type_theora); rtp_profile_set_payload(&av_profile,99,&payload_type_mp4v); rtp_profile_set_payload(&av_profile,100,&payload_type_x_snow); rtp_profile_set_payload(&av_profile,102,&payload_type_h264); #endif vs.width=MS_VIDEO_SIZE_CIF_W; vs.height=MS_VIDEO_SIZE_CIF_H; if (argc<4) { printf("%s",usage); return -1; } for (i=1;i<argc;i++){ if (strcmp(argv[i],"--local")==0){ i++; localport=atoi(argv[i]); }else if (strcmp(argv[i],"--remote")==0){ i++; if (!parse_addr(argv[i],ip,sizeof(ip),&remoteport)) { printf("%s",usage); return -1; } printf("Remote addr: ip=%s port=%i\n",ip,remoteport); }else if (strcmp(argv[i],"--payload")==0){ i++; payload=atoi(argv[i]); }else if (strcmp(argv[i],"--fmtp")==0){ i++; fmtp=argv[i]; }else if (strcmp(argv[i],"--jitter")==0){ i++; jitter=atoi(argv[i]); }else if (strcmp(argv[i],"--bitrate")==0){ i++; bitrate=atoi(argv[i]); }else if (strcmp(argv[i],"--width")==0){ i++; vs.width=atoi(argv[i]); }else if (strcmp(argv[i],"--height")==0){ i++; vs.height=atoi(argv[i]); }else if (strcmp(argv[i],"--capture-card")==0){ i++; capture_card=argv[i]; }else if (strcmp(argv[i],"--playback-card")==0){ i++; playback_card=argv[i]; }else if (strcmp(argv[i],"--ec")==0){ ec=TRUE; }else if (strcmp(argv[i],"--agc")==0){ agc=TRUE; }else if (strcmp(argv[i],"--eq")==0){ eq=TRUE; }else if (strcmp(argv[i],"--ng")==0){ use_ng=1; }else if (strcmp(argv[i],"--ng-threshold")==0){ i++; ng_threshold=atof(argv[i]); }else if (strcmp(argv[i],"--two-windows")==0){ two_windows=TRUE; }else if (strcmp(argv[i],"--infile")==0){ i++; infile=argv[i]; }else if (strcmp(argv[i],"--outfile")==0){ i++; outfile=argv[i]; } } run_media_streams(localport,ip,remoteport,payload,fmtp,jitter,bitrate,vs,ec,agc,eq); return 0; }
int main(int argc, const char *argv[]) { int base_src_port = 65500; int polling = 0; int busy_poll = 0; int packet_timestamp = 0; int test_len = 1; int packet_size=PKT_SIZE; static struct option long_options[] = { {"src-port", required_argument, 0, 's'}, {"packet-size", required_argument, 0, 'm'}, {"polling", no_argument, 0, 'p'}, {"busy-poll", required_argument, 0, 'b'}, {"timestamp", no_argument, 0, 't'}, {"test-length", required_argument, 0, 'l'}, {NULL, 0, 0, 0}}; const char *optstring = optstring_from_long_options(long_options); optind = 1; while (1) { int option_index = 0; int arg = getopt_long(argc, (char **)argv, optstring, long_options, &option_index); if (arg == -1) { break; } switch (arg) { case 's': base_src_port = atoi(optarg); break; case 'p': polling = 1; break; case 'b': busy_poll = atoi(optarg); break; case 't': packet_timestamp = 1; break; case 'l': test_len = atoi(optarg); break; case 'm': packet_size=atoi(optarg); break; default: FATAL("Unknown option %c: %s", arg, argv[optind]); } } int thread_num = argc - optind; if (thread_num < 1) { FATAL("Usage: %s [--polling] [--busy-poll=<>] [--src-port=<>] " "[--timestamp] [target:port...]", argv[0]); } struct net_addr *target_addrs = calloc(thread_num, sizeof(struct net_addr)); int t; for (t = 0; t < thread_num; t++) { const char *target_addr_str = argv[optind + t]; parse_addr(&target_addrs[t], target_addr_str); fprintf(stderr, "[*] Sending to %s, polling=%i, src_port=%i\n", addr_to_str(&target_addrs[t]), polling, base_src_port + t); } struct state *array_of_states = calloc(thread_num, sizeof(struct state)); for (t = 0; t < thread_num; t++) { struct state *state = &array_of_states[t]; state->target_addr = &target_addrs[t]; state->polling = polling; state->busy_poll = busy_poll; state->packet_size = packet_size; if (base_src_port > 0) { state->src_port = base_src_port + t; } thread_spawn(thread_loop, state); } while (1) { struct timeval timeout = NSEC_TIMEVAL(MSEC_NSEC(1000UL*test_len)); while (1) { int r = select(0, NULL, NULL, NULL, &timeout); if (r != 0) { continue; } if (TIMEVAL_NSEC(&timeout) == 0) { break; } } for (t = 0; t < thread_num; t++) { struct state *state = &array_of_states[t]; uint64_t count; double avg, stddev; double avg_packet, stddev_packet; pthread_spin_lock(&state->lock); stddev_get(&state->stddev, &count, &avg, &stddev); int min = state->stddev.min; int max = state->stddev.max; stddev_get(&state->stddev_packet, NULL, &avg_packet, &stddev_packet); stddev_init(&state->stddev); stddev_init(&state->stddev_packet); pthread_spin_unlock(&state->lock); printf("pps=%6lu avg=%7.3f dev=%7.3f min=%6.3f max=%6.3f", count/test_len, avg / 1000., stddev / 1000., (double)min / 1000., (double)max / 1000.); if (packet_timestamp) { printf("(packet=%5.3fus/%5.3f) ", avg_packet / 1000., stddev_packet / 1000.); } } printf("\n"); } return 0; }
int main(int argc, char **argv) { int i, c; int pid_flags = 0; char *user = NULL; char *local_port = NULL; char *local_addr = NULL; char *password = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; int remote_num = 0; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; ss_addr_t tunnel_addr = { .host = NULL, .port = NULL }; char *tunnel_addr_str = NULL; opterr = 0; USE_TTY(); #ifdef ANDROID while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uUvVA")) != -1) { #else while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uUvA")) != -1) { #endif switch (c) { case 's': if (remote_num < MAX_REMOTE_NUM) { remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; } break; case 'p': remote_port = optarg; break; case 'l': local_port = optarg; break; case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'b': local_addr = optarg; break; case 'u': mode = TCP_AND_UDP; break; case 'U': mode = UDP_ONLY; break; case 'L': tunnel_addr_str = optarg; break; case 'a': user = optarg; break; case 'v': verbose = 1; break; case 'A': auth = 1; LOGI("onetime authentication enabled"); break; #ifdef ANDROID case 'V': vpn = 1; break; #endif } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (argc == 1) { if (conf_path == NULL) { conf_path = DEFAULT_CONF_PATH; } } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (remote_num == 0) { remote_num = conf->remote_num; for (i = 0; i < remote_num; i++) { remote_addr[i] = conf->remote_addr[i]; } } if (remote_port == NULL) { remote_port = conf->remote_port; } if (local_addr == NULL) { local_addr = conf->local_addr; } if (local_port == NULL) { local_port = conf->local_port; } if (password == NULL) { password = conf->password; } if (method == NULL) { method = conf->method; } if (timeout == NULL) { timeout = conf->timeout; } } if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL || local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } if (timeout == NULL) { timeout = "60"; } if (local_addr == NULL) { local_addr = "127.0.0.1"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } // parse tunnel addr parse_addr(tunnel_addr_str, &tunnel_addr); if (tunnel_addr.port == NULL) { FATAL("tunnel port is not defined"); } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif // Setup keys LOGI("initialize ciphers... %s", method); int m = enc_init(password, method); // Setup proxy context struct listen_ctx listen_ctx; listen_ctx.tunnel_addr = tunnel_addr; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num); for (i = 0; i < remote_num; i++) { char *host = remote_addr[i].host; char *port = remote_addr[i].port == NULL ? remote_port : remote_addr[i].port; struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage, 1) == -1) { FATAL("failed to resolve the provided hostname"); } listen_ctx.remote_addr[i] = (struct sockaddr *)storage; } listen_ctx.timeout = atoi(timeout); listen_ctx.iface = iface; listen_ctx.method = m; struct ev_loop *loop = EV_DEFAULT; if (mode != UDP_ONLY) { // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); if (listenfd < 0) { FATAL("bind() error:"); } if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error:"); } setnonblocking(listenfd); listen_ctx.fd = listenfd; ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx.io); } // Setup UDP if (mode != TCP_ONLY) { LOGI("UDP relay enabled"); init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0], get_sockaddr_len(listen_ctx.remote_addr[0]), tunnel_addr, m, listen_ctx.timeout, iface); } if (mode == UDP_ONLY) { LOGI("TCP relay disabled"); } LOGI("listening at %s:%s", local_addr, local_port); // setuid if (user != NULL) { run_as(user); } ev_run(loop, 0); #ifdef __MINGW32__ winsock_cleanup(); #endif return 0; }
jconf_t *read_jconf(const char * file) { static jconf_t conf; char *buf; json_value *obj; FILE *f = fopen(file, "rb"); if (f == NULL) { FATAL("Invalid config path."); } fseek(f, 0, SEEK_END); long pos = ftell(f); fseek(f, 0, SEEK_SET); if (pos >= MAX_CONF_SIZE) { FATAL("Too large config file."); } buf = malloc(pos + 1); if (buf == NULL) { FATAL("No enough memory."); } int nread = fread(buf, pos, 1, f); if (!nread) { FATAL("Failed to read the config file."); } fclose(f); buf[pos] = '\0'; // end of string json_settings settings = { 0 }; char error_buf[512]; obj = json_parse_ex(&settings, buf, pos, error_buf); if (obj == NULL) { FATAL(error_buf); } if (obj->type == json_object) { int i, j; for (i = 0; i < obj->u.object.length; i++) { char *name = obj->u.object.values[i].name; json_value *value = obj->u.object.values[i].value; if (strcmp(name, "server") == 0) { if (value->type == json_array) { for (j = 0; j < value->u.array.length; j++) { if (j >= MAX_REMOTE_NUM) { break; } json_value *v = value->u.array.values[j]; parse_addr(to_string(v), conf.remote_addr + j); conf.remote_num = j + 1; } } else if (value->type == json_string) { conf.remote_addr[0].host = to_string(value); conf.remote_addr[0].port = NULL; conf.remote_num = 1; } } else if (strcmp(name, "server_port") == 0) { conf.remote_port = to_string(value); } else if (strcmp(name, "local") == 0) { conf.local_addr = to_string(value); } else if (strcmp(name, "local_port") == 0) { conf.local_port = to_string(value); } else if (strcmp(name, "password") == 0) { conf.password = to_string(value); } else if (strcmp(name, "method") == 0) { conf.method = to_string(value); } else if (strcmp(name, "timeout") == 0) { conf.timeout = to_string(value); } else if (strcmp(name, "fast_open") == 0) { conf.fast_open = value->u.boolean; } else if (strcmp(name, "nofile") == 0) { conf.nofile = value->u.integer; } else if (strcmp(name, "tunnel_addr") == 0){ conf.tunnel_addr = to_string(value); } } } else { FATAL("Invalid config file"); } free(buf); json_value_free(obj); return &conf; }
static const struct token * match_token(const char *word, const struct token *table, struct parse_result *res) { unsigned int i, match; const struct token *t = NULL; match = 0; for (i = 0; table[i].type != ENDTOKEN; i++) { switch (table[i].type) { case NOTOKEN: if (word == NULL || strlen(word) == 0) { match++; t = &table[i]; } break; case KEYWORD: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; if (t->value) res->action = t->value; } break; case FLAG: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; res->flags |= t->value; } break; case FAMILY: if (word == NULL) break; if (!strcmp(word, "inet") || !strcasecmp(word, "IPv4")) { match++; t = &table[i]; res->family = AF_INET; } if (!strcmp(word, "inet6") || !strcasecmp(word, "IPv6")) { match++; t = &table[i]; res->family = AF_INET6; } break; case ASNUM: if (parse_asnum(word, &res->as)) { match++; t = &table[i]; } break; case ADDRESS: if (parse_addr(word, &res->family, &res->addr)) { match++; t = &table[i]; if (t->value) res->action = t->value; } break; case PREFIX: if (parse_prefix(word, &res->family, &res->addr, &res->prefixlen)) { match++; t = &table[i]; if (t->value) res->action = t->value; } break; case IFNAME: if (!match && word != NULL && strlen(word) > 0) { if (strlcpy(res->ifname, word, sizeof(res->ifname)) >= sizeof(res->ifname)) err(1, "interface name too long"); match++; t = &table[i]; if (t->value) res->action = t->value; } break; case ENDTOKEN: break; } } if (match != 1) { if (word == NULL) fprintf(stderr, "missing argument:\n"); else if (match > 1) fprintf(stderr, "ambiguous argument: %s\n", word); else if (match < 1) fprintf(stderr, "unknown argument: %s\n", word); return (NULL); } return (t); }
const struct token * match_token(const char *word, const struct token *table) { u_int i, match; const struct token *t = NULL; match = 0; for (i = 0; table[i].type != ENDTOKEN; i++) { switch (table[i].type) { case NOTOKEN: if (word == NULL || strlen(word) == 0) { match++; t = &table[i]; } break; case KEYWORD: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case FLAG: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; res.flags |= t->value; } break; case ADDRESS: if (!parse_addr(word, &res.addr)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case NAME: if (word != NULL && strlen(word) > 0) { if (strlcpy(res.name, word, sizeof(res.name)) >= sizeof(res.name)) errx(1, "name too long"); match++; t = &table[i]; } break; case ENDTOKEN: break; } } if (match != 1) { if (word == NULL) fprintf(stderr, "missing argument:\n"); else if (match > 1) fprintf(stderr, "ambiguous argument: %s\n", word); else if (match < 1) fprintf(stderr, "unknown argument: %s\n", word); return (NULL); } return (t); }
const struct token * match_token(const char *word, const struct token *table) { u_int i, match; const char *errstr; const struct token *t = NULL; match = 0; for (i = 0; table[i].type != ENDTOKEN; i++) { switch (table[i].type) { case NOTOKEN: if (word == NULL || strlen(word) == 0) { match++; t = &table[i]; } break; case BRFLAGS: if (parse_brflags(word, &res.flags)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case FLAGS: if (parse_flags(word, &res.flags)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case KEYWORD: if (word != NULL && strcmp(word, table[i].keyword) == 0) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case PROTO: if (word != NULL && strcmp(word, table[i].keyword) == 0) { res.proto = word; match++; t = &table[i]; if (t->value) res.action = t->value; } break; case ADDRESS: if (parse_addr(word, &res.addr)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case HOSTNAME: if (parse_hostname(word, res.hostname)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case FQDN: if (parse_target_hostname(word, res.hostname)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case APPPROTO: if (word != NULL && *word != '-') { res.app = word; match++; t = &table[i]; if (t->value) res.action = t->value; } break; case SRVNAME: /* match anything */ if (word != NULL) { res.srvname = word; match++; t = &table[i]; if (t->value) res.action = t->value; } break; case TXTSTRING: if (word != NULL) { res.txtstring = word; match++; t = &table[i]; if (t->value) res.action = t->value; } break; case PORT: if (word != NULL) { res.port = strtonum(word, 1, UINT16_MAX, &errstr); if (errstr) errx(1, "strtonum: %s", errstr); match++; t = &table[i]; if (t->value) res.action = t->value; } break; case ENDTOKEN: break; } } if (match != 1) { if (word == NULL) fprintf(stderr, "missing argument:\n"); else if (match > 1) fprintf(stderr, "ambiguous argument: %s\n", word); else if (match < 1) fprintf(stderr, "unknown argument: %s\n", word); return (NULL); } return (t); }
static void recv_cb(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { struct tundev_context *ctx; struct client_context *client; ctx = stream->data; client = container_of(stream, struct client_context, handle.stream); struct packet *packet = &client->packet; if (nread > 0) { if ((ctx->connect == AUTHING) && ( (0 == memcmp(packet->buf, "GET ", 4)) || (0 == memcmp(packet->buf, "POST", 4)) ) ) { http_auth(stream, packet->buf); packet_reset(packet); ctx->connect = CONNECTED; return; } int rc = packet_filter(packet, buf->base, nread); if (rc == PACKET_UNCOMPLETE) { return; } else if (rc == PACKET_INVALID) { logger_log(LOG_ERR, "Filter Invalid: %d", nread); goto error; } int clen = packet->size; int mlen = packet->size - PRIMITIVE_BYTES; uint8_t *c = packet->buf, *m = packet->buf; assert(mlen > 0 && mlen <= ctx->tun->mtu); int err = crypto_decrypt(m, c, clen); if (err) { logger_log(LOG_ERR, "Fail Decrypt: %d", clen); goto error; } struct iphdr *iphdr = (struct iphdr *) m; in_addr_t client_network = iphdr->saddr & htonl(ctx->tun->netmask); if (client_network != ctx->tun->network) { char *a = inet_ntoa(*(struct in_addr *) &iphdr->saddr); logger_log(LOG_ERR, "Invalid client: %s", a); close_client(client); return; } if (client->peer == NULL) { uv_rwlock_rdlock(&rwlock); struct peer *peer = lookup_peer(iphdr->saddr, peers); uv_rwlock_rdunlock(&rwlock); if (peer == NULL) { char saddr[24] = {0}, daddr[24] = {0}; parse_addr(iphdr, saddr, daddr); logger_log(LOG_WARNING, "[TCP] Cache miss: %s -> %s", saddr, daddr); uv_rwlock_wrlock(&rwlock); peer = save_peer(iphdr->saddr, &client->addr, peers); uv_rwlock_wrunlock(&rwlock); } else { if (peer->data) { struct client_context *old = peer->data; close_client(old); } } peer->protocol= xTUN_TCP; peer->data = client; client->peer = peer; } network_to_tun(ctx->tunfd, m, mlen); packet_reset(packet); } else if (nread < 0) { if (nread != UV_EOF) { logger_log(LOG_ERR, "Receive from client failed: %s", uv_strerror(nread)); } close_client(client); } return; error: if (verbose) { dump_hex(buf->base, nread, "Invalid tcp Packet"); } handle_invalid_packet(client); }
int main(int argc, char *argv[]) { int addr; modbus_mapping_t *mb_mapping; modbus_t *ctx; int s; int ret; /* * Check command line */ optind = check_common_opts(argc, argv); if (argc - optind < 1) usage(); addr = parse_addr(argv[optind + 0]); if (addr < 1) { err("invalid address \"%s\"", argv[optind + 0]); exit(-1); } /* * Modbus stuff */ mb_mapping = modbus_mapping_new(10, 10, 10, 10); if (mb_mapping == NULL) { err("failed to allocate the mapping: %s\n", modbus_strerror(errno)); exit(-1); } ctx = modbus_server_new(addr, &s); if (!ctx) { err("cannot create server: %s", modbus_strerror(errno)); exit(1); } for (;;) { ret = modbus_server_connect(ctx, &s); if (ret < 0) { err("connection failed: %s", modbus_strerror(errno)); exit(1); } dbg("got new connection"); for (;;) { uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH]; ret = modbus_receive(ctx, query); dbg("got new query"); if (ret >= 0) { modbus_reply(ctx, query, ret, mb_mapping); dbg("query answered"); } else { /* Connection closed by the client or server */ break; } } } printf("Quit the loop: %s\n", modbus_strerror(errno)); modbus_mapping_free(mb_mapping); modbus_close(ctx); modbus_free(ctx); return 0; }
static int parse_option(struct if_options *ifo, int opt, const char *arg) { int i; char *p = NULL, *np; ssize_t s; struct in_addr addr, addr2; struct rt *rt; switch(opt) { case 'a': /* FALLTHROUGH */ case 'f': /* FALLTHROUGH */ case 'g': /* FALLTHROUGH */ case 'n': /* FALLTHROUGH */ case 'x': /* FALLTHROUGH */ case 'T': /* FALLTHROUGH */ case 'U': /* We need to handle non interface options */ break; case 'b': ifo->options |= DHCPCD_BACKGROUND; break; case 'c': strlcpy(ifo->script, arg, sizeof(ifo->script)); break; case 'd': ifo->options |= DHCPCD_DEBUG; break; case 'e': add_environ(ifo, arg, 1); break; case 'h': if (arg) { s = parse_string(ifo->hostname, HOSTNAME_MAX_LEN, arg); if (s == -1) { syslog(LOG_ERR, "hostname: %m"); return -1; } if (s != 0 && ifo->hostname[0] == '.') { syslog(LOG_ERR, "hostname cannot begin with ."); return -1; } ifo->hostname[s] = '\0'; } if (ifo->hostname[0] == '\0') ifo->options &= ~DHCPCD_HOSTNAME; else ifo->options |= DHCPCD_HOSTNAME; break; case 'i': if (arg) s = parse_string((char *)ifo->vendorclassid + 1, VENDORCLASSID_MAX_LEN, arg); else s = 0; if (s == -1) { syslog(LOG_ERR, "vendorclassid: %m"); return -1; } *ifo->vendorclassid = (uint8_t)s; break; case 'k': ifo->options |= DHCPCD_RELEASE; break; case 'l': if (*arg == '-') { syslog(LOG_ERR, "leasetime must be a positive value"); return -1; } errno = 0; ifo->leasetime = (uint32_t)strtol(arg, NULL, 0); if (errno == EINVAL || errno == ERANGE) { syslog(LOG_ERR, "`%s' out of range", arg); return -1; } break; case 'm': ifo->metric = atoint(arg); if (ifo->metric < 0) { syslog(LOG_ERR, "metric must be a positive value"); return -1; } break; case 'o': if (make_option_mask(ifo->requestmask, arg, 1) != 0) { syslog(LOG_ERR, "unknown option `%s'", arg); return -1; } break; case 'p': ifo->options |= DHCPCD_PERSISTENT; break; case 'q': ifo->options |= DHCPCD_QUIET; break; case 'r': if (parse_addr(&ifo->req_addr, NULL, arg) != 0) return -1; ifo->options |= DHCPCD_REQUEST; ifo->req_mask.s_addr = 0; break; case 's': if (arg && *arg != '\0') { if (parse_addr(&ifo->req_addr, &ifo->req_mask, arg) != 0) return -1; } else { ifo->req_addr.s_addr = 0; ifo->req_mask.s_addr = 0; } ifo->options |= DHCPCD_INFORM | DHCPCD_PERSISTENT; ifo->options &= ~(DHCPCD_ARP | DHCPCD_STATIC); break; case 't': ifo->timeout = atoint(arg); if (ifo->timeout < 0) { syslog(LOG_ERR, "timeout must be a positive value"); return -1; } break; case 'u': s = USERCLASS_MAX_LEN - ifo->userclass[0] - 1; s = parse_string((char *)ifo->userclass + ifo->userclass[0] + 2, s, arg); if (s == -1) { syslog(LOG_ERR, "userclass: %m"); return -1; } if (s != 0) { ifo->userclass[ifo->userclass[0] + 1] = s; ifo->userclass[0] += s + 1; } break; case 'v': p = strchr(arg, ','); if (!p || !p[1]) { syslog(LOG_ERR, "invalid vendor format"); return -1; } /* If vendor starts with , then it is not encapsulated */ if (p == arg) { arg++; s = parse_string((char *)ifo->vendor + 1, VENDOR_MAX_LEN, arg); if (s == -1) { syslog(LOG_ERR, "vendor: %m"); return -1; } ifo->vendor[0] = (uint8_t)s; ifo->options |= DHCPCD_VENDORRAW; break; } /* Encapsulated vendor options */ if (ifo->options & DHCPCD_VENDORRAW) { ifo->options &= ~DHCPCD_VENDORRAW; ifo->vendor[0] = 0; } *p = '\0'; i = atoint(arg); arg = p + 1; if (i < 1 || i > 254) { syslog(LOG_ERR, "vendor option should be between" " 1 and 254 inclusive"); return -1; } s = VENDOR_MAX_LEN - ifo->vendor[0] - 2; if (inet_aton(arg, &addr) == 1) { if (s < 6) { s = -1; errno = ENOBUFS; } else memcpy(ifo->vendor + ifo->vendor[0] + 3, &addr.s_addr, sizeof(addr.s_addr)); } else { s = parse_string((char *)ifo->vendor + ifo->vendor[0] + 3, s, arg); } if (s == -1) { syslog(LOG_ERR, "vendor: %m"); return -1; } if (s != 0) { ifo->vendor[ifo->vendor[0] + 1] = i; ifo->vendor[ifo->vendor[0] + 2] = s; ifo->vendor[0] += s + 2; } break; case 'w': ifo->options |= DHCPCD_WAITIP; break; case 'y': ifo->reboot = atoint(arg); if (ifo->reboot < 0) { syslog(LOG_ERR, "reboot must be a positive value"); return -1; } break; case 'z': ifav = splitv(&ifac, ifav, arg); break; case 'A': ifo->options &= ~DHCPCD_ARP; /* IPv4LL requires ARP */ ifo->options &= ~DHCPCD_IPV4LL; break; case 'B': ifo->options &= ~DHCPCD_DAEMONISE; break; case 'C': /* Commas to spaces for shell */ while ((p = strchr(arg, ','))) *p = ' '; s = strlen("skip_hooks=") + strlen(arg) + 1; p = xmalloc(sizeof(char) * s); snprintf(p, s, "skip_hooks=%s", arg); add_environ(ifo, p, 0); free(p); break; case 'D': ifo->options |= DHCPCD_CLIENTID | DHCPCD_DUID; break; case 'E': ifo->options |= DHCPCD_LASTLEASE; break; case 'F': if (!arg) { ifo->fqdn = FQDN_BOTH; break; } if (strcmp(arg, "none") == 0) ifo->fqdn = FQDN_NONE; else if (strcmp(arg, "ptr") == 0) ifo->fqdn = FQDN_PTR; else if (strcmp(arg, "both") == 0) ifo->fqdn = FQDN_BOTH; else if (strcmp(arg, "disable") == 0) ifo->fqdn = FQDN_DISABLE; else { syslog(LOG_ERR, "invalid value `%s' for FQDN", arg); return -1; } break; case 'G': ifo->options &= ~DHCPCD_GATEWAY; break; case 'H': ifo->options |= DHCPCD_XID_HWADDR; break; case 'I': /* Strings have a type of 0 */; ifo->clientid[1] = 0; if (arg) s = parse_string_hwaddr((char *)ifo->clientid + 1, CLIENTID_MAX_LEN, arg, 1); else s = 0; if (s == -1) { syslog(LOG_ERR, "clientid: %m"); return -1; } ifo->options |= DHCPCD_CLIENTID; ifo->clientid[0] = (uint8_t)s; break; case 'J': ifo->options |= DHCPCD_BROADCAST; break; case 'K': ifo->options &= ~DHCPCD_LINK; break; case 'L': ifo->options &= ~DHCPCD_IPV4LL; break; case 'O': if (make_option_mask(ifo->requestmask, arg, -1) != 0 || make_option_mask(ifo->requiremask, arg, -1) != 0 || make_option_mask(ifo->nomask, arg, 1) != 0) { syslog(LOG_ERR, "unknown option `%s'", arg); return -1; } break; case 'Q': if (make_option_mask(ifo->requiremask, arg, 1) != 0 || make_option_mask(ifo->requestmask, arg, 1) != 0) { syslog(LOG_ERR, "unknown option `%s'", arg); return -1; } break; case 'S': p = strchr(arg, '='); if (p == NULL) { syslog(LOG_ERR, "static assignment required"); return -1; } p++; if (strncmp(arg, "ip_address=", strlen("ip_address=")) == 0) { if (parse_addr(&ifo->req_addr, ifo->req_mask.s_addr == 0 ? &ifo->req_mask : NULL, p) != 0) return -1; ifo->options |= DHCPCD_STATIC; ifo->options &= ~DHCPCD_INFORM; } else if (strncmp(arg, "subnet_mask=", strlen("subnet_mask=")) == 0) { if (parse_addr(&ifo->req_mask, NULL, p) != 0) return -1; } else if (strncmp(arg, "routes=", strlen("routes=")) == 0 || strncmp(arg, "static_routes=", strlen("static_routes=")) == 0 || strncmp(arg, "classless_static_routes=", strlen("classless_static_routes=")) == 0 || strncmp(arg, "ms_classless_static_routes=", strlen("ms_classless_static_routes=")) == 0) { np = strchr(p, ' '); if (np == NULL) { syslog(LOG_ERR, "all routes need a gateway"); return -1; } *np++ = '\0'; while (*np == ' ') np++; if (ifo->routes == NULL) { rt = ifo->routes = xmalloc(sizeof(*rt)); } else { rt = ifo->routes; while (rt->next) rt = rt->next; rt->next = xmalloc(sizeof(*rt)); rt = rt->next; } rt->next = NULL; if (parse_addr(&rt->dest, &rt->net, p) == -1 || parse_addr(&rt->gate, NULL, np) == -1) return -1; } else if (strncmp(arg, "routers=", strlen("routers=")) == 0) { if (ifo->routes == NULL) { rt = ifo->routes = xzalloc(sizeof(*rt)); } else { rt = ifo->routes; while (rt->next) rt = rt->next; rt->next = xmalloc(sizeof(*rt)); rt = rt->next; } rt->dest.s_addr = INADDR_ANY; rt->net.s_addr = INADDR_ANY; rt->next = NULL; if (parse_addr(&rt->gate, NULL, p) == -1) return -1; } else { s = 0; if (ifo->config != NULL) { while (ifo->config[s] != NULL) { if (strncmp(ifo->config[s], arg, p - arg) == 0) { free(ifo->config[s]); ifo->config[s] = xstrdup(arg); return 1; } s++; } } ifo->config = xrealloc(ifo->config, sizeof(char *) * (s + 2)); ifo->config[s] = xstrdup(arg); ifo->config[s + 1] = NULL; } break; case 'W': if (parse_addr(&addr, &addr2, arg) != 0) return -1; if (strchr(arg, '/') == NULL) addr2.s_addr = INADDR_BROADCAST; ifo->whitelist = xrealloc(ifo->whitelist, sizeof(in_addr_t) * (ifo->whitelist_len + 2)); ifo->whitelist[ifo->whitelist_len++] = addr.s_addr; ifo->whitelist[ifo->whitelist_len++] = addr2.s_addr; break; case 'X': if (parse_addr(&addr, &addr2, arg) != 0) return -1; if (strchr(arg, '/') == NULL) addr2.s_addr = INADDR_BROADCAST; ifo->blacklist = xrealloc(ifo->blacklist, sizeof(in_addr_t) * (ifo->blacklist_len + 2)); ifo->blacklist[ifo->blacklist_len++] = addr.s_addr; ifo->blacklist[ifo->blacklist_len++] = addr2.s_addr; break; case 'Z': ifdv = splitv(&ifdc, ifdv, arg); break; case O_ARPING: if (parse_addr(&addr, NULL, arg) != 0) return -1; ifo->arping = xrealloc(ifo->arping, sizeof(in_addr_t) * (ifo->arping_len + 1)); ifo->arping[ifo->arping_len++] = addr.s_addr; break; case O_DESTINATION: if (make_option_mask(ifo->dstmask, arg, 2) != 0) { if (errno == EINVAL) syslog(LOG_ERR, "option `%s' does not take" " an IPv4 address", arg); else syslog(LOG_ERR, "unknown option `%s'", arg); return -1; } break; case O_FALLBACK: free(ifo->fallback); ifo->fallback = xstrdup(arg); break; case O_NOIPV6RS: ifo->options &= ~DHCPCD_IPV6RS; break; case O_IPV6_RA_FORK: ifo->options &= ~DHCPCD_IPV6RA_REQRDNSS; break; default: return 0; } return 1; }
int main(int argc, char **argv) { srand(time(NULL)); int i, c; int pid_flags = 0; int mptcp = 0; int mtu = 0; char *user = NULL; char *local_port = NULL; char *local_addr = NULL; char *password = NULL; char *timeout = NULL; char *method = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; int remote_num = 0; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; ss_addr_t tunnel_addr = { .host = NULL, .port = NULL }; char *tunnel_addr_str = NULL; int option_index = 0; static struct option long_options[] = { { "mtu", required_argument, 0, 0 }, { "mptcp",no_argument, 0, 0 }, { "help", no_argument, 0, 0 }, { 0, 0, 0, 0 } }; opterr = 0; USE_TTY(); #ifdef ANDROID while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:P:huUvVA", long_options, &option_index)) != -1) { #else while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:huUvA", long_options, &option_index)) != -1) { #endif switch (c) { case 0: if (option_index == 0) { mtu = atoi(optarg); LOGI("set MTU to %d", mtu); } else if (option_index == 1) { mptcp = 1; LOGI("enable multipath TCP"); } else if (option_index == 2) { usage(); exit(EXIT_SUCCESS); } break; case 's': if (remote_num < MAX_REMOTE_NUM) { remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; } break; case 'p': remote_port = optarg; break; case 'l': local_port = optarg; break; case 'k': password = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'm': method = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'b': local_addr = optarg; break; case 'u': mode = TCP_AND_UDP; break; case 'U': mode = UDP_ONLY; break; case 'L': tunnel_addr_str = optarg; break; case 'a': user = optarg; break; #ifdef HAVE_SETRLIMIT case 'n': nofile = atoi(optarg); break; #endif case 'v': verbose = 1; break; case 'h': usage(); exit(EXIT_SUCCESS); case 'A': auth = 1; break; #ifdef ANDROID case 'V': vpn = 1; break; case 'P': prefix = optarg; break; #endif case '?': // The option character is not recognized. opterr = 1; break; } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (argc == 1) { if (conf_path == NULL) { conf_path = DEFAULT_CONF_PATH; } } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (remote_num == 0) { remote_num = conf->remote_num; for (i = 0; i < remote_num; i++) remote_addr[i] = conf->remote_addr[i]; } if (remote_port == NULL) { remote_port = conf->remote_port; } if (local_addr == NULL) { local_addr = conf->local_addr; } if (local_port == NULL) { local_port = conf->local_port; } if (password == NULL) { password = conf->password; } if (method == NULL) { method = conf->method; } if (timeout == NULL) { timeout = conf->timeout; } if (auth == 0) { auth = conf->auth; } if (tunnel_addr_str == NULL) { tunnel_addr_str = conf->tunnel_address; } if (mode == TCP_ONLY) { mode = conf->mode; } if (mtu == 0) { mtu = conf->mtu; } if (mptcp == 0) { mptcp = conf->mptcp; } #ifdef HAVE_SETRLIMIT if (nofile == 0) { nofile = conf->nofile; } /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile > 1024) { if (verbose) { LOGI("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif } if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL || local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } if (timeout == NULL) { timeout = "60"; } if (local_addr == NULL) { local_addr = "127.0.0.1"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } if (auth) { LOGI("onetime authentication enabled"); } // parse tunnel addr parse_addr(tunnel_addr_str, &tunnel_addr); if (tunnel_addr.port == NULL) { FATAL("tunnel port is not defined"); } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); signal(SIGINT, signal_cb); signal(SIGTERM, signal_cb); #endif // Setup keys LOGI("initializing ciphers... %s", method); int m = enc_init(password, method); // Setup proxy context struct listen_ctx listen_ctx; listen_ctx.tunnel_addr = tunnel_addr; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = ss_malloc(sizeof(struct sockaddr *) * remote_num); for (i = 0; i < remote_num; i++) { char *host = remote_addr[i].host; char *port = remote_addr[i].port == NULL ? remote_port : remote_addr[i].port; struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage, 1) == -1) { FATAL("failed to resolve the provided hostname"); } listen_ctx.remote_addr[i] = (struct sockaddr *)storage; } listen_ctx.timeout = atoi(timeout); listen_ctx.iface = iface; listen_ctx.method = m; listen_ctx.mptcp = mptcp; struct ev_loop *loop = EV_DEFAULT; if (mode != UDP_ONLY) { // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); if (listenfd == -1) { FATAL("bind() error:"); } if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error:"); } setnonblocking(listenfd); listen_ctx.fd = listenfd; ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx.io); } // Setup UDP if (mode != TCP_ONLY) { LOGI("UDP relay enabled"); init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0], get_sockaddr_len(listen_ctx.remote_addr[0]), tunnel_addr, mtu, m, auth, listen_ctx.timeout, iface); } if (mode == UDP_ONLY) { LOGI("TCP relay disabled"); } LOGI("listening at %s:%s", local_addr, local_port); // setuid if (user != NULL) { run_as(user); } ev_run(loop, 0); #ifdef __MINGW32__ winsock_cleanup(); #endif return 0; }
int main(int argc, char *argv[]){ FILE *fp; // stimulus file handle char filename[50] = "stim.txt"; // stimulus file name, can be overwritten on cmdline // if filename given on commandline use it otherwise use default filename if (argc == 2) {strcpy(filename, argv[1]);} else {strcpy(filename, "stim.txt");} int opt = 0; // parse the cmdline while ((opt = getopt(argc, argv, "i:p:")) != -1) { switch(opt) { case 'i': strcpy(filename, optarg); break; case 'p': available_pf = (u32) strtol(optarg,NULL,10); validate_pf_number(available_pf); break; case '?': if (optopt == 'i'){ printf("USAGE: -i <filename>\n\n"); return -1; } else if (optopt == 'p') { printf("USAGE: -p <numpages>\n\n"); return -1; } else { printf("Valid switches are:\n"); printf("\t -i <input_filename>\n\t -p <numpages>\n\n"); return -1; break; } } } // open the input file fp = fopen (filename,"r"); if (NULL == fp){ fprintf (stderr, "Failed to open input file. This is fatal!\n"); exit(0); } //call function to allocate memory to PD init_PD(); // loop through input file an feed commands to sim do { get_command(fp); if (strcmp(cmd, "-v") == MATCH) { printf("VMM Simulator Ver 0.1\n"); exit(-1); } else if (strcmp(cmd, "w") == MATCH || strcmp(cmd, "r") == MATCH ) { // update read/wrote/access statistics num_accesses ++; if (strcmp(cmd, "w") == MATCH) {num_writes ++;} else {num_reads ++;} parse_addr(addr); if ( t_flag == 1 ){ printf(" %s 0x%08X\n", cmd, addr); } if (is_PT_present(working_addr.PD_index) == 1) { //check the user page present if(is_UP_present(working_addr.PD_index, working_addr.PT_index) == 1) { total_cycles += 20; //if the address exist, it considers memory access //printf("get here few time\n"); } else //the PT exists but not the user page { if (available_pf == used_pf) // no pf avail then evict one page evict_page(); create_user_page(working_addr.PD_index, working_addr.PT_index,cmd); } } else // new PT and UP need to created { while (available_pf < (used_pf + 2)) // create 2 avail pf evict_page(); create_page_table(working_addr.PD_index, cmd); create_user_page(working_addr.PD_index, working_addr.PT_index, cmd); } } if (d_flag == 1){dump_vmm();} } while (strcmp (cmd, "EOF")); num_physical_frames = 1 + num_PT + num_UP; print_outputs(); }
static void parse_addr(char *s, size_t len, int is_from) { size_t pos = 0; int terminal = 0; /* unless this is a continuation... */ if (!WSP(s[pos]) && s[pos] != ',' && s[pos] != ';') { /* ... skip over everything before the ':' */ for (; pos < len && s[pos] != ':'; pos++) ; /* nothing */ /* ... and check & reset parser state */ parse_addr_terminal(is_from); } /* skip over ':' ',' ';' and whitespace */ for (; pos < len && !pstate.quote && (WSP(s[pos]) || s[pos] == ':' || s[pos] == ',' || s[pos] == ';'); pos++) ; /* nothing */ for (; pos < len; pos++) { if (!pstate.esc && !pstate.quote && s[pos] == '(') pstate.comment++; if (!pstate.comment && !pstate.esc && s[pos] == '"') pstate.quote = !pstate.quote; if (!pstate.comment && !pstate.quote && !pstate.esc) { if (s[pos] == ':') { /* group */ for (pos++; pos < len && WSP(s[pos]); pos++) ; /* nothing */ pstate.wpos = 0; } if (s[pos] == '\n' || s[pos] == '\r') break; if (s[pos] == ',' || s[pos] == ';') { terminal = 1; break; } if (s[pos] == '<') { pstate.brackets = 1; pstate.wpos = 0; } if (pstate.brackets && s[pos] == '>') terminal = 1; } if (!pstate.comment && !terminal && (!(!(pstate.quote || pstate.esc) && (s[pos] == '<' || WSP(s[pos]))))) { if (pstate.wpos >= sizeof(pstate.buf)) errx(1, "address exceeds buffer size"); pstate.buf[pstate.wpos++] = s[pos]; } if (!pstate.quote && pstate.comment && s[pos] == ')') pstate.comment--; if (!pstate.esc && !pstate.comment && !pstate.quote && s[pos] == '\\') pstate.esc = 1; else pstate.esc = 0; } if (terminal) parse_addr_terminal(is_from); for (; pos < len && (s[pos] == '\r' || s[pos] == '\n'); pos++) ; /* nothing */ if (pos < len) parse_addr(s + pos, len - pos, is_from); }
int main_html_server(int argc, char **argv) { struct server server; unsigned i, playing = 0, spectating = 0; char *ip, *port; const char *addr; sqlite3_stmt *res; unsigned nrow; const char *query = "SELECT" ALL_EXTENDED_SERVER_COLUMNS " FROM servers" " WHERE ip = ? AND port = ?"; if (argc != 2) { fprintf(stderr, "usage: %s <server_addr>\n", argv[0]); return EXIT_FAILURE; } if (!parse_addr(argv[1], &ip, &port)) return EXIT_NOT_FOUND; foreach_extended_server(query, &server, "ss", ip, port); if (!res) return EXIT_FAILURE; if (!nrow) return EXIT_NOT_FOUND; if (!read_server_clients(&server)) return EXIT_FAILURE; for (i = 0; i < server.num_clients; i++) server.clients[i].ingame ? playing++ : spectating++; /* Eventually, print them */ CUSTOM_TAB.name = escape(server.name); CUSTOM_TAB.href = ""; html_header(&CUSTOM_TAB, server.name, "/servers", NULL); html("<header id=\"server_header\">"); html("<section id=\"serverinfo\">"); html("<h2>%s</h2>", escape(server.name)); html("<ul>"); html("<li>%s</li><li>%s</li>", server.gametype, server.map); html("<li>%u / %u clients</li>", server.num_clients, server.max_clients); html("<li>"); html("%u players", playing); if (spectating) html(" + %u spectators", spectating); html("</li>"); html("</ul>"); html("</section>"); html("<section id=\"serveraddr\">"); html("<label for=\"serveraddr_input\">Server address</label>"); addr = build_addr(server.ip, server.port); html("<input type=\"text\" value=\"%s\" size=\"%u\" id=\"serveraddr_input\" readonly/>", addr, strlen(addr)); html("</section>"); html("</header>"); show_client_list(&server); html_footer("server", relurl("/servers/%s.json", addr)); return EXIT_SUCCESS; }
static SIM_RC memory_option_handler (SIM_DESC sd, sim_cpu *cpu, int opt, char *arg, int is_command) { switch (opt) { case OPTION_MEMORY_DELETE: if (strcasecmp (arg, "all") == 0) { while (STATE_MEMOPT (sd) != NULL) do_memopt_delete (sd, STATE_MEMOPT (sd)->level, STATE_MEMOPT (sd)->space, STATE_MEMOPT (sd)->addr); return SIM_RC_OK; } else { int level = 0; int space = 0; address_word addr = 0; parse_addr (arg, &level, &space, &addr); return do_memopt_delete (sd, level, space, addr); } case OPTION_MEMORY_REGION: { char *chp = arg; int level = 0; int space = 0; address_word addr = 0; address_word nr_bytes = 0; unsigned modulo = 0; /* parse the arguments */ chp = parse_addr (chp, &level, &space, &addr); if (*chp != ',') { sim_io_eprintf (sd, "Missing size for memory-region\n"); return SIM_RC_FAIL; } chp = parse_size (chp + 1, &nr_bytes, &modulo); /* old style */ if (*chp == ',') modulo = strtoul (chp + 1, &chp, 0); /* try to attach/insert it */ do_memopt_add (sd, level, space, addr, nr_bytes, modulo, &STATE_MEMOPT (sd), NULL); return SIM_RC_OK; } case OPTION_MEMORY_ALIAS: { char *chp = arg; int level = 0; int space = 0; address_word addr = 0; address_word nr_bytes = 0; unsigned modulo = 0; sim_memopt *entry; /* parse the arguments */ chp = parse_addr (chp, &level, &space, &addr); if (*chp != ',') { sim_io_eprintf (sd, "Missing size for memory-region\n"); return SIM_RC_FAIL; } chp = parse_size (chp + 1, &nr_bytes, &modulo); /* try to attach/insert the main record */ entry = do_memopt_add (sd, level, space, addr, nr_bytes, modulo, &STATE_MEMOPT (sd), NULL); /* now attach all the aliases */ while (*chp == ',') { int a_level = level; int a_space = space; address_word a_addr = addr; chp = parse_addr (chp + 1, &a_level, &a_space, &a_addr); do_memopt_add (sd, a_level, a_space, a_addr, nr_bytes, modulo, &entry->alias, entry->buffer); } return SIM_RC_OK; } case OPTION_MEMORY_SIZE: { int level = 0; int space = 0; address_word addr = 0; address_word nr_bytes = 0; unsigned modulo = 0; /* parse the arguments */ parse_size (arg, &nr_bytes, &modulo); /* try to attach/insert it */ do_memopt_add (sd, level, space, addr, nr_bytes, modulo, &STATE_MEMOPT (sd), NULL); return SIM_RC_OK; } case OPTION_MEMORY_CLEAR: { fill_byte_value = (unsigned8) 0; fill_byte_flag = 1; return SIM_RC_OK; break; } case OPTION_MEMORY_FILL: { unsigned long fill_value; parse_ulong_value (arg, &fill_value); if (fill_value > 255) { sim_io_eprintf (sd, "Missing fill value between 0 and 255\n"); return SIM_RC_FAIL; } fill_byte_value = (unsigned8) fill_value; fill_byte_flag = 1; return SIM_RC_OK; break; } case OPTION_MEMORY_INFO: { sim_memopt *entry; sim_io_printf (sd, "Memory maps:\n"); for (entry = STATE_MEMOPT (sd); entry != NULL; entry = entry->next) { sim_memopt *alias; sim_io_printf (sd, " memory"); if (entry->alias == NULL) sim_io_printf (sd, " region "); else sim_io_printf (sd, " alias "); if (entry->space != 0) sim_io_printf (sd, "0x%lx:", (long) entry->space); sim_io_printf (sd, "0x%08lx", (long) entry->addr); if (entry->level != 0) sim_io_printf (sd, "@0x%lx", (long) entry->level); sim_io_printf (sd, ",0x%lx", (long) entry->nr_bytes); if (entry->modulo != 0) sim_io_printf (sd, "%%0x%lx", (long) entry->modulo); for (alias = entry->alias; alias != NULL; alias = alias->next) { if (alias->space != 0) sim_io_printf (sd, "0x%lx:", (long) alias->space); sim_io_printf (sd, ",0x%08lx", (long) alias->addr); if (alias->level != 0) sim_io_printf (sd, "@0x%lx", (long) alias->level); } sim_io_printf (sd, "\n"); } return SIM_RC_OK; break; } default: sim_io_eprintf (sd, "Unknown memory option %d\n", opt); return SIM_RC_FAIL; } return SIM_RC_FAIL; }
/* Does DNS lookup for addr and puts resulting tox id in id_bin. */ void *dns3_lookup_thread(void *data) { ToxWindow *self = t_data.self; char inputdomain[MAX_STR_SIZE]; char name[MAX_STR_SIZE]; int namelen = parse_addr(t_data.addr, name, inputdomain); if (namelen == -1) { dns_error(self, "Must be a Tox ID or an address in the form username@domain"); killdns_thread(NULL); } char DNS_pubkey[DNS3_KEY_SIZE]; char domain[MAX_DOMAIN_SIZE]; int match = get_domain_match(DNS_pubkey, domain, inputdomain); if (match == -1) { dns_error(self, "Domain not found."); killdns_thread(NULL); } void *dns_obj = tox_dns3_new((uint8_t *) DNS_pubkey); if (dns_obj == NULL) { dns_error(self, "Core failed to create DNS object."); killdns_thread(NULL); } char string[MAX_DNS_REQST_SIZE + 1]; uint32_t request_id; int str_len = tox_generate_dns3_string(dns_obj, (uint8_t *) string, sizeof(string), &request_id, (uint8_t *) name, namelen); if (str_len == -1) { dns_error(self, "Core failed to generate DNS3 string."); killdns_thread(dns_obj); } string[str_len] = '\0'; u_char answer[PACKETSZ]; char d_string[MAX_DOMAIN_SIZE + MAX_DNS_REQST_SIZE + 10]; /* format string and create dns query */ snprintf(d_string, sizeof(d_string), "_%s._tox.%s", string, domain); int ans_len = res_query(d_string, C_IN, T_TXT, answer, sizeof(answer)); if (ans_len <= 0) { dns_error(self, "DNS query failed."); killdns_thread(dns_obj); } char ans_id[MAX_DNS_REQST_SIZE + 1]; /* extract TXT from DNS response */ if (parse_dns_response(self, answer, ans_len, ans_id) == -1) killdns_thread(dns_obj); char encrypted_id[MAX_DNS_REQST_SIZE + 1]; int prfx_len = strlen(TOX_DNS3_TXT_PREFIX); /* extract the encrypted ID from TXT response */ if (strncmp(ans_id, TOX_DNS3_TXT_PREFIX, prfx_len) != 0) { dns_error(self, "Bad DNS3 TXT response."); killdns_thread(dns_obj); } memcpy(encrypted_id, ans_id + prfx_len, ans_len - prfx_len); if (tox_decrypt_dns3_TXT(dns_obj, (uint8_t *) t_data.id_bin, (uint8_t *) encrypted_id, strlen(encrypted_id), request_id) == -1) { dns_error(self, "Core failed to decrypt DNS response."); killdns_thread(dns_obj); } pthread_mutex_lock(&Winthread.lock); cmd_add_helper(self, t_data.m, t_data.id_bin, t_data.msg); pthread_mutex_unlock(&Winthread.lock); killdns_thread(dns_obj); return 0; }
void read_ifaces(void) { struct sockaddr_nl addr; socklen_t addr_len = sizeof(addr); unsigned char buffer[4096]; int sock, len; struct { struct nlmsghdr nlh; struct rtgenmsg g; }req; print_dbg(0, "Searching for network interfaces...\n"); sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock < 0) { perror("socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE) failed"); exit(1); } memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; if (bind(sock, (struct sockaddr*)&addr, addr_len) < 0) { perror("bind(AF_NETLINK) failed"); exit(1); } req.nlh.nlmsg_len = sizeof(req); req.nlh.nlmsg_type = RTM_GETLINK; req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_REQUEST; req.nlh.nlmsg_pid = 0; req.nlh.nlmsg_seq = 1; req.g.rtgen_family = AF_PACKET; if (sendto(sock, (void*)&req, sizeof(req), 0, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("inarpd: sendto(RTM_GETLINK) failed"); exit(1); } while(1) { struct nlmsghdr *h = (struct nlmsghdr*)buffer; if ((len = recv(sock, buffer, sizeof(buffer), 0)) < 0) { perror("recv() failed"); exit(1); } while (len > 0) { if (!NLMSG_OK(h, (unsigned) len)) { error("NLMSG 0x%X not OK\n", h->nlmsg_type); break; } print_dbg(2, "NLMSG 0x%X\n", h->nlmsg_type); if (h->nlmsg_type == RTM_NEWLINK) parse_link(NLMSG_DATA(h), IFLA_PAYLOAD(h)); else if (h->nlmsg_type == RTM_NEWADDR) parse_addr(NLMSG_DATA(h), IFA_PAYLOAD(h)); else if (h->nlmsg_type == NLMSG_DONE) { if (req.nlh.nlmsg_type == RTM_GETADDR) { close(sock); return; } req.nlh.nlmsg_type = RTM_GETADDR; if (sendto(sock, (void*)&req, sizeof(req), 0, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("inarpd: sendto(RTM_GETADDR)" " failed"); exit(1); } break; } else error("Unknown netlink message type 0x%X\n", h->nlmsg_type); h = NLMSG_NEXT(h, len); } } }
static void dump_cmd(char **ptr) { static char *lastaddr = 0; static int lastcount = 20; char *addr = lastaddr; int count = lastcount, displacement; int force = 0, decode = 0; if (more_p(ptr)) { // you can't both "force" and "decode" - only one or the other, // or neither if (!strncmp(*ptr, "-f ", 3)) { force = 1; *ptr += 3; } else if (!strncmp(*ptr, "-d ", 3)) { decode = 1; *ptr += 3; } addr = parse_addr(ptr, !force); if (more_p(ptr)) count = parse_number(ptr); } if (count == 0) { printf("COUNT must be non-zero.\n"); return; } lastcount = count; if (count > 0) displacement = N_WORD_BYTES; else { displacement = -N_WORD_BYTES; count = -count; } boolean aligned = ((uword_t)addr & LOWTAG_MASK) == 0; if (decode && (!aligned || displacement < 0)) { printf("Sorry, can only decode if aligned and stepping forward\n"); decode = 0; } lispobj* next_object = decode ? (lispobj*)addr : 0; while (count-- > 0) { #ifndef LISP_FEATURE_ALPHA printf("%p: ", (os_vm_address_t) addr); #else printf("0x%08X: ", (u32) addr); #endif if (force || gc_managed_addr_p((lispobj)addr)) { #ifndef LISP_FEATURE_ALPHA unsigned long *lptr = (unsigned long *)addr; #else u32 *lptr = (u32 *)addr; #endif unsigned char *cptr = (unsigned char *)addr; #if N_WORD_BYTES == 8 printf("0x%016lx | %c%c%c%c%c%c%c%c", lptr[0], visible(cptr[0]), visible(cptr[1]), visible(cptr[2]), visible(cptr[3]), visible(cptr[4]), visible(cptr[5]), visible(cptr[6]), visible(cptr[7])); #else unsigned short *sptr = (unsigned short *)addr; printf("0x%08lx 0x%04x 0x%04x " "0x%02x 0x%02x 0x%02x 0x%02x " "%c%c" "%c%c", lptr[0], sptr[0], sptr[1], cptr[0], cptr[1], cptr[2], cptr[3], visible(cptr[0]), visible(cptr[1]), visible(cptr[2]), visible(cptr[3])); #endif #ifdef LISP_FEATURE_GENCGC if (aligned) { lispobj ptr = *(lispobj*)addr; int gen; if (is_lisp_pointer(ptr) && gc_managed_heap_space_p(ptr) && (gen = gc_gen_of(ptr, 99)) != 99) // say that static is 99 if (gen != 99) printf(" | %d", gen); } #endif if (decode && addr == (char*)next_object) { lispobj word = *addr; // ensure validity of widetag because crashing with // "no size function" would be worse than doing nothing if (word != 0 && !is_lisp_pointer(word) && valid_widetag_p(header_widetag(word))) { printf(" %s", widetag_names[header_widetag(word)>>2]); next_object += sizetab[header_widetag(word)](next_object); } else if (is_cons_half(word)) {
jconf_t * read_jconf(const char *file) { static jconf_t conf; memset(&conf, 0, sizeof(jconf_t)); char *buf; json_value *obj; FILE *f = fopen(file, "rb"); if (f == NULL) { FATAL("Invalid config path."); } fseek(f, 0, SEEK_END); long pos = ftell(f); fseek(f, 0, SEEK_SET); if (pos >= MAX_CONF_SIZE) { FATAL("Too large config file."); } buf = ss_malloc(pos + 1); if (buf == NULL) { FATAL("No enough memory."); } int nread = fread(buf, pos, 1, f); if (!nread) { FATAL("Failed to read the config file."); } fclose(f); buf[pos] = '\0'; // end of string json_settings settings = { 0UL, 0, NULL, NULL, NULL }; char error_buf[512]; obj = json_parse_ex(&settings, buf, pos, error_buf); if (obj == NULL) { FATAL(error_buf); } if (obj->type == json_object) { unsigned int i, j; for (i = 0; i < obj->u.object.length; i++) { char *name = obj->u.object.values[i].name; json_value *value = obj->u.object.values[i].value; if (strcmp(name, "server") == 0) { if (value->type == json_array) { for (j = 0; j < value->u.array.length; j++) { if (j >= MAX_REMOTE_NUM) { break; } json_value *v = value->u.array.values[j]; char *addr_str = to_string(v); parse_addr(addr_str, conf.remote_addr + j); ss_free(addr_str); conf.remote_num = j + 1; } } else if (value->type == json_string) { conf.remote_addr[0].host = to_string(value); conf.remote_addr[0].port = NULL; conf.remote_num = 1; } } else if (strcmp(name, "server_port") == 0) { conf.remote_port = to_string(value); } else if (strcmp(name, "local_address") == 0) { conf.local_addr = to_string(value); } else if (strcmp(name, "local_port") == 0) { conf.local_port = to_string(value); } else if (strcmp(name, "timeout") == 0) { conf.timeout = to_string(value); } else if (strcmp(name, "user") == 0) { conf.user = to_string(value); } else if (strcmp(name, "obfs") == 0) { conf.obfs = to_string(value); } else if (strcmp(name, "obfs_host") == 0) { conf.obfs_host = to_string(value); } else if (strcmp(name, "obfs_uri") == 0) { conf.obfs_uri = to_string(value); } else if (strcmp(name, "http_method") == 0) { conf.http_method = to_string(value); } else if (strcmp(name, "failover") == 0) { conf.failover = to_string(value); } else if (strcmp(name, "fast_open") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'fast_open' must be a boolean"); conf.fast_open = value->u.boolean; } else if (strcmp(name, "nofile") == 0) { check_json_value_type(value, json_integer, "invalid config file: option 'nofile' must be an integer"); conf.nofile = value->u.integer; } else if (strcmp(name, "nameserver") == 0) { conf.nameserver = to_string(value); } else if (strcmp(name, "dst_addr") == 0) { conf.dst_addr = to_string(value); } else if (strcmp(name, "mptcp") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'mptcp' must be a boolean"); conf.mptcp = value->u.boolean; } else if (strcmp(name, "ipv6_first") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'ipv6_first' must be a boolean"); conf.ipv6_first = value->u.boolean; } else if (strcmp(name, "reverse_proxy") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'reverse_proxy' must be a boolean"); conf.reverse_proxy = value->u.boolean; } } } else { FATAL("Invalid config file"); } ss_free(buf); json_value_free(obj); return &conf; }
bool rfc822::check_addr(const char* in) { #define VALID1(x) (((x) >= '0' && (x) <= '9') \ || ((x) >= 'a' && (x) <= 'z') \ || ((x) >= 'A' && (x) <= 'Z')) #define VALID2(x) (((x) >= '0' && (x) <= '9') \ || ((x) >= 'a' && (x) <= 'z') \ || ((x) >= 'A' && (x) <= 'Z') \ || (x) == '-' \ || (x) == '_' \ || (x) == '.') while (*in == ' ' || *in == '\t') in++; if (*in == ';' || *in == ',') return false; const rfc822_addr* addr = parse_addr(in); if (addr == NULL || addr->addr == NULL) return false; const char* at = addr->addr; //printf(">>%s, %s\r\n", addr->comment ? addr->comment : "null", addr->addr); if (!VALID1(*at)) return false; at++; while (*at) { if (*at == '@') { // 必须保证 @ 前一个字符的有效性遵守 VALID1 if (!VALID1(*(at - 1))) return false; break; } if (!VALID2(*at)) return false; at++; } if (*at != '@') return false; at++; int dot = 0; bool first = true; while (*at) { if (first) { // at: [a-z]|[A-Z]|[0-9] if (!VALID1(*at)) return false; first = false; } else if (*at == '.') { dot++; first = true; } else if (!VALID2(*at)) return false; at++; } if (!VALID1(*(at - 1)) || dot == 0) return false; return true; }
static void enable_connect(EVENT_KERNEL *ev, ACL_EVENT_FDTABLE *fdp) { const char *myname = "enable_connect"; DWORD SentLen = 0; struct sockaddr_in addr; unsigned short port; char *local_ip, *remote, buf[256]; ACL_SOCKET sock = ACL_VSTREAM_SOCK(fdp->stream); LPFN_CONNECTEX lpfnConnectEx = NULL; GUID GuidConnectEx = WSAID_CONNECTEX; int dwErr, dwBytes; static char *any_ip = "0.0.0.0"; memset(&fdp->event_write->overlapped, 0, sizeof(fdp->event_write->overlapped)); ACL_SAFE_STRNCPY(buf, ACL_VSTREAM_PEER(fdp->stream), sizeof(buf)); parse_addr(buf, &port, &local_ip, &remote); if (!local_ip || !*local_ip) local_ip = any_ip; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(local_ip); addr.sin_port = htons(0); if (bind(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr)) < 0) { acl_msg_fatal("%s(%d): bind local ip(%s) error(%s, %d), sock: %d", myname, __LINE__, local_ip, acl_last_serror(), acl_last_error(), (int) sock); } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons((short) port); addr.sin_addr.s_addr = inet_addr(remote); dwErr = WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidConnectEx, sizeof(GuidConnectEx), &lpfnConnectEx, sizeof(lpfnConnectEx), &dwBytes, NULL, NULL); if(dwErr == SOCKET_ERROR) acl_msg_fatal("%s(%d): WSAIoctl error(%s)", myname, __LINE__, acl_last_serror()); if (lpfnConnectEx(sock, (const struct sockaddr *) &addr, sizeof(struct sockaddr), NULL, 0, NULL, &fdp->event_write->overlapped) == FALSE && acl_last_error() !=ERROR_IO_PENDING) { acl_msg_warn("%s(%d): ConnectEx error(%s), sock(%d)", myname, __LINE__, acl_last_serror(), sock); } }
int main(int argc, char *argv[]) { if (argc < 2) { usage(argv[0]); } if ((fin = fopen(argv[1], "rb")) == 0) { fprintf(stderr, "Error: could not open file\n"); exit(1); } BYTE *fbuf = (BYTE *) malloc(16 * sizeof(BYTE)); pe = (PESTRUCT *) malloc(sizeof(PESTRUCT)); parse_pe_header(); printf("EP RVA: %.8X\n", pe->rvaep); printf("Code section RVA: %.8X\n", pe->rvacode); printf("Data section RVA: %.8X\n", pe->rvadata); printf("Image base: %.8X\n", pe->imagebase); printf("Size of code section: %.8X\n", pe->codesize); /* Get size of headers to know where code section starts */ fseek(fin, pe->offset + 84, SEEK_SET); fgets(fbuf, 4, fin); pe->codeoffset = lendian(fbuf, 4); printf("Code section offset: %.8X\n", pe->codeoffset); /* Get OEP address */ pe->oep = pe->imagebase + pe->rvacode; printf("OEP address: %.8X\n", pe->oep); printf("\n"); // Formatting /* Get max offset from total file size */ fseek(fin, 0L, SEEK_END); pe->maxoffset = ftell(fin); fseek(fin, pe->codeoffset, SEEK_SET); // Go to start of code section DWORD len; DWORD cur_addr = pe->oep; // First instruction at OEP DWORD addr; int i; int quit = 0; /* Start parsing and outputting 50 instructions at a time, waiting for user input after each block */ while (!feof(fin) && !quit) { printf(":"); /* Wait for user input */ int ch = _getch(); printf("\b"); // Erase character switch (ch) { case KEY_ESC: // Quit case 'q': quit = 1; break; case 'n': // Next instruction print_instr(&cur_addr); break; case ' ': // Next 32 instructions print_ninstr(&cur_addr, 50); break; case 'o': // Go back to OEP printf("\r \n"); // Clear line printf("EP RVA: %.8X\n", pe->rvaep); printf("Code section RVA: %.8X\n", pe->rvacode); printf("Data section RVA: %.8X\n", pe->rvadata); printf("Image base: %.8X\n", pe->imagebase); printf("Size of code section: %.8X\n", pe->codesize); printf("Code section offset: %.8X\n", pe->codeoffset); printf("OEP address: %.8X\n", pe->oep); printf("\n"); fseek(fin, pe->codeoffset, SEEK_SET); cur_addr = pe->oep; break; case 'g': { // Go to specific address printf("\r \n"); // Clear line printf("Go to address: "); char getaddr[32]; fgets(getaddr, sizeof(getaddr), stdin); // Get input if (getaddr[0] == '\n' || getaddr[0] == '\r') { printf("\n"); break; } // Blank input (cancel instruction) addr = strtol(getaddr, NULL, 16); // Parse input address if (!print_instr(&addr)) break; // Print the first instruction cur_addr = addr; break; } case 'f': { // Follow instruction at specific address printf("\r \n"); // Clear line printf("Address of instruction to follow: "); char addrstr[32]; fgets(addrstr, sizeof(addrstr), stdin); // Get input if (addrstr[0] == '\n' || addrstr[0] == '\r') { printf("\n"); break; } // Blank input (cancel instruction) addr = strtol(addrstr, NULL, 16); char *instr = get_instr(addr); if (!instr) break; // Error printf("%.8X\t%s\n", addr, instr); // Print instruction to follow printf("\t\tv\n"); addr = parse_addr(instr); if (!print_instr(&addr)) break; cur_addr = addr; free(instr); break; } case 'd': { // Dump data at specific address printf("\r \n"); // Clear line printf("Address to dump: "); char addrstr[32]; fgets(addrstr, sizeof(addrstr), stdin); // Get input if (addrstr[0] == '\n' || addrstr[0] == '\r') { printf("\n"); break; } // Blank input (cancel instruction) addr = strtol(addrstr, NULL, 16); if (!valid_addr(addr)) { printf("Address out of bounds\n"); break; } printf("Number of bytes to dump (default 16): "); char bytesstr[3]; fgets(bytesstr, sizeof(bytesstr), stdin); int bytes = strtol(bytesstr, NULL, 10); if (bytes == 0) bytes = 16; if (bytes > DUMP_MAX) { printf("Too high\n"); break; } print_dump(addr, bytes); printf("\n"); // Formatting break; } case 's': { // Search for a string in .data, .rdata, and .rsrc sections (no unicode support) printf("\r \n"); // Clear line printf("Search for string: "); char searchstr[STRLEN_MAX]; fgets(searchstr, sizeof(searchstr), stdin); // Get input if (searchstr[0] == '\n' || searchstr[0] == '\r') { printf("\n"); break; } // Blank input (cancel instruction) addr = find_string_addr(searchstr); // Find address of string if (addr == 0) { printf("String not found\n"); } else { print_dump_str(addr); // Print dump of matched string } printf("\n"); // Formatting break; } case 'e': { // Edit binary printf("\r \n"); // Clear line printf("Starting address for editing: "); char addrstr[32]; fgets(addrstr, sizeof(addrstr), stdin); // Get input if (addrstr[0] == '\n' || addrstr[0] == '\r') { printf("\n"); break; } // Blank input (cancel instruction) addr = strtol(addrstr, NULL, 16); if (!valid_addr(addr)) { printf("Address out of bounds\n"); break; } printf("Input hex bytes: "); char bytestr[STRLEN_MAX]; fgets(bytestr, sizeof(bytestr), stdin); // Get input char *edit_file = (char *) calloc(strlen(argv[1]) + 6, sizeof(char)); strncpy(edit_file, argv[1], strlen(argv[1]) - 4); strcat(edit_file, "_edit.exe"); // Edited file name: inputfilename_edit.exe save_edits_to_file(fin, edit_file, addr, bytestr); printf("Edited file %s saved\n\n", edit_file); free(edit_file); break; } case 'h': // Show help case '?': print_help(); break; // Special keys case SPECIAL_KEY: ch = _getch(); switch (ch) { case KEY_DOWN: // Next instruction print_instr(&cur_addr); break; case KEY_PGDN: // Next 32 instructions print_ninstr(&cur_addr, 50); break; case KEY_HOME: // Go back to OEP printf("\r \n"); // Clear line printf("EP RVA: %.8X\n", pe->rvaep); printf("Code section RVA: %.8X\n", pe->rvacode); printf("Data section RVA: %.8X\n", pe->rvadata); printf("Image base: %.8X\n", pe->imagebase); printf("Size of code section: %.8X\n", pe->codesize); printf("Code section offset: %.8X\n", pe->codeoffset); printf("OEP address: %.8X\n", pe->oep); printf("\n"); fseek(fin, pe->codeoffset, SEEK_SET); cur_addr = pe->oep; break; default: //printf("0x%X\n", ch); // DEBUGGING break; } break; default: //printf("0x%X\n", ch); // DEBUGGING break; } fflush(stdin); } free(fbuf); free(pe); fclose(fin); return 0; }
static int command(void) { int ret = 0; char *addr, *port; struct mls_elnet_frame *req = (struct mls_elnet_frame*)_req; unsigned int reqlen = sizeof(_req); struct mls_elnet_frame *res = (struct mls_elnet_frame*)_res; int reslen = sizeof(_res); /* target host */ if (parse_addr(_remote_host, &addr, &port) < 0) { ret = -1; goto out; } /* create request */ { int dlen; struct mls_eoj_code seoj, deoj; seoj.cgc = MLS_EL_CGC_PROFILE; seoj.clc = MLS_EL_CLC_NODEPROFILE; seoj.inc = 0x01; deoj = _eoj_code; mls_elnet_setup_frame_header(req, &seoj, &deoj, _esv_code, 1, 1); dlen = _setup_frame_data((req->data - 1), (reqlen - MLS_ELNET_FRAME_HEADER_LENGTH), _set_prop, _set_prop_len, _get_prop, _get_prop_len); if (dlen < 0) { errlog("Error _setup_frame_data(%d)\n", dlen); ret = dlen; goto out; } reqlen = MLS_ELNET_FRAME_HEADER_LENGTH - 1 + dlen; } /* RPC */ reslen = mls_elnet_rpc(_cln_ctx, addr, port, req, reqlen, res, reslen); if (reslen < 0) { errlog("Error mls_elnet_rpc(%d)\n", reslen); ret = -10; goto out; } /* * OK! valid response packet. */ /* check error code */ if (MLS_ELNET_ESV_IS_ERR_RES_GROUP(res->esv)) { errlog("Error response code (%02X)\n", res->esv); ret = -11; goto out; } /* output result */ output_data(&(res->opc)); ret = 0; out: return ret; }
const struct token * match_token(int *argc, char **argv[], const struct token table[]) { u_int i, match; const struct token *t = NULL; struct filter_set *fs; const char *word = *argv[0]; match = 0; for (i = 0; table[i].type != ENDTOKEN; i++) { switch (table[i].type) { case NOTOKEN: if (word == NULL || strlen(word) == 0) { match++; t = &table[i]; } break; case KEYWORD: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case FLAG: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; res.flags |= t->value; } break; case FAMILY: if (word == NULL) break; if (!strcmp(word, "inet") || !strcasecmp(word, "IPv4")) { match++; t = &table[i]; res.aid = AID_INET; } if (!strcmp(word, "inet6") || !strcasecmp(word, "IPv6")) { match++; t = &table[i]; res.aid = AID_INET6; } if (!strcasecmp(word, "VPNv4")) { match++; t = &table[i]; res.aid = AID_VPN_IPv4; } break; case ADDRESS: if (parse_addr(word, &res.addr)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case PEERADDRESS: if (parse_addr(word, &res.peeraddr)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case PREFIX: if (parse_prefix(word, &res.addr, &res.prefixlen)) { match++; t = &table[i]; if (t->value) res.action = t->value; } break; case ASTYPE: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { match++; t = &table[i]; res.as.type = t->value; } break; case ASNUM: if (parse_asnum(word, &res.as.as)) { match++; t = &table[i]; } break; case PEERDESC: if (!match && word != NULL && strlen(word) > 0) { if (strlcpy(res.peerdesc, word, sizeof(res.peerdesc)) >= sizeof(res.peerdesc)) errx(1, "neighbor description too " "long"); match++; t = &table[i]; } break; case RIBNAME: if (!match && word != NULL && strlen(word) > 0) { if (strlcpy(res.rib, word, sizeof(res.rib)) >= sizeof(res.rib)) errx(1, "rib name too long"); match++; t = &table[i]; } break; case COMMUNITY: if (word != NULL && strlen(word) > 0 && parse_community(word, &res)) { match++; t = &table[i]; } break; case LOCALPREF: case MED: case PREPNBR: case PREPSELF: case WEIGHT: case RTABLE: if (word != NULL && strlen(word) > 0 && parse_number(word, &res, table[i].type)) { match++; t = &table[i]; } break; case NEXTHOP: if (word != NULL && strlen(word) > 0 && parse_nexthop(word, &res)) { match++; t = &table[i]; } break; case PFTABLE: if (word != NULL && strlen(word) > 0) { if ((fs = calloc(1, sizeof(struct filter_set))) == NULL) err(1, NULL); if (strlcpy(fs->action.pftable, word, sizeof(fs->action.pftable)) >= sizeof(fs->action.pftable)) errx(1, "pftable name too long"); TAILQ_INSERT_TAIL(&res.set, fs, entry); match++; t = &table[i]; } break; case GETOPT: if (bgpctl_getopt(argc, argv, table[i].value)) { match++; t = &table[i]; } break; case FILENAME: if (word != NULL && strlen(word) > 0) { if ((res.mrtfd = open(word, O_RDONLY)) == -1) { /* * ignore error if path has no / and * does not exist. In hope to print * usage. */ if (errno == ENOENT && !strchr(word, '/')) break; err(1, "mrt open(%s)", word); } match++; t = &table[i]; } break; case ENDTOKEN: break; } } if (match != 1) { if (word == NULL) fprintf(stderr, "missing argument:\n"); else if (match > 1) fprintf(stderr, "ambiguous argument: %s\n", word); else if (match < 1) fprintf(stderr, "unknown argument: %s\n", word); return (NULL); } return (t); }
/* opposite of pfkey_sa() */ void pfkey_print_sa(struct sadb_msg *msg, int opts) { int i; struct ipsec_rule r; struct ipsec_key enckey, authkey; struct ipsec_transforms xfs; struct ipsec_addr_wrap src, dst; struct sadb_sa *sa; setup_extensions(msg); sa = (struct sadb_sa *)extensions[SADB_EXT_SA]; if (!(opts & IPSECCTL_OPT_SHOWKEY)) { extensions[SADB_EXT_KEY_AUTH] = NULL; extensions[SADB_EXT_KEY_ENCRYPT] = NULL; } bzero(&r, sizeof r); r.type |= RULE_SA; r.tmode = (msg->sadb_msg_satype != SADB_X_SATYPE_TCPSIGNATURE) && (sa->sadb_sa_flags & SADB_X_SAFLAGS_TUNNEL) ? IPSEC_TUNNEL : IPSEC_TRANSPORT; r.spi = ntohl(sa->sadb_sa_spi); switch (msg->sadb_msg_satype) { case SADB_SATYPE_AH: r.satype = IPSEC_AH; break; case SADB_SATYPE_ESP: r.satype = IPSEC_ESP; break; case SADB_X_SATYPE_IPCOMP: r.satype = IPSEC_IPCOMP; break; case SADB_X_SATYPE_TCPSIGNATURE: r.satype = IPSEC_TCPMD5; break; case SADB_X_SATYPE_IPIP: r.satype = IPSEC_IPIP; break; default: return; } bzero(&dst, sizeof dst); bzero(&src, sizeof src); parse_addr(extensions[SADB_EXT_ADDRESS_SRC], &src); parse_addr(extensions[SADB_EXT_ADDRESS_DST], &dst); r.src = &src; r.dst = &dst; if (r.satype == IPSEC_IPCOMP) { if (sa->sadb_sa_encrypt) { bzero(&xfs, sizeof xfs); r.xfs = &xfs; switch (sa->sadb_sa_encrypt) { case SADB_X_CALG_DEFLATE: xfs.encxf = &compxfs[COMPXF_DEFLATE]; break; case SADB_X_CALG_LZS: xfs.encxf = &compxfs[COMPXF_LZS]; break; } } } else if (r.satype == IPSEC_TCPMD5) { bzero(&authkey, sizeof authkey); parse_key(extensions[SADB_EXT_KEY_AUTH], &authkey); r.authkey = &authkey; } else if (sa->sadb_sa_encrypt || sa->sadb_sa_auth) { bzero(&xfs, sizeof xfs); r.xfs = &xfs; if (sa->sadb_sa_encrypt) { switch (sa->sadb_sa_encrypt) { case SADB_EALG_3DESCBC: xfs.encxf = &encxfs[ENCXF_3DES_CBC]; break; case SADB_EALG_DESCBC: xfs.encxf = &encxfs[ENCXF_DES_CBC]; break; case SADB_X_EALG_AES: xfs.encxf = &encxfs[ENCXF_AES]; break; case SADB_X_EALG_AESCTR: xfs.encxf = &encxfs[ENCXF_AESCTR]; break; case SADB_X_EALG_BLF: xfs.encxf = &encxfs[ENCXF_BLOWFISH]; break; case SADB_X_EALG_CAST: xfs.encxf = &encxfs[ENCXF_CAST128]; break; case SADB_EALG_NULL: xfs.encxf = &encxfs[ENCXF_NULL]; break; case SADB_X_EALG_SKIPJACK: xfs.encxf = &encxfs[ENCXF_SKIPJACK]; break; } bzero(&enckey, sizeof enckey); parse_key(extensions[SADB_EXT_KEY_ENCRYPT], &enckey); r.enckey = &enckey; } if (sa->sadb_sa_auth) { switch (sa->sadb_sa_auth) { case SADB_AALG_MD5HMAC: xfs.authxf = &authxfs[AUTHXF_HMAC_MD5]; break; case SADB_X_AALG_RIPEMD160HMAC: xfs.authxf = &authxfs[AUTHXF_HMAC_RIPEMD160]; break; case SADB_AALG_SHA1HMAC: xfs.authxf = &authxfs[AUTHXF_HMAC_SHA1]; break; case SADB_X_AALG_SHA2_256: xfs.authxf = &authxfs[AUTHXF_HMAC_SHA2_256]; break; case SADB_X_AALG_SHA2_384: xfs.authxf = &authxfs[AUTHXF_HMAC_SHA2_384]; break; case SADB_X_AALG_SHA2_512: xfs.authxf = &authxfs[AUTHXF_HMAC_SHA2_512]; break; } bzero(&authkey, sizeof authkey); parse_key(extensions[SADB_EXT_KEY_AUTH], &authkey); r.authkey = &authkey; } } ipsecctl_print_rule(&r, opts); if (opts & IPSECCTL_OPT_VERBOSE) { for (i = 0; i <= SADB_EXT_MAX; i++) if (extensions[i]) print_ext(extensions[i], msg); } fflush(stdout); }
static int parse_message(FILE *fin, int get_from, int tflag, FILE *fout) { char *buf; size_t len; uint i, cur = HDR_NONE; uint header_seen = 0, header_done = 0; memset(&pstate, 0, sizeof(pstate)); for (;;) { buf = fgetln(fin, &len); if (buf == NULL && ferror(fin)) err(1, "fgetln"); if (buf == NULL && feof(fin)) break; if (buf == NULL || len < 1) err(1, "fgetln weird"); /* account for \r\n linebreaks */ if (len >= 2 && buf[len - 2] == '\r' && buf[len - 1] == '\n') buf[--len - 1] = '\n'; if (len == 1 && buf[0] == '\n') /* end of header */ header_done = 1; if (!WSP(buf[0])) { /* whitespace -> continuation */ if (cur == HDR_FROM) parse_addr_terminal(1); if (cur == HDR_TO || cur == HDR_CC || cur == HDR_BCC) parse_addr_terminal(0); cur = HDR_NONE; } /* not really exact, if we are still in headers */ if (len + (buf[len - 1] == '\n' ? 0 : 1) >= LINESPLIT) msg.need_linesplit = 1; for (i = 0; !header_done && cur == HDR_NONE && i < nitems(keywords); i++) if (len > strlen(keywords[i].word) && !strncasecmp(buf, keywords[i].word, strlen(keywords[i].word))) cur = keywords[i].type; if (cur != HDR_NONE) header_seen = 1; if (cur != HDR_BCC) { send_line(fout, 0, "%.*s", (int)len, buf); if (buf[len - 1] != '\n') fputc('\n', fout); if (ferror(fout)) err(1, "write error"); } /* * using From: as envelope sender is not sendmail compatible, * but I really want it that way - maybe needs a knob */ if (cur == HDR_FROM) { msg.saw_from++; if (get_from) parse_addr(buf, len, 1); } if (tflag && (cur == HDR_TO || cur == HDR_CC || cur == HDR_BCC)) parse_addr(buf, len, 0); if (cur == HDR_DATE) msg.saw_date++; if (cur == HDR_MSGID) msg.saw_msgid++; if (cur == HDR_MIME_VERSION) msg.saw_mime_version = 1; if (cur == HDR_CONTENT_TYPE) msg.saw_content_type = 1; if (cur == HDR_CONTENT_DISPOSITION) msg.saw_content_disposition = 1; if (cur == HDR_CONTENT_TRANSFER_ENCODING) msg.saw_content_transfer_encoding = 1; if (cur == HDR_USER_AGENT) msg.saw_user_agent = 1; } return (!header_seen); }
static void stat_update_cb(EV_P_ ev_timer *watcher, int revents) { struct sockaddr_un svaddr, claddr; int sfd = -1; size_t msgLen; char resp[BUF_SIZE]; if (verbose) { LOGI("update traffic stat: tx: %"PRIu64" rx: %"PRIu64"", tx, rx); } snprintf(resp, BUF_SIZE, "stat: {\"%s\":%"PRIu64"}", server_port, tx + rx); msgLen = strlen(resp) + 1; ss_addr_t ip_addr = { .host = NULL, .port = NULL }; parse_addr(manager_address, &ip_addr); if (ip_addr.host == NULL || ip_addr.port == NULL) { sfd = socket(AF_UNIX, SOCK_DGRAM, 0); if (sfd == -1) { ERROR("stat_socket"); return; } memset(&claddr, 0, sizeof(struct sockaddr_un)); claddr.sun_family = AF_UNIX; snprintf(claddr.sun_path, sizeof(claddr.sun_path), "/tmp/shadowsocks.%s", server_port); unlink(claddr.sun_path); if (bind(sfd, (struct sockaddr *) &claddr, sizeof(struct sockaddr_un)) == -1) { ERROR("stat_bind"); close(sfd); return; } memset(&svaddr, 0, sizeof(struct sockaddr_un)); svaddr.sun_family = AF_UNIX; strncpy(svaddr.sun_path, manager_address, sizeof(svaddr.sun_path) - 1); if (sendto(sfd, resp, strlen(resp) + 1, 0, (struct sockaddr *) &svaddr, sizeof(struct sockaddr_un)) != msgLen) { ERROR("stat_sendto"); close(sfd); return; } unlink(claddr.sun_path); } else { struct sockaddr_storage storage; memset(&storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(ip_addr.host, ip_addr.port, &storage, 0) == -1) { ERROR("failed to parse the manager addr"); return; } sfd = socket(storage.ss_family, SOCK_DGRAM, 0); if (sfd == -1) { ERROR("stat_socket"); return; } size_t addr_len = get_sockaddr_len((struct sockaddr *)&storage); if (sendto(sfd, resp, strlen(resp) + 1, 0, (struct sockaddr *)&storage, addr_len) != msgLen) { ERROR("stat_sendto"); close(sfd); return; } } close(sfd); }
static void dump_cmd(char **ptr) { static char *lastaddr = 0; static int lastcount = 20; char *addr = lastaddr; int count = lastcount, displacement; if (more_p(ptr)) { addr = parse_addr(ptr); if (more_p(ptr)) count = parse_number(ptr); } if (count == 0) { printf("COUNT must be non-zero.\n"); return; } lastcount = count; if (count > 0) displacement = N_WORD_BYTES; else { displacement = -N_WORD_BYTES; count = -count; } while (count-- > 0) { #ifndef LISP_FEATURE_ALPHA printf("%p: ", (os_vm_address_t) addr); #else printf("0x%08X: ", (u32) addr); #endif if (is_valid_lisp_addr((os_vm_address_t)addr)) { #ifndef LISP_FEATURE_ALPHA unsigned long *lptr = (unsigned long *)addr; #else u32 *lptr = (u32 *)addr; #endif unsigned char *cptr = (unsigned char *)addr; #if N_WORD_BYTES == 8 printf("0x%016lx | %c%c%c%c%c%c%c%c\n", lptr[0], visible(cptr[0]), visible(cptr[1]), visible(cptr[2]), visible(cptr[3]), visible(cptr[4]), visible(cptr[5]), visible(cptr[6]), visible(cptr[7])); #else unsigned short *sptr = (unsigned short *)addr; printf("0x%08lx 0x%04x 0x%04x " "0x%02x 0x%02x 0x%02x 0x%02x " "%c%c" "%c%c\n", lptr[0], sptr[0], sptr[1], cptr[0], cptr[1], cptr[2], cptr[3], visible(cptr[0]), visible(cptr[1]), visible(cptr[2]), visible(cptr[3])); #endif } else printf("invalid Lisp-level address\n"); addr += displacement; } lastaddr = addr; }