static void demonize_start() { if (daemonize) { OOR_LOG(LDBG_1, "Starting the daemonizing process"); if ((pid = fork()) < 0) { exit_cleanup(); } umask(0); if (pid > 0){ exit(EXIT_SUCCESS); } if ((sid = setsid()) < 0){ exit_cleanup(); } if ((chdir("/")) < 0){ exit_cleanup(); } close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } }
uint16 get_del_for_flag(uint16 mode) { if (S_ISREG(mode)) return DEL_FOR_FILE; if (S_ISDIR(mode)) return DEL_FOR_DIR; if (S_ISLNK(mode)) return DEL_FOR_SYMLINK; if (IS_DEVICE(mode)) return DEL_FOR_DEVICE; if (IS_SPECIAL(mode)) return DEL_FOR_SPECIAL; exit_cleanup(RERR_UNSUPPORTED); /* IMPOSSIBLE */ }
JNIEXPORT void JNICALL Java_org_openoverlayrouter_noroot_OOR_1JNI_oor_1loop(JNIEnv * env, jclass cl) { oor_running = TRUE; ctrl_dev_run(ctrl_dev); /* EVENT LOOP */ while (oor_running) { sockmstr_wait_on_all_read(smaster); sockmstr_process_all(smaster); } /* event_loop returned: bad! */ OOR_LOG(LINF, "Exiting..."); exit_cleanup(); }
static void gpfs_add_attr(struct rsync_gpfs_attr *b, struct rsync_gpfs_attr2 *b2) { struct rsync_gpfs_attr *a; struct rsync_gpfs_attr2 *a2; if (!b) return; a = EXPAND_ITEM_LIST(&gpfs_attr_list, struct rsync_gpfs_attr, 1000); if (!a) { rprintf(FERROR, "failed to allocate gpfs attribute " "item (at count: %d)\n", (int)gpfs_attr_list.count); exit_cleanup(RERR_MALLOC); } a->buf = malloc(b->size); if (!a->buf) { rprintf(FERROR, "failed to allocate gpfs attribute " "size %u (at count: %d)\n", b->size, (int)gpfs_attr_list.count); exit_cleanup(RERR_MALLOC); } memcpy(a->buf, b->buf, b->size); a->size = b->size; /* calculate the second part */ a2 = EXPAND_ITEM_LIST(&gpfs_attr2_list, struct rsync_gpfs_attr2, 1000); if (!a2) { rprintf(FERROR, "failed to allocate gpfs attribute2 " "item (at count: %d)\n", (int)gpfs_attr2_list.count); exit_cleanup(RERR_MALLOC); } memcpy(a2, b2, sizeof(struct rsync_gpfs_attr2)); }
JNIEXPORT void JNICALL Java_org_lispmob_noroot_LISPmob_1JNI_lispd_1loop(JNIEnv * env, jclass cl) { lispd_running = TRUE; ctrl_dev_run(ctrl_dev); /* EVENT LOOP */ while (lispd_running) { sockmstr_wait_on_all_read(smaster); sockmstr_process_all(smaster); } /* event_loop returned: bad! */ LMLOG(LINF, "Exiting..."); exit_cleanup(); }
void init_signal(void) { sigset_t siglist; if(sigemptyset(&siglist) == -1) { perror("Unable to initialize signal list"); exit_cleanup(); } if(sigaddset(&siglist, SIGALRM) == -1) { perror("Unable to add SIGALRM signal to signal list"); exit_cleanup(); } if(sigaddset(&siglist, SIGINT) == -1) { perror("Unable to add SIGINT signal to signal list"); exit_cleanup(); } if(pthread_sigmask(SIG_BLOCK, &siglist, NULL) != 0) { perror("Unable to change signal mask"); exit_cleanup(); } }
/******************************************************************* return the DNS name of the client ******************************************************************/ char *client_name(int fd) { struct sockaddr sa; struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa); int length = sizeof(sa); static char name_buf[100]; struct hostent *hp; char **p; char *def = "UNKNOWN"; static int initialised; if (initialised) return name_buf; initialised = 1; strcpy(name_buf,def); if (getpeername(fd, &sa, &length)) { exit_cleanup(RERR_SOCKETIO); } /* Look up the remote host name. */ if ((hp = gethostbyaddr((char *) &sockin->sin_addr, sizeof(sockin->sin_addr), AF_INET))) { strlcpy(name_buf,(char *)hp->h_name,sizeof(name_buf)); } /* do a forward lookup as well to prevent spoofing */ hp = gethostbyname(name_buf); if (!hp) { strcpy(name_buf,def); rprintf(FERROR,"reverse name lookup failed\n"); } else { for (p=hp->h_addr_list;*p;p++) { if (memcmp(*p, &sockin->sin_addr, hp->h_length) == 0) { break; } } if (!*p) { strcpy(name_buf,def); rprintf(FERROR,"reverse name lookup mismatch - spoofed address?\n"); } } return name_buf; }
/* * Request to the kernel the routing table with the selected afi */ int request_route_table(uint32_t table, int afi) { struct nlmsghdr *nlh = NULL; struct rtmsg *rtm = NULL; char sndbuf[4096]; int rta_len = 0; int retval = 0; /* * Build the command */ memset(sndbuf, 0, 4096); nlh = (struct nlmsghdr *)sndbuf; rtm = (struct rtmsg *)(CO(sndbuf,sizeof(struct nlmsghdr))); rta_len = sizeof(struct rtmsg); nlh->nlmsg_len = NLMSG_LENGTH(rta_len); nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; nlh->nlmsg_type = RTM_GETROUTE; rtm->rtm_family = afi; if (table == 0){ rtm->rtm_table = RT_TABLE_MAIN; }else{ rtm->rtm_table = table; } rtm->rtm_protocol = RTPROT_STATIC; rtm->rtm_scope = RT_SCOPE_UNIVERSE; rtm->rtm_type = RTN_UNICAST; rtm->rtm_src_len = 0; rtm->rtm_tos = 0; rtm->rtm_dst_len = 0; retval = send(netlink_fd, sndbuf, NLMSG_LENGTH(rta_len), 0); if (retval < 0) { lispd_log_msg(LISP_LOG_CRIT, "request_route_table: send netlink command failed %s", strerror(errno)); exit_cleanup(); } return(GOOD); }
/** * \brief version of interrupt handled for Windows */ BOOL sigINT_handler(DWORD fdwCtrlType) { // output for DEBUG only std::cerr << "DEBUG: caught signal to interrupt: "; switch( fdwCtrlType ) { // Handle the CTRL-C signal. case CTRL_C_EVENT: std::cerr << "Ctrl-C event" << std::endl; break; // CTRL-CLOSE: confirm that the user wants to exit. case CTRL_CLOSE_EVENT: std::cerr << "Ctrl-Close event" << std::endl; break; // Pass other signals to the next handler. case CTRL_BREAK_EVENT: std::cerr << "Ctrl-Break event" << std::endl; break; case CTRL_LOGOFF_EVENT: std::cerr << "Ctrl-Logoff event" << std::endl; break; case CTRL_SHUTDOWN_EVENT: std::cerr << "Ctrl-Shutdown event" << std::endl; break; default: std::cerr << "Unknown event" << std::endl; break; } // TODO: dump summary, if needed // in case PCM is blocked just return and summary will be dumped in // calling function, if needed if( PCM::getInstance()->isBlocked() ) { return FALSE; } else { exit_cleanup(); return FALSE; // to prevent Warning } }
/** * Get the sockaddr for the client. * * If it comes in as an ipv4 address mapped into IPv6 format then we * convert it back to a regular IPv4. **/ void client_sockaddr(int fd, struct sockaddr_storage *ss, socklen_t *ss_len) { memset(ss, 0, sizeof *ss); if (getpeername(fd, (struct sockaddr *) ss, ss_len)) { /* FIXME: Can we really not continue? */ rsyserr(FLOG, errno, "getpeername on fd%d failed", fd); exit_cleanup(RERR_SOCKETIO); } #ifdef INET6 if (get_sockaddr_family(ss) == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)ss)->sin6_addr)) { /* OK, so ss is in the IPv6 family, but it is really * an IPv4 address: something like * "::ffff:10.130.1.2". If we use it as-is, then the * reverse lookup might fail or perhaps something else * bad might happen. So instead we convert it to an * equivalent address in the IPv4 address family. */ struct sockaddr_in6 sin6; struct sockaddr_in *sin; memcpy(&sin6, ss, sizeof sin6); sin = (struct sockaddr_in *)ss; memset(sin, 0, sizeof *sin); sin->sin_family = AF_INET; *ss_len = sizeof (struct sockaddr_in); #ifdef HAVE_SOCKADDR_IN_LEN sin->sin_len = *ss_len; #endif sin->sin_port = sin6.sin6_port; /* There is a macro to extract the mapped part * (IN6_V4MAPPED_TO_SINADDR ?), but it does not seem * to be present in the Linux headers. */ memcpy(&sin->sin_addr, &sin6.sin6_addr.s6_addr[12], sizeof sin->sin_addr); } #endif }
void check_batch_flags(void) { int i; if (protocol_version < 29) flag_ptr[7] = NULL; else if (protocol_version < 30) flag_ptr[9] = NULL; tweaked_append = append_mode == 1; tweaked_append_verify = append_mode == 2; #ifdef ICONV_OPTION tweaked_iconv = iconv_opt != NULL; #endif for (i = 0; flag_ptr[i]; i++) { int set = batch_stream_flags & (1 << i) ? 1 : 0; if (*flag_ptr[i] != set) { if (i == 9) { rprintf(FERROR, "%s specify the --iconv option to use this batch file.\n", set ? "Please" : "Do not"); exit_cleanup(RERR_SYNTAX); } if (INFO_GTE(MISC, 1)) { rprintf(FINFO, "%sing the %s option to match the batchfile.\n", set ? "Sett" : "Clear", flag_name[i]); } *flag_ptr[i] = set; } } if (protocol_version < 29) { if (recurse) xfer_dirs |= 1; else if (xfer_dirs < 2) xfer_dirs = 0; } if (tweaked_append) append_mode = 1; else if (tweaked_append_verify) append_mode = 2; }
/******************************************************************* return the IP addr of the client as a string ******************************************************************/ char *client_addr(int fd) { struct sockaddr sa; struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa); char buf[INET_ADDRSTRLEN]; int length = sizeof(sa); static char addr_buf[100]; static int initialised; if (initialised) return addr_buf; initialised = 1; if (getpeername(fd, &sa, &length)) { exit_cleanup(RERR_SOCKETIO); } strlcpy(addr_buf,(char *)inet_ntop( AF_INET, &sockin->sin_addr, buf, INET_ADDRSTRLEN ), sizeof(addr_buf)); return addr_buf; }
void gpfs_free_list(void) { int i = gpfs_attr_list.count; int rc; struct rsync_gpfs_attr *a = gpfs_attr_list.items; while(i) { gpfs_free_attr(a++); i--; } if (gpfs_bst) { rc = bst_free(gpfs_bst); if (rc) { rprintf(FERROR, "bst_free rc=%d\n", rc); exit_cleanup(RERR_CRASHED); } } }
/* This is only called by the sender. */ static void read_final_goodbye(int f_in, int f_out) { int i; if (protocol_version < 29) i = read_int(f_in); else { while ((i = read_int(f_in)) == the_file_list->count && read_shortint(f_in) == ITEM_IS_NEW) { /* Forward the keep-alive (no-op) to the receiver. */ write_int(f_out, the_file_list->count); write_shortint(f_out, ITEM_IS_NEW); } } if (i != -1) { rprintf(FERROR, "Invalid packet at end of run (%d) [%s]\n", i, who_am_i()); exit_cleanup(RERR_PROTOCOL); } }
/* This is like rprintf, but it also tries to print some * representation of the error code. Normally errcode = errno. * * Unlike rprintf, this always adds a newline and there should not be * one in the format string. * * Note that since strerror might involve dynamically loading a * message catalog we need to call it once before chroot-ing. */ void rsyserr(enum logcode code, int errcode, const char *format, ...) { va_list ap; char buf[BIGPATHBUFLEN]; size_t len; strlcpy(buf, RSYNC_NAME ": ", sizeof buf); len = (sizeof RSYNC_NAME ": ") - 1; va_start(ap, format); len += vsnprintf(buf + len, sizeof buf - len, format, ap); va_end(ap); if (len < sizeof buf) { len += snprintf(buf + len, sizeof buf - len, ": %s (%d)\n", strerror(errcode), errcode); } if (len >= sizeof buf) exit_cleanup(RERR_MESSAGEIO); rwrite(code, buf, len, 0); }
void start_server(int f_in, int f_out, int argc, char *argv[]) { set_nonblocking(f_in); set_nonblocking(f_out); io_set_sock_fds(f_in, f_out); setup_protocol(f_out, f_in); if (protocol_version >= 23) io_start_multiplex_out(); if (am_sender) { keep_dirlinks = 0; /* Must be disabled on the sender. */ if (need_messages_from_generator) io_start_multiplex_in(); recv_filter_list(f_in); do_server_sender(f_in, f_out, argc, argv); } else { do_server_recv(f_in, f_out, argc, argv); } exit_cleanup(0); }
int configure_mn(cfg_t *cfg) { lisp_xtr_t *xtr; shash_t *lcaf_ht; /* CREATE AND CONFIGURE MN */ if (ctrl_dev_create(MN_MODE, &ctrl_dev) != GOOD) { OOR_LOG(LCRIT, "Failed to create mobile node. Aborting!"); exit_cleanup(); } lcaf_ht = parse_lcafs(cfg); xtr = CONTAINER_OF(ctrl_dev, lisp_xtr_t, super); if (configure_tunnel_router(cfg, xtr, lcaf_ht)!=GOOD){ return (BAD); } if (parse_map_servers(cfg, xtr) != GOOD){ return (BAD); } if (parse_proxy_etrs(cfg, xtr) != GOOD){ return (BAD); } if (parse_proxy_itrs(cfg, xtr) != GOOD){ return (BAD); } if (parse_database_mapping(cfg, xtr, lcaf_ht) != GOOD){ return (BAD); } /* destroy the hash table */ shash_destroy(lcaf_ht); return (GOOD); }
static void handle_oor_command_line(int argc, char **argv) { struct gengetopt_args_info args_info; if (cmdline_parser(argc, argv, &args_info) != 0) { exit_cleanup(); } if (args_info.daemonize_given) { daemonize = TRUE; } if (args_info.config_file_given) { config_file = strdup(args_info.config_file_arg); } if (args_info.debug_given) { debug_level = args_info.debug_arg; } if (args_info.afi_given) { switch (args_info.afi_arg) { case 0: /* afi given = 4 */ default_rloc_afi = AF_INET; break; case 1: /* afi given = 6 */ default_rloc_afi = AF_INET6; break; default: OOR_LOG(LINF, "AFI must be IPv4 (-a 4) or IPv6 (-a 6)\n"); break; } } else { default_rloc_afi = AF_UNSPEC; } cmdline_parser_free(&args_info); }
/* A generic logging routine for send/recv, with parameter substitiution. */ static void log_formatted(enum logcode code, const char *format, const char *op, struct file_struct *file, const char *fname, int iflags, const char *hlink) { char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32]; char *p, *s, *c; const char *n; size_t len, total; int64 b; *fmt = '%'; /* We expand % codes one by one in place in buf. We don't * copy in the terminating null of the inserted strings, but * rather keep going until we reach the null of the format. */ total = strlcpy(buf, format, sizeof buf); if (total > MAXPATHLEN) { rprintf(FERROR, "log-format string is WAY too long!\n"); exit_cleanup(RERR_MESSAGEIO); } buf[total++] = '\n'; buf[total] = '\0'; for (p = buf; (p = strchr(p, '%')) != NULL; ) { int humanize = 0; s = p++; c = fmt + 1; while (*p == '\'') { humanize++; p++; } if (*p == '-') *c++ = *p++; while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8) *c++ = *p++; while (*p == '\'') { humanize++; p++; } if (!*p) break; *c = '\0'; n = NULL; /* Note for %h and %a: it doesn't matter what fd we pass to * client_{name,addr} because rsync_module will already have * forced the answer to be cached (assuming, of course, for %h * that lp_reverse_lookup(module_id) is true). */ switch (*p) { case 'h': if (am_daemon) { n = lp_reverse_lookup(module_id) ? client_name(0) : undetermined_hostname; } break; case 'a': if (am_daemon) n = client_addr(0); break; case 'l': strlcat(fmt, "s", sizeof fmt); snprintf(buf2, sizeof buf2, fmt, do_big_num(F_LENGTH(file), humanize, NULL)); n = buf2; break; case 'U': strlcat(fmt, "u", sizeof fmt); snprintf(buf2, sizeof buf2, fmt, uid_ndx ? F_OWNER(file) : 0); n = buf2; break; case 'G': if (!gid_ndx || file->flags & FLAG_SKIP_GROUP) n = "DEFAULT"; else { strlcat(fmt, "u", sizeof fmt); snprintf(buf2, sizeof buf2, fmt, F_GROUP(file)); n = buf2; } break; case 'p': strlcat(fmt, "d", sizeof fmt); snprintf(buf2, sizeof buf2, fmt, (int)getpid()); n = buf2; break; case 'M': n = c = timestring(file->modtime); while ((c = strchr(c, ' ')) != NULL) *c = '-'; break; case 'B': c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1; permstring(c, file->mode); n = c + 1; /* skip the type char */ break; case 'o': n = op; break; case 'f': if (fname) { c = f_name_buf(); strlcpy(c, fname, MAXPATHLEN); } else c = f_name(file, NULL); if (am_sender && F_PATHNAME(file)) { pathjoin(buf2, sizeof buf2, F_PATHNAME(file), c); clean_fname(buf2, 0); if (fmt[1]) { strlcpy(c, buf2, MAXPATHLEN); n = c; } else n = buf2; } else if (am_daemon && *c != '/') { pathjoin(buf2, sizeof buf2, curr_dir + module_dirlen, c); clean_fname(buf2, 0); if (fmt[1]) { strlcpy(c, buf2, MAXPATHLEN); n = c; } else n = buf2; } else { clean_fname(c, 0); n = c; } if (*n == '/') n++; break; case 'n': if (fname) { c = f_name_buf(); strlcpy(c, fname, MAXPATHLEN); } else c = f_name(file, NULL); if (S_ISDIR(file->mode)) strlcat(c, "/", MAXPATHLEN); n = c; break; case 'L': if (hlink && *hlink) { n = hlink; strlcpy(buf2, " => ", sizeof buf2); } else if (S_ISLNK(file->mode) && !fname) { n = F_SYMLINK(file); strlcpy(buf2, " -> ", sizeof buf2); } else { n = ""; if (!fmt[1]) break; strlcpy(buf2, " ", sizeof buf2); } strlcat(fmt, "s", sizeof fmt); snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n); n = buf2; break; case 'm': n = lp_name(module_id); break; case 't': n = timestring(time(NULL)); break; case 'P': n = full_module_path; break; case 'u': n = auth_user; break; case 'b': case 'c': if (!(iflags & ITEM_TRANSFER)) b = 0; else if ((!!am_sender) ^ (*p == 'c')) b = total_data_written - initial_data_written; else b = total_data_read - initial_data_read; strlcat(fmt, "s", sizeof fmt); snprintf(buf2, sizeof buf2, fmt, do_big_num(b, humanize, NULL)); n = buf2; break; case 'C': n = NULL; if (S_ISREG(file->mode)) { if (always_checksum && canonical_checksum(checksum_type)) n = sum_as_hex(checksum_type, F_SUM(file)); else if (iflags & ITEM_TRANSFER && canonical_checksum(xfersum_type)) n = sum_as_hex(xfersum_type, sender_file_sum); } if (!n) { int checksum_len = csum_len_for_type(always_checksum ? checksum_type : xfersum_type); memset(buf2, ' ', checksum_len*2); buf2[checksum_len*2] = '\0'; n = buf2; } break; case 'i': if (iflags & ITEM_DELETED) { n = "*deleting "; break; } n = c = buf2 + MAXPATHLEN - 32; c[0] = iflags & ITEM_LOCAL_CHANGE ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c' : !(iflags & ITEM_TRANSFER) ? '.' : !local_server && *op == 's' ? '<' : '>'; if (S_ISLNK(file->mode)) { c[1] = 'L'; c[3] = '.'; c[4] = !(iflags & ITEM_REPORT_TIME) ? '.' : !preserve_times || !receiver_symlink_times || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't'; } else { c[1] = S_ISDIR(file->mode) ? 'd' : IS_SPECIAL(file->mode) ? 'S' : IS_DEVICE(file->mode) ? 'D' : 'f'; c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's'; c[4] = !(iflags & ITEM_REPORT_TIME) ? '.' : !preserve_times ? 'T' : 't'; } c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c'; c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p'; c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o'; c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g'; c[8] = !(iflags & ITEM_REPORT_ATIME) ? '.' : 'u'; c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a'; c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x'; c[11] = '\0'; if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) { char ch = iflags & ITEM_IS_NEW ? '+' : '?'; int i; for (i = 2; c[i]; i++) c[i] = ch; } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') { int i; for (i = 2; c[i]; i++) { if (c[i] != '.') break; } if (!c[i]) { for (i = 2; c[i]; i++) c[i] = ' '; } } break; } /* "n" is the string to be inserted in place of this % code. */ if (!n) continue; if (n != buf2 && fmt[1]) { strlcat(fmt, "s", sizeof fmt); snprintf(buf2, sizeof buf2, fmt, n); n = buf2; } len = strlen(n); /* Subtract the length of the escape from the string's size. */ total -= p - s + 1; if (len + total >= (size_t)sizeof buf) { rprintf(FERROR, "buffer overflow expanding %%%c -- exiting\n", p[0]); exit_cleanup(RERR_MESSAGEIO); } /* Shuffle the rest of the string along to make space for n */ if (len != (size_t)(p - s + 1)) memmove(s + len, p + 1, total - (s - buf) + 1); total += len; /* Insert the contents of string "n", but NOT its null. */ if (len) memcpy(s, n, len); /* Skip over inserted string; continue looking */ p = s + len; } rwrite(code, buf, total, 0); }
/* this is the underlying (unformatted) rsync debugging function. Call * it with FINFO, FERROR_*, FWARNING, FLOG, or FCLIENT. Note: recursion * can happen with certain fatal conditions. */ void rwrite(enum logcode code, const char *buf, int len, int is_utf8) { int trailing_CR_or_NL; FILE *f = msgs2stderr ? stderr : stdout; #ifdef ICONV_OPTION iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck; #else #ifdef ICONV_CONST iconv_t ic = ic_chck; #endif #endif if (len < 0) exit_cleanup(RERR_MESSAGEIO); if (msgs2stderr) { if (!am_daemon) { if (code == FLOG) return; goto output_msg; } if (code == FCLIENT) return; code = FLOG; } else if (send_msgs_to_gen) { assert(!is_utf8); /* Pass the message to our sibling in native charset. */ send_msg((enum msgcode)code, buf, len, 0); return; } if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */ code = FERROR; else if (code == FERROR_UTF8) { is_utf8 = 1; code = FERROR; } if (code == FCLIENT) code = FINFO; else if (am_daemon || logfile_name) { static int in_block; char msg[2048]; int priority = code == FINFO || code == FLOG ? LOG_INFO : LOG_WARNING; if (in_block) return; in_block = 1; if (!log_initialised) log_init(0); strlcpy(msg, buf, MIN((int)sizeof msg, len + 1)); logit(priority, msg); in_block = 0; if (code == FLOG || (am_daemon && !am_server)) return; } else if (code == FLOG) return; if (quiet && code == FINFO) return; if (am_server) { enum msgcode msg = (enum msgcode)code; if (protocol_version < 30) { if (msg == MSG_ERROR) msg = MSG_ERROR_XFER; else if (msg == MSG_WARNING) msg = MSG_INFO; } /* Pass the message to the non-server side. */ if (send_msg(msg, buf, len, !is_utf8)) return; if (am_daemon) { /* TODO: can we send the error to the user somehow? */ return; } f = stderr; } output_msg: switch (code) { case FERROR_XFER: got_xfer_error = 1; /* FALL THROUGH */ case FERROR: case FERROR_UTF8: case FERROR_SOCKET: case FWARNING: f = stderr; break; case FLOG: case FINFO: case FCLIENT: break; default: fprintf(stderr, "Unknown logcode in rwrite(): %d [%s]\n", (int)code, who_am_i()); exit_cleanup(RERR_MESSAGEIO); } if (output_needs_newline) { fputc('\n', f); output_needs_newline = 0; } trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r') ? buf[--len] : 0; if (len && buf[0] == '\r') { fputc('\r', f); buf++; len--; } #ifdef ICONV_CONST if (ic != (iconv_t)-1) { xbuf outbuf, inbuf; char convbuf[1024]; int ierrno; INIT_CONST_XBUF(outbuf, convbuf); INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1); while (inbuf.len) { iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT); ierrno = errno; if (outbuf.len) { filtered_fwrite(f, convbuf, outbuf.len, 0); outbuf.len = 0; } if (!ierrno || ierrno == E2BIG) continue; fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++)); inbuf.len--; } } else #endif filtered_fwrite(f, buf, len, !allow_8bit_chars); if (trailing_CR_or_NL) { fputc(trailing_CR_or_NL, f); fflush(f); } }
int main(int const argc, char const* const* argv) { openlog(NULL, LOG_NDELAY, LOG_DAEMON); PT_LOG("starting %s\n", argv[0]); memset(&g_hs, 0, sizeof(g_hs)); if (argc != 3) { PT_LOG("wrong syntax: should be %s <target_id> <stubdom_id>", argv[0]); return -1; } g_hs.stubdom_id = atoi(argv[2]); if (g_hs.stubdom_id <= 0) { PT_LOG("bad stubdom id (%d)", g_hs.stubdom_id); return -1; } signal(SIGINT, signal_handler); if (init_helper_state(&g_hs) != 0) { PT_LOG("failed to init helper!\n"); return -1; } while (!pending_exit) { int ret; uint8_t io_buf[MAX_V4V_MSG_SIZE] = {0,}; PT_DEBUG("wait for command from stubdom (%d)", g_hs.stubdom_id); /* updates global remote_addr on per-packet basis */ ret = v4v_recvfrom(g_hs.v4v_fd, io_buf, sizeof(io_buf), 0, &g_hs.remote_addr); if (ret < 0) { PT_LOG("v4v_recvfrom failed!\n"); break; } switch (io_buf[0]) { case ATAPI_PTV4V_OPEN: PT_LOG("ATAPI_PTV4V_OPEN\n"); ret = atapi_ptv4v_open(&g_hs, io_buf, ret); break; case ATAPI_PTV4V_SG_IO: PT_DEBUG("ATAPI_PTV4V_SG_IO\n"); ret = atapi_ptv4v_sg_io(&g_hs, io_buf, ret); break; case ATAPI_PTV4V_SG_GET_RESERVED_SIZE: PT_LOG("ATAPI_PTV4V_SG_GET_RESERVED_SIZE\n"); ret = atapi_ptv4v_sg_get_reserved_size(&g_hs, io_buf, ret); break; case ATAPI_PTV4V_ACQUIRE_LOCK: PT_LOG("ATAPI_PTV4V_ACQUIRE_LOCK\n"); ret = atapi_ptv4v_acquire_lock(&g_hs, io_buf, ret); break; case ATAPI_PTV4V_RELEASE_LOCK: PT_LOG("ATAPI_PTV4V_RELEASE_LOCK\n"); ret = atapi_ptv4v_release_lock(&g_hs, io_buf, ret); break; default: PT_LOG("bad command = %d", io_buf[0]); ret = -1; break; } if (ret < 0) { PT_LOG("command failed!\n"); break; } } PT_LOG("exiting...\n"); exit_cleanup(0); return 0; }
static void signal_handler(int sig) { PT_LOG("handle signal %d", sig); exit_cleanup(0); }
/** \brief Main function. * * @param argc Number of arguments from the system. * @param argv Arguments from the system. * @return Program exit code. */ int main(int argc, char **argv) { // Option arguments. static const struct option opts_long[] = { { "2chan", no_argument, NULL, '2' }, { "benchmark", no_argument, NULL, 'h' }, { "enable-case", no_argument, NULL, 'c' }, { "help", no_argument, NULL, 'h' }, { "enable-leet", no_argument, NULL, 'l' }, { "generate", no_argument, NULL, 'g' }, { "nthreads", required_argument, NULL, 'n' }, { "progress-file", required_argument, NULL, 'p' }, { "start-from", required_argument, NULL, 's' }, { "wildcard", no_argument, NULL, 'w' }, { NULL, 0, 0, 0 } }; static const char *opts_short = "2cbhlgn:p:s:w"; // Local args. uint8_t enable_generate = 0, enable_leet = 0, enable_case = 0, enable_wildcard = 0; while(1) { int indexptr = 0; int opt = getopt_long(argc, argv, opts_short, opts_long, &indexptr); if(opt == -1) { break; } switch(opt) { case '2': if(einfo.name) { fputs("Tripcode algorithm may only be specified once.", stderr); exit_cleanup(); return 1; } einfo = encrypt_info_2chan; break; case 'b': flag_print_benchmarks = 1; break; case 'c': enable_case = 1; break; case 'h': puts(usage); exit_cleanup(); return 0; case 'l': enable_leet = 1; break; case 'g': enable_generate = 1; break; case 'n': thread_count = strtol(optarg, NULL, 10); if((thread_count == LONG_MAX) || (thread_count == LONG_MIN)) { fprintf(stderr, "Invalid thread count: %i\n", (int)thread_count); exit_cleanup(); return 1; } break; case 'p': if(progress_filename) { fputs("Progress file may only be specified once.", stderr); exit_cleanup(); return 1; } progress_filename = strdup(optarg); break; case 's': if(current_tripcode) { fputs("Starting code may only be specified once.", stderr); exit_cleanup(); return 1; } current_tripcode_len = strlen(optarg); current_tripcode = memdup(optarg, current_tripcode_len + 1); printf("Using starting code: %s\n", current_tripcode); break; case 'w': enable_wildcard = 1; break; default: puts(usage); exit_cleanup(); return 1; } } while(optind < argc) { char *opt = argv[optind++]; size_t len = strlen(opt); if(len > 0) { if(!search_tripcodes) { search_tripcodes = (tripcode_t*)malloc(sizeof(tripcode_t)); search_tripcode_count = 1; } else { search_tripcodes = (tripcode_t*)realloc(search_tripcodes, sizeof(tripcode_t) * (++search_tripcode_count)); } tripcode_t *trip = search_tripcodes + (search_tripcode_count - 1); trip->trip = (char*)memdup(opt, len + 1); trip->len = len; } else { fputs("Empty string are not valid searching.", stderr); return 1; } } // Sanity check for tripcode count. if(search_tripcode_count <= 0) { fprintf(stderr, "Please specify at least one tripcode.\n"); return 1; } // If no algo selected yet, pick 2chan. if(!einfo.name) { einfo = encrypt_info_2chan; } printf("Using algorithm: %s\n", einfo.name); str_enumerate_init(einfo.search_space); // Thread cap based on search space size. { long int sspacesize = get_search_space_size(); if(sspacesize < thread_count) { printf("WARNING: current search space limits to %i threads\n", (int)sspacesize); thread_count = sspacesize; } } // Decide character transform. if(!enable_generate) { char_transform_func = char_transform_identity; strstr_func = strstr_normal; printf("Using character transform: "); if(enable_case && !enable_leet && !enable_wildcard) { puts("none"); } else { unsigned flag_line = 0; if(enable_case) { if(enable_leet) { flag_line = fprint_list_spacing(stdout, flag_line); printf("1337"); char_transform_func = char_transform_leet; } } else { flag_line = fprint_list_spacing(stdout, flag_line); printf("case_insensitive"); char_transform_func = char_transform_nocase; if(enable_leet) { flag_line = fprint_list_spacing(stdout, flag_line); printf("1337"); char_transform_func = char_transform_nocase_leet; } } if(enable_wildcard) { flag_line = fprint_list_spacing(stdout, flag_line); printf("wildcard"); strstr_func = strstr_wildcard; } puts(""); } } // If generate trip requested, do it and exit. if(enable_generate) { for(size_t ii = 0; (ii < search_tripcode_count); ++ii) { tripcode_t *trip = search_tripcodes + ii; char *enc = einfo.encrypt_function(trip->trip, trip->len); printf("Password %s encrypts to tripcode %s\n", trip->trip, enc); free(enc); } exit_cleanup(); return 0; } // Sanity check for tripcode lengths. for(size_t ii = 0; (ii < search_tripcode_count); ++ii) { tripcode_t *trip = search_tripcodes + ii; if(trip->len > einfo.max_code_length) { fprintf(stderr, "Code %s is %u chars long, too much for current algo (%u).\n", trip->trip, (unsigned)(trip->len), (unsigned)(einfo.max_code_length - 1)); exit_cleanup(); return 1; } // Perform case transform in precalc! for(size_t jj = 0; (jj < trip->len); ++jj) { trip->trip[jj] = (char)char_transform_func(trip->trip[jj]); } } // Only read current tripcode if it's not yet specified. if(progress_filename) { char *prog = progress_read(progress_filename); if(prog) { if(current_tripcode) { fprintf(stderr, "Not overwriting starting code from file: %s\n", prog); free(prog); } else { printf("Using starting code from file: %s\n", prog); current_tripcode = prog; current_tripcode_len = strlen(prog); } } } // Try the initial tripcode if it has been specified. int64_t benchmark_processed = 0; if(current_tripcode) { benchmark_processed += einfo.test_function(current_tripcode, current_tripcode_len, stdout); } pthread_cond_init(&term_cond, NULL); pthread_mutex_init(&term_mutex, NULL); signal(SIGINT, tripcrunch_signal_handler); signal(SIGTERM, tripcrunch_signal_handler); // Enter critical section and create all threads. pthread_mutex_lock(&term_mutex); pthread_t *threads = (pthread_t*)malloc(sizeof(pthread_t) * (unsigned)thread_count); for(int ii = 0; (ii < thread_count); ++ii) { // Reserve the thread info for passing to the threads. thread_info_t *tinfo = (thread_info_t*)malloc(sizeof(thread_info_t)); // Give the next tripcode to the string. current_tripcode = str_enumerate_1(current_tripcode, ¤t_tripcode_len); tinfo->trip.trip = memdup(current_tripcode, current_tripcode_len + 1); tinfo->trip.len = current_tripcode_len; int err = pthread_create(threads + ii, NULL, threadfunc_tripcrunch, tinfo); if(err) { fprintf(stderr, "ERROR %s\n", strerror(err)); return 1; // Should never happen, okay to not clean up. } } // Wait for exit, then leave critical section. int64_t benchmark_start = get_current_time_int64(); pthread_mutex_unlock(&term_mutex); // Immediately start joining the threads. for(int ii = 0; (ii < thread_count); ++ii) { void **thr_ret = NULL; pthread_join(threads[ii], thr_ret); if(!thr_ret) { fprintf(stderr, "ERROR: no return value from thread %i\n", ii); return 1; // Should never happen, okay to not clean up. } thread_info_t *tinfo = (thread_info_t*)(*thr_ret); char *trip = tinfo->trip.trip; size_t len = tinfo->trip.len; int64_t count = tinfo->count; printf("Thread %i: %s (%.0f trips)\n", ii, tinfo->trip.trip, (double)(tinfo->count)); benchmark_processed += count; int cmp = str_enumcmp(current_tripcode, current_tripcode_len, trip, len); if((cmp > 0) || ((ii <= 0) && count)) { free(current_tripcode); current_tripcode = memdup(trip, len + 1); current_tripcode_len = len; } free(trip); free(tinfo); } // All threads have been joined, time to end the benchmark and free the // thread table. int64_t benchmark_end = get_current_time_int64(); free(threads); // Must save progress before other cleanup. if(progress_filename) { progress_save(progress_filename, current_tripcode); } // Current tripcode is not necessarily initialized. if(current_tripcode) { printf("Last search: %s\n", current_tripcode); } exit_cleanup(); // Only print benchmarks if requested. if(flag_print_benchmarks) { double trips = (double)benchmark_processed, secs = (double)(benchmark_end - benchmark_start) / 1000000.0; printf("Benchmark: %.0f trips / %.2f secs -> %.2f trips/sec\n", trips, secs, trips / secs); } pthread_cond_destroy(&term_cond); pthread_mutex_destroy(&term_mutex); return 0; }
static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix, int argc, const char **argv) { char tmpdir[PATH_MAX]; struct strbuf info = STRBUF_INIT, lpath = STRBUF_INIT; struct strbuf rpath = STRBUF_INIT, buf = STRBUF_INIT; struct strbuf ldir = STRBUF_INIT, rdir = STRBUF_INIT; struct strbuf wtdir = STRBUF_INIT; char *lbase_dir, *rbase_dir; size_t ldir_len, rdir_len, wtdir_len; const char *workdir, *tmp; int ret = 0, i; FILE *fp; struct hashmap working_tree_dups, submodules, symlinks2; struct hashmap_iter iter; struct pair_entry *entry; struct index_state wtindex; struct checkout lstate, rstate; int rc, flags = RUN_GIT_CMD, err = 0; struct child_process child = CHILD_PROCESS_INIT; const char *helper_argv[] = { "difftool--helper", NULL, NULL, NULL }; struct hashmap wt_modified, tmp_modified; int indices_loaded = 0; workdir = get_git_work_tree(); /* Setup temp directories */ tmp = getenv("TMPDIR"); xsnprintf(tmpdir, sizeof(tmpdir), "%s/git-difftool.XXXXXX", tmp ? tmp : "/tmp"); if (!mkdtemp(tmpdir)) return error("could not create '%s'", tmpdir); strbuf_addf(&ldir, "%s/left/", tmpdir); strbuf_addf(&rdir, "%s/right/", tmpdir); strbuf_addstr(&wtdir, workdir); if (!wtdir.len || !is_dir_sep(wtdir.buf[wtdir.len - 1])) strbuf_addch(&wtdir, '/'); mkdir(ldir.buf, 0700); mkdir(rdir.buf, 0700); memset(&wtindex, 0, sizeof(wtindex)); memset(&lstate, 0, sizeof(lstate)); lstate.base_dir = lbase_dir = xstrdup(ldir.buf); lstate.base_dir_len = ldir.len; lstate.force = 1; memset(&rstate, 0, sizeof(rstate)); rstate.base_dir = rbase_dir = xstrdup(rdir.buf); rstate.base_dir_len = rdir.len; rstate.force = 1; ldir_len = ldir.len; rdir_len = rdir.len; wtdir_len = wtdir.len; hashmap_init(&working_tree_dups, (hashmap_cmp_fn)working_tree_entry_cmp, NULL, 0); hashmap_init(&submodules, (hashmap_cmp_fn)pair_cmp, NULL, 0); hashmap_init(&symlinks2, (hashmap_cmp_fn)pair_cmp, NULL, 0); child.no_stdin = 1; child.git_cmd = 1; child.use_shell = 0; child.clean_on_exit = 1; child.dir = prefix; child.out = -1; argv_array_pushl(&child.args, "diff", "--raw", "--no-abbrev", "-z", NULL); for (i = 0; i < argc; i++) argv_array_push(&child.args, argv[i]); if (start_command(&child)) die("could not obtain raw diff"); fp = xfdopen(child.out, "r"); /* Build index info for left and right sides of the diff */ i = 0; while (!strbuf_getline_nul(&info, fp)) { int lmode, rmode; struct object_id loid, roid; char status; const char *src_path, *dst_path; if (starts_with(info.buf, "::")) die(N_("combined diff formats('-c' and '--cc') are " "not supported in\n" "directory diff mode('-d' and '--dir-diff').")); if (parse_index_info(info.buf, &lmode, &rmode, &loid, &roid, &status)) break; if (strbuf_getline_nul(&lpath, fp)) break; src_path = lpath.buf; i++; if (status != 'C' && status != 'R') { dst_path = src_path; } else { if (strbuf_getline_nul(&rpath, fp)) break; dst_path = rpath.buf; } if (S_ISGITLINK(lmode) || S_ISGITLINK(rmode)) { strbuf_reset(&buf); strbuf_addf(&buf, "Subproject commit %s", oid_to_hex(&loid)); add_left_or_right(&submodules, src_path, buf.buf, 0); strbuf_reset(&buf); strbuf_addf(&buf, "Subproject commit %s", oid_to_hex(&roid)); if (!oidcmp(&loid, &roid)) strbuf_addstr(&buf, "-dirty"); add_left_or_right(&submodules, dst_path, buf.buf, 1); continue; } if (S_ISLNK(lmode)) { char *content = get_symlink(&loid, src_path); add_left_or_right(&symlinks2, src_path, content, 0); free(content); } if (S_ISLNK(rmode)) { char *content = get_symlink(&roid, dst_path); add_left_or_right(&symlinks2, dst_path, content, 1); free(content); } if (lmode && status != 'C') { if (checkout_path(lmode, &loid, src_path, &lstate)) { ret = error("could not write '%s'", src_path); goto finish; } } if (rmode && !S_ISLNK(rmode)) { struct working_tree_entry *entry; /* Avoid duplicate working_tree entries */ FLEX_ALLOC_STR(entry, path, dst_path); hashmap_entry_init(entry, strhash(dst_path)); if (hashmap_get(&working_tree_dups, entry, NULL)) { free(entry); continue; } hashmap_add(&working_tree_dups, entry); if (!use_wt_file(workdir, dst_path, &roid)) { if (checkout_path(rmode, &roid, dst_path, &rstate)) { ret = error("could not write '%s'", dst_path); goto finish; } } else if (!is_null_oid(&roid)) { /* * Changes in the working tree need special * treatment since they are not part of the * index. */ struct cache_entry *ce2 = make_cache_entry(rmode, roid.hash, dst_path, 0, 0); add_index_entry(&wtindex, ce2, ADD_CACHE_JUST_APPEND); add_path(&rdir, rdir_len, dst_path); if (ensure_leading_directories(rdir.buf)) { ret = error("could not create " "directory for '%s'", dst_path); goto finish; } add_path(&wtdir, wtdir_len, dst_path); if (symlinks) { if (symlink(wtdir.buf, rdir.buf)) { ret = error_errno("could not symlink '%s' to '%s'", wtdir.buf, rdir.buf); goto finish; } } else { struct stat st; if (stat(wtdir.buf, &st)) st.st_mode = 0644; if (copy_file(rdir.buf, wtdir.buf, st.st_mode)) { ret = error("could not copy '%s' to '%s'", wtdir.buf, rdir.buf); goto finish; } } } } } fclose(fp); fp = NULL; if (finish_command(&child)) { ret = error("error occurred running diff --raw"); goto finish; } if (!i) goto finish; /* * Changes to submodules require special treatment.This loop writes a * temporary file to both the left and right directories to show the * change in the recorded SHA1 for the submodule. */ hashmap_iter_init(&submodules, &iter); while ((entry = hashmap_iter_next(&iter))) { if (*entry->left) { add_path(&ldir, ldir_len, entry->path); ensure_leading_directories(ldir.buf); write_file(ldir.buf, "%s", entry->left); } if (*entry->right) { add_path(&rdir, rdir_len, entry->path); ensure_leading_directories(rdir.buf); write_file(rdir.buf, "%s", entry->right); } } /* * Symbolic links require special treatment.The standard "git diff" * shows only the link itself, not the contents of the link target. * This loop replicates that behavior. */ hashmap_iter_init(&symlinks2, &iter); while ((entry = hashmap_iter_next(&iter))) { if (*entry->left) { add_path(&ldir, ldir_len, entry->path); ensure_leading_directories(ldir.buf); write_file(ldir.buf, "%s", entry->left); } if (*entry->right) { add_path(&rdir, rdir_len, entry->path); ensure_leading_directories(rdir.buf); write_file(rdir.buf, "%s", entry->right); } } strbuf_release(&buf); strbuf_setlen(&ldir, ldir_len); helper_argv[1] = ldir.buf; strbuf_setlen(&rdir, rdir_len); helper_argv[2] = rdir.buf; if (extcmd) { helper_argv[0] = extcmd; flags = 0; } else setenv("GIT_DIFFTOOL_DIRDIFF", "true", 1); rc = run_command_v_opt(helper_argv, flags); /* * If the diff includes working copy files and those * files were modified during the diff, then the changes * should be copied back to the working tree. * Do not copy back files when symlinks are used and the * external tool did not replace the original link with a file. * * These hashes are loaded lazily since they aren't needed * in the common case of --symlinks and the difftool updating * files through the symlink. */ hashmap_init(&wt_modified, (hashmap_cmp_fn)path_entry_cmp, NULL, wtindex.cache_nr); hashmap_init(&tmp_modified, (hashmap_cmp_fn)path_entry_cmp, NULL, wtindex.cache_nr); for (i = 0; i < wtindex.cache_nr; i++) { struct hashmap_entry dummy; const char *name = wtindex.cache[i]->name; struct stat st; add_path(&rdir, rdir_len, name); if (lstat(rdir.buf, &st)) continue; if ((symlinks && S_ISLNK(st.st_mode)) || !S_ISREG(st.st_mode)) continue; if (!indices_loaded) { static struct lock_file lock; strbuf_reset(&buf); strbuf_addf(&buf, "%s/wtindex", tmpdir); if (hold_lock_file_for_update(&lock, buf.buf, 0) < 0 || write_locked_index(&wtindex, &lock, COMMIT_LOCK)) { ret = error("could not write %s", buf.buf); rollback_lock_file(&lock); goto finish; } changed_files(&wt_modified, buf.buf, workdir); strbuf_setlen(&rdir, rdir_len); changed_files(&tmp_modified, buf.buf, rdir.buf); add_path(&rdir, rdir_len, name); indices_loaded = 1; } hashmap_entry_init(&dummy, strhash(name)); if (hashmap_get(&tmp_modified, &dummy, name)) { add_path(&wtdir, wtdir_len, name); if (hashmap_get(&wt_modified, &dummy, name)) { warning(_("both files modified: '%s' and '%s'."), wtdir.buf, rdir.buf); warning(_("working tree file has been left.")); warning("%s", ""); err = 1; } else if (unlink(wtdir.buf) || copy_file(wtdir.buf, rdir.buf, st.st_mode)) warning_errno(_("could not copy '%s' to '%s'"), rdir.buf, wtdir.buf); } } if (err) { warning(_("temporary files exist in '%s'."), tmpdir); warning(_("you may want to cleanup or recover these.")); exit(1); } else exit_cleanup(tmpdir, rc); finish: if (fp) fclose(fp); free(lbase_dir); free(rbase_dir); strbuf_release(&ldir); strbuf_release(&rdir); strbuf_release(&wtdir); strbuf_release(&buf); return ret; }
/** * main routine for receiver process. * * Receiver process runs on the same host as the generator process. */ int recv_files(int f_in, char *local_name) { int fd1,fd2; STRUCT_STAT st; int iflags, xlen; char *fname, fbuf[MAXPATHLEN]; char xname[MAXPATHLEN]; char fnametmp[MAXPATHLEN]; char *fnamecmp, *partialptr; char fnamecmpbuf[MAXPATHLEN]; uchar fnamecmp_type; struct file_struct *file; struct stats initial_stats; int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i; enum logcode log_code = log_before_transfer ? FLOG : FINFO; int max_phase = protocol_version >= 29 ? 2 : 1; int dflt_perms = (ACCESSPERMS & ~orig_umask); #ifdef SUPPORT_ACLS const char *parent_dirname = ""; #endif int ndx, recv_ok; if (verbose > 2) rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used); if (delay_updates) delayed_bits = bitbag_create(cur_flist->used + 1); while (1) { cleanup_disable(); /* This call also sets cur_flist. */ ndx = read_ndx_and_attrs(f_in, &iflags, &fnamecmp_type, xname, &xlen); if (ndx == NDX_DONE) { if (inc_recurse && first_flist) { if (read_batch) gen_wants_ndx(first_flist->used + first_flist->ndx_start); flist_free(first_flist); if (first_flist) continue; } else if (read_batch && first_flist) gen_wants_ndx(first_flist->used); if (++phase > max_phase) break; if (verbose > 2) rprintf(FINFO, "recv_files phase=%d\n", phase); if (phase == 2 && delay_updates) handle_delayed_updates(local_name); send_msg(MSG_DONE, "", 0, 0); continue; } if (ndx - cur_flist->ndx_start >= 0) file = cur_flist->files[ndx - cur_flist->ndx_start]; else file = dir_flist->files[cur_flist->parent_ndx]; fname = local_name ? local_name : f_name(file, fbuf); if (verbose > 2) rprintf(FINFO, "recv_files(%s)\n", fname); #ifdef SUPPORT_XATTRS if (iflags & ITEM_REPORT_XATTR && !dry_run) recv_xattr_request(file, f_in); #endif if (!(iflags & ITEM_TRANSFER)) { maybe_log_item(file, iflags, itemizing, xname); #ifdef SUPPORT_XATTRS if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && !dry_run) set_file_attrs(fname, file, NULL, fname, 0); #endif continue; } if (phase == 2) { rprintf(FERROR, "got transfer request in phase 2 [%s]\n", who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (file->flags & FLAG_FILE_SENT) { if (csum_length == SHORT_SUM_LENGTH) { if (keep_partial && !partial_dir) make_backups = -make_backups; /* prevents double backup */ if (append_mode) sparse_files = -sparse_files; append_mode = -append_mode; csum_length = SUM_LENGTH; redoing = 1; } } else { if (csum_length != SHORT_SUM_LENGTH) { if (keep_partial && !partial_dir) make_backups = -make_backups; if (append_mode) sparse_files = -sparse_files; append_mode = -append_mode; csum_length = SHORT_SUM_LENGTH; redoing = 0; } } if (!am_server && do_progress) set_current_file_index(file, ndx); stats.num_transferred_files++; stats.total_transferred_size += F_LENGTH(file); cleanup_got_literal = 0; if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) { rprintf(FERROR, "attempt to hack rsync failed.\n"); exit_cleanup(RERR_PROTOCOL); } if (!do_xfers) { /* log the transfer */ log_item(FCLIENT, file, &stats, iflags, NULL); if (read_batch) discard_receive_data(f_in, F_LENGTH(file)); continue; } if (write_batch < 0) { log_item(FCLIENT, file, &stats, iflags, NULL); if (!am_server) discard_receive_data(f_in, F_LENGTH(file)); continue; } if (read_batch) { if (!(redoing ? we_want_redo(ndx) : gen_wants_ndx(ndx))) { rprintf(FINFO, "(Skipping batched update for%s \"%s\")\n", redoing ? " resend of" : "", fname); discard_receive_data(f_in, F_LENGTH(file)); file->flags |= FLAG_FILE_SENT; continue; } } partialptr = partial_dir ? partial_dir_fname(fname) : fname; if (protocol_version >= 29) { switch (fnamecmp_type) { case FNAMECMP_FNAME: fnamecmp = fname; break; case FNAMECMP_PARTIAL_DIR: fnamecmp = partialptr; break; case FNAMECMP_BACKUP: fnamecmp = get_backup_name(fname); break; case FNAMECMP_FUZZY: if (file->dirname) { pathjoin(fnamecmpbuf, MAXPATHLEN, file->dirname, xname); fnamecmp = fnamecmpbuf; } else fnamecmp = xname; break; default: if (fnamecmp_type >= basis_dir_cnt) { rprintf(FERROR, "invalid basis_dir index: %d.\n", fnamecmp_type); exit_cleanup(RERR_PROTOCOL); } pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname); fnamecmp = fnamecmpbuf; break; } if (!fnamecmp || (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) { fnamecmp = fname; fnamecmp_type = FNAMECMP_FNAME; } } else { /* Reminder: --inplace && --partial-dir are never * enabled at the same time. */ if (inplace && make_backups > 0) { if (!(fnamecmp = get_backup_name(fname))) fnamecmp = fname; else fnamecmp_type = FNAMECMP_BACKUP; } else if (partial_dir && partialptr) fnamecmp = partialptr; else fnamecmp = fname; } initial_stats = stats; /* open the file */ fd1 = do_open(fnamecmp, O_RDONLY, 0); if (fd1 == -1 && protocol_version < 29) { if (fnamecmp != fname) { fnamecmp = fname; fd1 = do_open(fnamecmp, O_RDONLY, 0); } if (fd1 == -1 && basis_dir[0]) { /* pre-29 allowed only one alternate basis */ pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[0], fname); fnamecmp = fnamecmpbuf; fd1 = do_open(fnamecmp, O_RDONLY, 0); } } updating_basis_or_equiv = inplace && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP); if (fd1 == -1) { st.st_mode = 0; st.st_size = 0; } else if (do_fstat(fd1,&st) != 0) { rsyserr(FERROR_XFER, errno, "fstat %s failed", full_fname(fnamecmp)); discard_receive_data(f_in, F_LENGTH(file)); close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) { /* this special handling for directories * wouldn't be necessary if robust_rename() * and the underlying robust_unlink could cope * with directories */ rprintf(FERROR_XFER, "recv_files: %s is a directory\n", full_fname(fnamecmp)); discard_receive_data(f_in, F_LENGTH(file)); close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } if (fd1 != -1 && !S_ISREG(st.st_mode)) { close(fd1); fd1 = -1; } /* If we're not preserving permissions, change the file-list's * mode based on the local permissions and some heuristics. */ if (!preserve_perms) { int exists = fd1 != -1; #ifdef SUPPORT_ACLS const char *dn = file->dirname ? file->dirname : "."; if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) { dflt_perms = default_perms_for_dir(dn); parent_dirname = dn; } #endif file->mode = dest_mode(file->mode, st.st_mode, dflt_perms, exists); } /* We now check to see if we are writing the file "inplace" */ if (inplace) { fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600); if (fd2 == -1) { rsyserr(FERROR_XFER, errno, "open %s failed", full_fname(fname)); } } else { fd2 = open_tmpfile(fnametmp, fname, file); if (fd2 != -1) cleanup_set(fnametmp, partialptr, file, fd1, fd2); } if (fd2 == -1) { discard_receive_data(f_in, F_LENGTH(file)); if (fd1 != -1) close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } /* log the transfer */ if (log_before_transfer) log_item(FCLIENT, file, &initial_stats, iflags, NULL); else if (!am_server && verbose && do_progress) rprintf(FINFO, "%s\n", fname); /* recv file data */ recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size, fname, fd2, F_LENGTH(file)); log_item(log_code, file, &initial_stats, iflags, NULL); if (fd1 != -1) close(fd1); if (close(fd2) < 0) { rsyserr(FERROR, errno, "close failed on %s", full_fname(fnametmp)); exit_cleanup(RERR_FILEIO); } if ((recv_ok && (!delay_updates || !partialptr)) || inplace) { if (partialptr == fname) partialptr = NULL; if (!finish_transfer(fname, fnametmp, fnamecmp, partialptr, file, recv_ok, 1)) recv_ok = -1; else if (fnamecmp == partialptr) { do_unlink(partialptr); handle_partial_dir(partialptr, PDIR_DELETE); } } else if (keep_partial && partialptr) { if (!handle_partial_dir(partialptr, PDIR_CREATE)) { rprintf(FERROR, "Unable to create partial-dir for %s -- discarding %s.\n", local_name ? local_name : f_name(file, NULL), recv_ok ? "completed file" : "partial file"); do_unlink(fnametmp); recv_ok = -1; } else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL, file, recv_ok, !partial_dir)) recv_ok = -1; else if (delay_updates && recv_ok) { bitbag_set_bit(delayed_bits, ndx); recv_ok = 2; } else partialptr = NULL; } else do_unlink(fnametmp); cleanup_disable(); if (read_batch) file->flags |= FLAG_FILE_SENT; switch (recv_ok) { case 2: break; case 1: if (remove_source_files || inc_recurse || (preserve_hard_links && F_IS_HLINKED(file))) send_msg_int(MSG_SUCCESS, ndx); break; case 0: { enum logcode msgtype = redoing ? FERROR_XFER : FWARNING; if (msgtype == FERROR_XFER || verbose) { char *errstr, *redostr, *keptstr; if (!(keep_partial && partialptr) && !inplace) keptstr = "discarded"; else if (partial_dir) keptstr = "put into partial-dir"; else keptstr = "retained"; if (msgtype == FERROR_XFER) { errstr = "ERROR"; redostr = ""; } else { errstr = "WARNING"; redostr = read_batch ? " (may try again)" : " (will try again)"; } rprintf(msgtype, "%s: %s failed verification -- update %s%s.\n", errstr, local_name ? f_name(file, NULL) : fname, keptstr, redostr); } if (!redoing) { if (read_batch) flist_ndx_push(&batch_redo_list, ndx); send_msg_int(MSG_REDO, ndx); file->flags |= FLAG_FILE_SENT; } else if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); break; } case -1: if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); break; } } if (make_backups < 0) make_backups = -make_backups; if (phase == 2 && delay_updates) /* for protocol_version < 29 */ handle_delayed_updates(local_name); if (verbose > 2) rprintf(FINFO,"recv_files finished\n"); return 0; }
static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r, const char *fname, int fd, OFF_T total_size) { static char file_sum1[MAX_DIGEST_LEN]; static char file_sum2[MAX_DIGEST_LEN]; struct map_struct *mapbuf; struct sum_struct sum; int32 len, sum_len; OFF_T offset = 0; OFF_T offset2; char *data; int32 i; char *map = NULL; read_sum_head(f_in, &sum); if (fd_r >= 0 && size_r > 0) { int32 read_size = MAX(sum.blength * 2, 16*1024); mapbuf = map_file(fd_r, size_r, read_size, sum.blength); if (verbose > 2) { rprintf(FINFO, "recv mapped %s of size %.0f\n", fname_r, (double)size_r); } } else mapbuf = NULL; sum_init(checksum_seed); if (append_mode > 0) { OFF_T j; sum.flength = (OFF_T)sum.count * sum.blength; if (sum.remainder) sum.flength -= sum.blength - sum.remainder; if (append_mode == 2) { for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) { if (do_progress) show_progress(offset, total_size); sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE), CHUNK_SIZE); offset = j; } if (offset < sum.flength) { int32 len = (int32)(sum.flength - offset); if (do_progress) show_progress(offset, total_size); sum_update(map_ptr(mapbuf, offset, len), len); } } offset = sum.flength; if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) { rsyserr(FERROR_XFER, errno, "lseek of %s returned %.0f, not %.0f", full_fname(fname), (double)j, (double)offset); exit_cleanup(RERR_FILEIO); } } while ((i = recv_token(f_in, &data)) != 0) { if (do_progress) show_progress(offset, total_size); if (i > 0) { if (verbose > 3) { rprintf(FINFO,"data recv %d at %.0f\n", i,(double)offset); } stats.literal_data += i; cleanup_got_literal = 1; sum_update(data, i); if (fd != -1 && write_file(fd,data,i) != i) goto report_write_error; offset += i; continue; } i = -(i+1); offset2 = i * (OFF_T)sum.blength; len = sum.blength; if (i == (int)sum.count-1 && sum.remainder != 0) len = sum.remainder; stats.matched_data += len; if (verbose > 3) { rprintf(FINFO, "chunk[%d] of size %ld at %.0f offset=%.0f\n", i, (long)len, (double)offset2, (double)offset); } if (mapbuf) { map = map_ptr(mapbuf,offset2,len); see_token(map, len); sum_update(map, len); } if (updating_basis_or_equiv) { if (offset == offset2 && fd != -1) { OFF_T pos; if (flush_write_file(fd) < 0) goto report_write_error; offset += len; if ((pos = do_lseek(fd, len, SEEK_CUR)) != offset) { rsyserr(FERROR_XFER, errno, "lseek of %s returned %.0f, not %.0f", full_fname(fname), (double)pos, (double)offset); exit_cleanup(RERR_FILEIO); } continue; } } if (fd != -1 && map && write_file(fd, map, len) != (int)len) goto report_write_error; offset += len; } if (flush_write_file(fd) < 0) goto report_write_error; #ifdef HAVE_FTRUNCATE if (inplace && fd != -1 && ftruncate(fd, offset) < 0) { rsyserr(FERROR_XFER, errno, "ftruncate failed on %s", full_fname(fname)); } #endif if (do_progress) end_progress(total_size); if (fd != -1 && offset > 0 && sparse_end(fd) != 0) { report_write_error: rsyserr(FERROR_XFER, errno, "write failed on %s", full_fname(fname)); exit_cleanup(RERR_FILEIO); } sum_len = sum_end(file_sum1); if (mapbuf) unmap_file(mapbuf); read_buf(f_in, file_sum2, sum_len); if (verbose > 2) rprintf(FINFO,"got file_sum\n"); if (fd != -1 && memcmp(file_sum1, file_sum2, sum_len) != 0) return 0; return 1; }
int main() { die_if(SDL_Init(SDL_INIT_VIDEO), "unable to init SDL"); die_if(!(g_window = SDL_CreateWindow(WIN_TITLE, WIN_X, WIN_Y, WIN_WIDTH, WIN_HEIGHT, 0)), "unable to create window"); die_if(!(g_screen = SDL_GetWindowSurface(g_window)), "unable to create window surface"); die_if(!(g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED)), "unable to create renderer"); die_if(SDL_SetRenderDrawColor( g_renderer, 0x0, 0x0, 0x0, 0xFF ), "unable to set draw color"); g_perf_freq = SDL_GetPerformanceFrequency(); // init textures { SDL_Surface *srfc = NULL; for(unsigned int i = 0; i < NUM_TEX; ++i) { die_if(!(srfc = SDL_LoadBMP((char*)g_tex[i])), "unable to load bitmap"); die_if(!(g_tex[i] = SDL_CreateTextureFromSurface(g_renderer, srfc)) , "unable to create bmp texture"); g_tex_w[i] = srfc->w; g_tex_h[i] = srfc->h; SDL_FreeSurface(srfc); } } alloc_obj(SHIP_TID); int nufos = NUM_UFOS; for(int i = 0; i < nufos; ++i) { alloc_obj(UFO_TID); } Uint64 t0 = SDL_GetPerformanceCounter(); /* used to optimize (minimize) calls to rand() */ #define HASBITS(x,y) (((x) & (y)) == (y)) /* int foo = 0; */ /* for(int i = 0; i < 100000; ++i) */ /* { */ /* int r = rand(); */ /* if (HASBITS(r,0x7) || HASBITS(r,0x70)) ++foo; */ /* } */ // printf("%d\n", foo); // exit(-1); while (1) { // SDL_Delay(10); SDL_Event e; Uint64 t1 = SDL_GetPerformanceCounter(); float dt; dt = (float)(t1 - t0)/g_perf_freq; t0 = t1; /* user events */ if (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { exit_cleanup(0); } if (e.type == SDL_KEYDOWN) { SDL_Keycode sym = e.key.keysym.sym; if(sym == SDLK_SPACE) { alloc_timer_1s(alloc_obj(PHOTON_TID), t1); } g_obj_ax[0] = sym == SDLK_LEFT ? -(X_ACC) : (sym == SDLK_RIGHT ? X_ACC : 0.0f); g_obj_ay[0] = sym == SDLK_UP ? -(Y_ACC) : (sym == SDLK_DOWN ? Y_ACC : 0.0f); } } /* ai events */ for(int i = 1; i < nufos + 1; ++i) { int r = rand(); #define RAND_FREQ 0xf g_obj_ax[i] = HASBITS(r,RAND_FREQ) ? X_ACC : 0.0f; g_obj_ax[i] += HASBITS(r,RAND_FREQ << 8) ? -(X_ACC) : 0.0f; g_obj_ax[i] /= 100.0f; g_obj_ay[i] = HASBITS(r,RAND_FREQ << 16) ? Y_ACC : 0.0f; g_obj_ay[i] += HASBITS(r,RAND_FREQ << 24) ? -(Y_ACC) : 0.0f; g_obj_ay[i] /= 100.0f; } /* timer events */ for(int i = 0; i < g_ntimers; ++i) { if(t1 >= g_timer_expire[i]) { dealloc_timer_1s(i); } } /* physics update */ for(int i = g_nobjs - 1; i >= 0 ; --i) { update(&g_obj_x[i], &g_obj_vx[i], &g_obj_ax[i], dt, -OBJ_W(i), WIN_WIDTH); update(&g_obj_y[i], &g_obj_vy[i], &g_obj_ay[i], dt, -OBJ_H(i), WIN_HEIGHT); } /* collisions */ for(int i = g_nobjs - 1; i >= 0 ; --i) { for(int j = i - 1; j >= 0 ; --j) { if (colliding(i,j)) { } } } /* rendering */ SDL_RenderClear(g_renderer); /* ignore return */ SDL_Texture *tex = g_tex[UFO_TID]; for(int i = 1; i < nufos + 1; ++i) { render(i, tex); } render(0, g_tex[SHIP_TID]); tex = g_tex[PHOTON_TID]; for(int i = 1 + nufos; i < 1 + nufos + g_ntimers; ++i) { render(i, tex); } SDL_RenderPresent(g_renderer); } return 0; }
NORETURN void out_of_memory(const char *str) { rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i()); exit_cleanup(RERR_MALLOC); }
NORETURN void overflow_exit(const char *str) { rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i()); exit_cleanup(RERR_MALLOC); }
void *process_clients(void *arg) { int ret; struct worker_data *mydata = (struct worker_data *)arg; struct context_pool *pool; struct epoll_event evt; struct epoll_event evts[EVENTS_PER_BATCH]; int cpu_id; int ep_fd; int i; struct conn_context *ctx; if (enable_keepalive) http_response = http_200_keepalive; else http_response = http_200; http_response_len = strlen(http_response); ret = bind_process_cpu(mydata->cpu_id); if (ret < 0) { perror("Unable to Bind worker on CPU"); exit_cleanup(); } pool = init_pool(MAX_CONNS_PER_WORKER); if ((ep_fd = epoll_create(MAX_CONNS_PER_WORKER)) < 0) { perror("Unable to create epoll FD"); exit_cleanup(); } for (i = 0; i < la_num; i++) { ctx = alloc_context(pool); ctx->fd = la[i].listen_fd; ctx->handler = process_accept; cpu_id = mydata->cpu_id; ctx->cpu_id = cpu_id; ctx->ep_fd = ep_fd; evt.events = EPOLLIN | EPOLLHUP | EPOLLERR; evt.data.ptr = ctx; if (epoll_ctl(ctx->ep_fd, EPOLL_CTL_ADD, ctx->fd, &evt) < 0) { perror("Unable to add Listen Socket to epoll"); exit_cleanup(); } } wdata[cpu_id].polls_min = EVENTS_PER_BATCH; while (1) { int num_events; int i; int events; num_events = epoll_wait(ep_fd, evts, EVENTS_PER_BATCH, -1); if (num_events < 0) { if (errno == EINTR) continue; perror("epoll_wait() error"); } if (!num_events) wdata[cpu_id].polls_mpt++; else if (num_events < wdata[cpu_id].polls_min) wdata[cpu_id].polls_min = num_events; if (num_events > wdata[cpu_id].polls_max) wdata[cpu_id].polls_max = num_events; wdata[cpu_id].polls_sum += num_events; wdata[cpu_id].polls_cnt++; wdata[cpu_id].polls_avg = wdata[cpu_id].polls_sum / wdata[cpu_id].polls_cnt; wdata[cpu_id].polls_lst = num_events; for (i = 0 ; i < num_events; i++) { int active_fd; events = evts[i].events; ctx = evts[i].data.ptr; ctx->events = events; if (ctx->flags & PROXY_BACKEND_EVENT) active_fd = ctx->end_fd; else active_fd = ctx->fd; print_d("%dth event[0x%x] at fd %d\n", i, events, active_fd); ctx->handler(ctx); } } return NULL; }