int GetTimeStamp(int type) { MYSQL *conn = NULL; MYSQL_RES *res_set = NULL; MYSQL_ROW row = NULL; char query[512]; char datetime[64]; int updated_flag=0, DBres = -1, result = SUCCESS; int count; printLog(Log, STAMP, "GetTimeStamp() : %d\n", type); memset(query, 0, sizeof(query)); if(type == TYPE_SPEED) { sprintf(query, "select UpdateTime from SvcUpdateTime " "where SvcName in ('MinjaLinkSpeed', 'StdLinkSpeed', 'DongbuSpeed1', 'DongbuSpeed2') " "order by UpdateTime desc limit 1"); } else if(type == TYPE_FWNEWS) { sprintf(query, "select UpdateTime from SvcUpdateTime where SvcName='BreakingNews'"); } else if (type == TYPE_ACCIDENT) { sprintf(query, "select UpdateTime from SvcUpdateTime where SvcName='DongbuAccident'"); } if( (DBres = mydbc_init(&conn)) != DB_SUCCESS ) { printLog(Log, STAMP, "ERR: mydbc_init[%d]\n", DBres); exit_handler(); //return ERROR_DB; } if( (DBres = mydbc_execute_get_result(&conn, query, &updated_flag, &res_set)) != DB_SUCCESS ) { printLog(Log, STAMP, "ERR: mydbc_execute_get_result[%d]\n", DBres); return ERROR_DB; } if( (DBres = mydbc_end(&conn)) != DB_SUCCESS ) { printLog(Log, STAMP, "ERR: mydbc_end[%d]\n", DBres); return ERROR_DB; } row = NULL; row = mydbc_next_row(&res_set); memset(datetime, 0, sizeof(datetime)); if(row[0] != NULL) strcpy(datetime, row[0]); mydbc_free_result(&res_set); printLog(Log, STAMP, "TimeStamp = %s\n", datetime); time_t ts; struct tm tm; if( strptime(datetime, "%Y-%m-%d %H:%M:%S", &tm) != NULL ) ts = mktime(&tm); else ts = 0; return ts; }
void signal_handler(int signo) { if (signo == SIGINT || signo == SIGTERM) { printLog(HEAD, "Termination Signal Catched..\n") ; exit_handler(1) ; } else if(signo == SIGPIPE) { signal(SIGPIPE, SIG_IGN) ; return ; } }
static int write_handler (int fd, const void *buffer, unsigned size) { if (!is_user_vaddr(buffer + size) || pagedir_get_page(thread_current()->pagedir, buffer) == NULL) { exit_handler(-1); } int num_bytes_written = 0; if (fd == STDIN_FILENO) { exit_handler(-1); } else if (fd == STDOUT_FILENO) { putbuf(buffer, size); num_bytes_written = size; } else { struct file_struct *write_file = get_file(fd); if (write_file != NULL && write_file->sys_file != NULL) { num_bytes_written = file_write(write_file->sys_file, buffer, size); } else { return -1; } } return num_bytes_written; }
int main(int argc, char **argv) { pid_t pid ; int stat ; pthread_t threads ; int ret ; if (argc > 1) { if (argc == 4) { if (strcmp(argv[1], "-f") == 0) { strcpy(config_file_path, argv[2]); } else { printf("---------------------------------\n"); printf("-%s [-f ConfigFilePath DumpFileName]\n", argv[0]); printf("---------------------------------\n"); exit(-1); } } else { printf("---------------------------------\n"); printf("-%s [-f ConfigFilePath DumpFileName]\n", argv[0]); printf("---------------------------------\n"); exit(-1); } } else { printf("---------------------------------\n"); printf("-%s [-f ConfigFilePath DumpFileName]\n", argv[0]); printf("---------------------------------\n"); exit(-1); } memset(&Config, 0, sizeof(CONFIG_T)) ; readConfig(config_file_path, &Config) ; Log = openLog(argv[0], Config.LOG_FILE, LOG_MODE); printLog(HEAD, "========================================\n") ; printLog(HEAD, " SERVER START...\n") ; printLog(HEAD, "========================================\n") ; printLog(HEAD, "\n") ; ret = mydbc_connect(Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, Config.DB_HOST, Config.DB_PORT, Config.DB_CONN_COUNT); if(ret != DB_SUCCESS) { printLog(HEAD, "ERROR[%d]\n", ret); exit(0); } RedoUUID(argv[3]); exit_handler(1) ; }
/* Signal handler for SIGURG. */ static void sigurg_handler(int signo __unused) { int ttydisc = TTYDISC; signal(SIGURG, SIG_IGN); if(exiting) return; syslog(LOG_NOTICE,"SIGURG on %s (sl%d); hangup",dev,unit); if (ioctl(fd, TIOCSETD, &ttydisc) < 0) { syslog(LOG_ERR, "ioctl(TIOCSETD): %m"); exit_handler(1); } cfsetospeed(&tty, B0); if (tcsetattr(fd, TCSANOW, &tty) < 0) { syslog(LOG_ERR, "tcsetattr(TCSANOW): %m"); exit_handler(1); } /* Need to go to sighup handler in any case */ if (modem_control & CLOCAL) kill (getpid(), SIGHUP); }
/* * Return > 0 to return to guest, < 0 on error, 0 (and set exit_reason) on * proper exit to userspace. */ int handle_exit(struct kvm_vcpu *vcpu, struct kvm_run *run, int exception_index) { exit_handle_fn exit_handler; if (ARM_ABORT_PENDING(exception_index)) { u8 hsr_ec = kvm_vcpu_trap_get_class(vcpu); /* * HVC/SMC already have an adjusted PC, which we need * to correct in order to return to after having * injected the abort. */ if (hsr_ec == HSR_EC_HVC || hsr_ec == HSR_EC_SMC) { u32 adj = kvm_vcpu_trap_il_is32bit(vcpu) ? 4 : 2; *vcpu_pc(vcpu) -= adj; } kvm_inject_vabt(vcpu); return 1; } exception_index = ARM_EXCEPTION_CODE(exception_index); switch (exception_index) { case ARM_EXCEPTION_IRQ: return 1; case ARM_EXCEPTION_HVC: /* * See ARM ARM B1.14.1: "Hyp traps on instructions * that fail their condition code check" */ if (!kvm_condition_valid(vcpu)) { kvm_skip_instr(vcpu, kvm_vcpu_trap_il_is32bit(vcpu)); return 1; } exit_handler = kvm_get_exit_handler(vcpu); return exit_handler(vcpu, run); case ARM_EXCEPTION_DATA_ABORT: kvm_inject_vabt(vcpu); return 1; default: kvm_pr_unimpl("Unsupported exception type: %d", exception_index); run->exit_reason = KVM_EXIT_INTERNAL_ERROR; return 0; } }
bool byte_access_ok(void* p, bool check_writable) { void *ptr = p; uintptr_t pg_addr_ = ((uintptr_t) ptr / PGSIZE * PGSIZE); if (p == NULL || !is_user_vaddr(ptr)) { exit_handler(-1); NOT_REACHED () ; } else if (ptr < thread_current()->saved_esp) { struct spte* spte = spt_lookup(thread_current(), (void*) pg_addr_); if (spte == NULL) { exit_handler(-1); NOT_REACHED () ; }else if(check_writable && spte->type!= Swap_Space && spte->writable == false){ exit_handler(-1); NOT_REACHED () ; } } return true; }
int is_ctrl_d(char *key) { t_line *l; if (key[0] == 4 && key[1] == 0 && key[2] == 0 && key[3] == 0) { if ((data()->cur == NONE) || (data()->cur == CURRENT && !data()->current) || (data()->cur == CURRENT && !data()->current->edit)) return (exit_handler()); else if (data()->cur != CURRENT && data()->cur != NONE) { l = data()->history; while (l->id != data()->cur) l = l->next; if (!l->edit) return (exit_handler()); } write(1, "\a", 1); return (1); } return (0); }
/* configure the interface, e.g. by passing the unit number to a script. */ static void configure_network(void) { int new_unit; /* find out what unit number we were assigned */ if (ioctl(fd, SLIOCGUNIT, (caddr_t)&new_unit) < 0) { syslog(LOG_ERR, "ioctl(SLIOCGUNIT): %m"); exit_handler(1); } /* iff the unit number changes either invoke config_cmd or punt. */ if (config_cmd) { char *s; s = (char*) malloc(strlen(config_cmd) + 32); if (s == NULL) { syslog(LOG_ERR, "malloc failed"); exit(1); } sprintf (s, "%s %d %d", config_cmd, unit, new_unit); syslog(LOG_NOTICE, "configuring %s (sl%d):", dev, unit); syslog(LOG_NOTICE, " '%s'", s); system(s); free (s); unit = new_unit; } else { /* don't compare unit numbers if this is the first time to attach. */ if (unit < 0) unit = new_unit; if (new_unit != unit) { syslog(LOG_ERR, "slip unit changed from sl%d to sl%d, but no -u CMD was specified!", unit, new_unit); exit_handler(1); } syslog(LOG_NOTICE,"sl%d connected to %s at %d baud",unit,dev,speed); } }
bool byte_access_ok(void* p){ void *ptr = p; /* * There is no ctx switching in this kind of interrupts, * thread_current is current process, not main! */ uint32_t *pd = thread_current ()-> pagedir; if(p==NULL || !is_user_vaddr(ptr) || pagedir_get_page(pd,ptr) == NULL){ /*kill illegal process/thread, shall never return*/ //printf("Address access invalid, kill..."); exit_handler(-1); NOT_REACHED (); } return true; }
void read_config() { FILE *fp = NULL; char buf[BUF_SIZE], name[BUF_SIZE], value[BUF_SIZE]; memset(&Config, 0x00, sizeof(Config)); if ((fp = fopen(CONFIG_FILE, "r")) == NULL) { printLog(Log, STAMP, "Can't Open CONFIG_FILE(%s)\n", CONFIG_FILE); exit_handler(); } memset(buf, 0, sizeof(buf)); while (fgets(buf, sizeof(buf), fp) != NULL) { if (buf[0] != '#') { // comment 제외 memset(name, 0, sizeof(name)); memset(value, 0, sizeof(value)); sscanf(buf, "%s%s", name, value); if (!strcmp(name, "LISTEN_PORT")) Config.LISTEN_PORT = atoi(value); else if (!strcmp(name, "PROGRAM_NAME")) sprintf(Config.PROGRAM_NAME, "%s", value); else if (!strcmp(name, "TBL_MINJA_LINK_SPEED")) sprintf(Config.TBL_MINJA_LINK_SPEED, "%s", value); else if (!strcmp(name, "TBL_DETOUR_KD_LINK_SPEED")) sprintf(Config.TBL_DETOUR_KD_LINK_SPEED, "%s", value); else if (!strcmp(name, "TBL_STD_LINK_SPEED")) sprintf(Config.TBL_STD_LINK_SPEED, "%s", value); else if (!strcmp(name, "TBL_BREAKING_NEWS")) sprintf(Config.TBL_BREAKING_NEWS, "%s", value); else if (!strcmp(name, "TBL_SVC_UPDATE_TIME")) sprintf(Config.TBL_SVC_UPDATE_TIME, "%s", value); else if (!strcmp(name, "DB_NAME")) sprintf(Config.DB_NAME, "%s", value); else if (!strcmp(name, "DB_USER")) sprintf(Config.DB_USER, "%s", value); else if (!strcmp(name, "DB_PASSWORD")) sprintf(Config.DB_PASSWORD, "%s", value); else if (!strcmp(name, "DB_HOST")) sprintf(Config.DB_HOST, "%s", value); else if (!strcmp(name, "DB_PORT")) sprintf(Config.DB_PORT, "%s", value); else if (!strcmp(name, "DB_CONN_COUNT")) Config.DB_CONN_COUNT = atoi(value); else if (!strcmp(name, "DB_PING_PERIOD")) Config.DB_PING_PERIOD = atoi(value); } memset(buf, 0, sizeof(buf)); } fclose(fp); printLog(Log, STAMP, "LISTEN_PORT(%d)PROGRAM_NAME(%s)\n", Config.LISTEN_PORT, Config.PROGRAM_NAME) ; printLog(Log, STAMP, "DB SERVER(%s:%s)\n", Config.DB_HOST, Config.DB_PORT); printLog(Log, STAMP, "DB INFO(%s:%s:%s:%d:%d)\n", Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, Config.DB_CONN_COUNT, Config.DB_PING_PERIOD); printLog(Log, STAMP, "DB TABLE(%s:%s:%s:%s:%s)\n", Config.TBL_MINJA_LINK_SPEED, Config.TBL_DETOUR_KD_LINK_SPEED, Config.TBL_STD_LINK_SPEED, Config.TBL_BREAKING_NEWS, Config.TBL_SVC_UPDATE_TIME); }
void FileToData(int version, G_INFO *g_info) { struct stat stbuf ; FILE *handle = NULL ; char fileName[100] = {'\0'} ; int len = 0 ; sprintf(fileName, "%s/%d.DAT", Config.DAT_PATH, version) ; //: FILE이 있는지 조사 루틴 if(stat(fileName, &stbuf) != 0) { printLog(HEAD, "ERR: FILE(%s) NOT FOUND\n", fileName) ; return ; } if(receive_time[0] < stbuf.st_mtime) { receive_time[0] = stbuf.st_mtime ; if(version == 101) g_text_upd_time[0] = stbuf.st_mtime; else if(version == 102) g_mishap_upd_time[0] = stbuf.st_mtime; else g_speed_upd_time[0] = stbuf.st_mtime; } if(receive_time[1] < stbuf.st_mtime) { receive_time[1] = stbuf.st_mtime ; if(version == 101) g_text_upd_time[1] = stbuf.st_mtime; else if(version == 102) g_mishap_upd_time[1] = stbuf.st_mtime; else g_speed_upd_time[0] = stbuf.st_mtime; } handle = fopen(fileName, "rb") ; fread((G_INFO *)g_info, sizeof(G_INFO), 1, handle) ; if(g_info->compFlag == 0) len = g_info->realSize ; else len = g_info->compSize ; if((g_info->data = (char *) malloc (len)) == NULL) { printLog(HEAD, "ERR: Memory Alloc FAIL\n") ; exit_handler() ; } memset(g_info->data, 0, len) ; fread((char *)g_info->data, len, 1, handle) ; fclose(handle) ; printLog(HEAD, "FileToData[%s] READ\n", fileName) ; }
///[속도 정보 얻기]///// int main(void) { HD_IN hd_in ; ON_TRAFFIC_IN on_traffic_in ; ON_TRAFFIC_OUT on_traffic_out ; int i, len, wlen, rlen ; struct sockaddr_in serv_addr; int ret, ret_size = 0 ; char svc_flag = 0 ; char road_flag = 0 ; char highway_flag = 0 ; char *info = NULL ; char *data = NULL ; int version ; time_t t ; char timeStamp[19+1] = {'\0'} ; int temp ; unsigned char speed ; memset(&hd_in, 0, sizeof(HD_IN)) ; memset(&on_traffic_in, 0, sizeof(ON_TRAFFIC_IN)) ; memset(&on_traffic_out, 0, sizeof(ON_TRAFFIC_OUT)) ; printf("====[HD_IN]====\n") ; hd_in.serviceId = htonl(3000) ; // hd_in.serviceId = htonl(1031) ; printf("====[ON_TRAFFIC_IN]====표준노드링크 속도\n") ; on_traffic_in.areaInfo = htonl(100) ; //on_traffic_in.areaInfo = htonl(1) ; //InputInt("on_traffic_in.version", &(on_traffic_in.version), 20080805) ; on_traffic_in.version = 20501101; on_traffic_in.version = htonl(on_traffic_in.version) ; //InputInt("on_traffic_in.mdn", &(on_traffic_in.mdn), 1199981076) ; on_traffic_in.mdn = 1199981076; on_traffic_in.mdn = htonl(on_traffic_in.mdn) ; memset((char *) &serv_addr, 0, sizeof(serv_addr)) ; serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = inet_addr(SM_SERVER_IP) ; serv_addr.sin_port = htons(SM_SERVER_PORT) ; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("clientsoc: can't open stream socket") ; close(sockfd), exit(0); } if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printf("clientsoc: can't connect to server") ; close(sockfd), exit(0); } if((wlen = writen(sockfd, &hd_in, sizeof(HD_IN))) != sizeof(HD_IN)) { printf("ERR: write HD_IN[wlen:%d/%d]\n", wlen, sizeof(HD_IN)) ; close(sockfd), exit(1) ; } printf("SEND: HD_IN[wlen:%d]\n", wlen) ; if((wlen = writen(sockfd, &on_traffic_in, sizeof(ON_TRAFFIC_IN))) != sizeof(ON_TRAFFIC_IN)) { printf("ERR: write INFO_IN[wlen:%d/%d]\n", wlen, sizeof(ON_TRAFFIC_IN)) ; close(sockfd), exit(1) ; } printf("SEND: ON_TRAFFIC_IN[wlen:%d]-areaInfo[%d]\n", wlen, ntohl(on_traffic_in.areaInfo)) ; if ((rlen = readn(sockfd, &on_traffic_out, sizeof(ON_TRAFFIC_OUT))) != sizeof(ON_TRAFFIC_OUT)) { printf("ERR: read SRH_OUT[rlen:%d/%d]...\n", rlen, sizeof(ON_TRAFFIC_OUT)) ; close(sockfd), exit(1) ; } printf("READ: SRH_OUT[rlen:%d]\n", rlen) ; on_traffic_out.result = ntohl(on_traffic_out.result) ; on_traffic_out.num = ntohl(on_traffic_out.num) ; on_traffic_out.compFlag = ntohl(on_traffic_out.compFlag) ; on_traffic_out.realSize = ntohl(on_traffic_out.realSize) ; on_traffic_out.compSize = ntohl(on_traffic_out.compSize) ; printf("ON_TRAFFIC_OUT-result[%d] num[%d] compFlag[%d] realSize[%d] compSize[%d]\n", on_traffic_out.result, on_traffic_out.num, on_traffic_out.compFlag, on_traffic_out.realSize, on_traffic_out.compSize) ; if((on_traffic_out.result == 0) && (on_traffic_out.num> 0)) { if(on_traffic_out.compFlag == 0) ret_size = on_traffic_out.realSize ; else ret_size = on_traffic_out.compSize ; if((info = (char *) malloc (on_traffic_out.realSize)) == NULL) { printf("ERR: Memory Alloc Fail\n") ; close(sockfd), exit(1) ; } memset(info, 0, on_traffic_out.realSize) ; if ((rlen = readn(sockfd, info, ret_size)) != ret_size) { printf("ERR: read info[rlen:%d/%d]...\n", rlen, ret_size) ; close(sockfd), exit(1) ; } printf("READ: DATA[rlen:%d]\n", rlen) ; if(on_traffic_out.compFlag == 1) { if((data = (char *) malloc (on_traffic_out.realSize)) == NULL) { printf("ERR: Memory Alloc Fail\n") ; close(sockfd), exit(1) ; } memset(data, 0, on_traffic_out.realSize) ; memcpy(data, info, on_traffic_out.realSize) ; memset(info, 0, on_traffic_out.realSize) ; ret = uncompress(info, &(on_traffic_out.realSize), data, on_traffic_out.compSize) ; printf("uncompress():ret[%d] uncompSize[%d] compSize[%d]\n", ret, on_traffic_out.realSize, on_traffic_out.compSize) ; } //INFO 출력 len = 0 ; memcpy(&temp, &(info[len]), 4) ; //VERSION version = ntohl(temp) ; len += 4 ; memcpy(&temp, &(info[len]), 4) ; //시간 t = ntohl(temp) ; time2TimeStr(t, timeStamp) ; len += 4 ; memcpy(&temp, &(info[len]), 4) ; //SIZE ret_size = ntohl(temp) ; len += 4 ; printf("INFO: version[%d] time[%.19s] size[%d]\n", version, timeStamp, ret_size) ; for(i = 0 ; i < on_traffic_out.num; i++) { memcpy(&speed, &(info[len]), 1) ; len += 1 ; //printf("[%d] speed[%d]\n", i, speed) ; } printf("### END ###\n\n") ; if(info != NULL) free(info) ; info=NULL ; if(data != NULL) free(data) ; data=NULL ; } exit_handler() ; }
int get_tcon_speed(int type) { time_t time_info ; time_t rev_time, cal_time ; int set_index = 0 ; int recvInfoNum = 0 ; char *onlyRecvInfo = NULL ; int onlyRecvInfoNum = 0, only_len = 0 ; time_t t ; int temp = 0 ; int index = 0 ; ///---------------------------------------------------------------------/// int sockfd ; int wlen, rlen ; struct sockaddr_in serv_addr ; int ret = E_NO_ERR ; SRH_IN in ; SRH_OUT out ; S_INFO *info = NULL ; int i = 0 ; fd_set readset ; struct timeval tmv ; memset(&in, 0, sizeof(SRH_IN)) ; memset(&out, 0, sizeof(SRH_OUT)) ; printLog(PUSH, "===GET_SPEED_INFO(%d) START===\n", type) ; time_info = time(&t) ; memset((char *) &serv_addr, 0, sizeof(serv_addr)) ; serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = inet_addr(Config.TRAFFIC_IP) ; serv_addr.sin_port = htons(Config.TRAFFIC_PORT) ; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printLog(PUSH, "clientsoc: can't open stream socket[%s:%d]\n", Config.TRAFFIC_IP, Config.TRAFFIC_PORT) ; ret = E_TCP_FAIL ; goto error_exit ; } if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printLog(PUSH, "clientsoc: can't connect to server[%s:%d]\n", Config.TRAFFIC_IP, Config.TRAFFIC_PORT) ; ret = E_TCP_FAIL ; goto error_exit ; } in.op_code = htonl(type) ; //: TCON // in.limit_time = htonl(30) ; // strcpy(in.req_info, "INAVION3") ; in.limit_time = htonl((int)Config.LIMIT_TIME) ; // in.limit_time = htonl(0) ; //FULL DATA strcpy(in.req_info, Config.ID) ; if((wlen = writen(sockfd, &in, sizeof(SRH_IN))) != sizeof(SRH_IN)) { printLog(PUSH, "ERR: write SRH_IN[wlen:%d/%d]\n", wlen, sizeof(SRH_IN)) ; ret = E_TCP_FAIL ; goto error_exit ; } printLog(PUSH, "SEND: SRH_IN[wlen:%d]\n", wlen) ; FD_ZERO(&readset) ; FD_SET(sockfd, &readset) ; tmv.tv_sec = 30 ; tmv.tv_usec = 0 ; if(select(sockfd+1, &readset, NULL, NULL, &tmv) < 0) { printLog(PUSH, "ERR: select Error : SOCKET(%d) CLOSE\n", sockfd) ; ret = E_TCP_FAIL ; goto error_exit ; } if (!FD_ISSET(sockfd, &readset)) { // 30초동안 msgid를 받지 못한 경우, printLog(PUSH, "ERR: SockFD(%d) TimeOut wait read_time(%d)\n", sockfd, tmv.tv_sec) ; ret = E_TCP_TIMEOUT ; goto error_exit ; } if((rlen = readn(sockfd, &out, sizeof(SRH_OUT))) != sizeof(SRH_OUT)) { printLog(PUSH, "ERR: read SRH_OUT[rlen:%d/%d]\n", rlen, sizeof(SRH_OUT)) ; ret = E_TCP_FAIL ; goto error_exit ; } printLog(PUSH, "READ: SRH_OUT[rlen:%d]\n", rlen) ; out.result = ntohl(out.result) ; out.op_code = ntohl(out.op_code) ; out.count = ntohl(out.count) ; printLog(PUSH, "TYPE(%d) - OP_CODE(%d) RESULT(%d) COUNT(%d)\n", type, out.op_code, out.result, out.count) ; if(out.op_code == type) { printLog(PUSH, "TCON 속도\n") ; G_rev_op6_ret = out.result ; } if(out.count > 0) { if((info = (S_INFO *) malloc (out.count * sizeof(S_INFO))) == NULL) { printLog(PUSH, "ERR: Memory Alloc Fail ==> Program Exit\n") ; exit_handler() ; } memset(info, 0, out.count * sizeof(S_INFO)) ; FD_ZERO(&readset) ; FD_SET(sockfd, &readset) ; tmv.tv_sec = 30 ; tmv.tv_usec = 0 ; if(select(sockfd+1, &readset, NULL, NULL, &tmv) < 0) { printLog(PUSH, "ERR: select Error : SOCKET(%d) CLOSE\n", sockfd) ; ret = E_TCP_FAIL ; goto error_exit ; } if (!FD_ISSET(sockfd, &readset)) { // 30초동안 msgid를 받지 못한 경우, printLog(PUSH, "ERR: SockFD(%d) TimeOut wait read_time(%d)\n", sockfd, tmv.tv_sec) ; ret = E_TCP_TIMEOUT ; goto error_exit ; } if((rlen = readn(sockfd, info, sizeof(S_INFO)*out.count)) != (int) sizeof(S_INFO)*out.count) { printLog(PUSH, "ERR: read S_INFO[rlen:%d/%d]\n", rlen, sizeof(S_INFO)*out.count) ; ret = E_TCP_FAIL ; goto error_exit ; } printLog(PUSH, "READ: S_INFO [%d] DATA SET [%d]SIZE\n", out.count, sizeof(S_INFO)*out.count) ; for(i = 0 ; i < out.count ; i++) { info[i].speed = ntohl(info[i].speed) ; if(info[i].speed < 0) info[i].speed = 0 ; //: 속도 정보가 0보다 작으면(음수) 0로 변경 // info[i].hour = ntohs(info[i].hour) ; // info[i].min = ntohs(info[i].min) ; info[i].recv_date = ntohl(info[i].recv_date) ; info[i].recv_time = ntohl(info[i].recv_time) ; rev_time = makeReadTime2(info[i].recv_date, info[i].recv_time) ; cal_time = time_info - rev_time ; if(cal_time > 1800) { // 30분 이전 데이터면 속도 0 info[i].speed = 0 ; printLog(PUSH, "NOT-INVALID: DATE[%08d] TIME[%06d] CAL_TIME[%d]\n", info[i].recv_date, info[i].recv_time, cal_time) ; } if(i%1000 == 0) //: HEAR_SON printLog(PUSH, "[%d]: sid[%s] speed[%d] recv_date[%d] recv_time[%d]\n", i, info[i].sid, info[i].speed, info[i].recv_date, info[i].recv_time) ; } } else { //: 읽어올 정보가 없을 시에는 goto error_exit ; } ///---------------------------------------------------------------------/// recvInfoNum = out.count ; // index 결정 if(type == TYPE_TCON_SPEED_INFO) index = (g_tcon_speed_flag+1) % 2 ; receive_time[index] = time_info ; for(set_index = 0 ; set_index < speed_set_num ; set_index++) { //[TCON SPEED]////////////// if(type == TYPE_TCON_SPEED_INFO) { if(speed_set[set_index].tcon_map_num == 0) continue ; onlyRecvInfoNum = speed_set[set_index].tcon_map_num ; if((onlyRecvInfo = (char *) malloc(INT_LEN+INT_LEN+INT_LEN+onlyRecvInfoNum)) == NULL) { printLog(PUSH, "ERR: Mamory Alloc Fail=>Program Exit\n") ; exit_handler() ; } memset(onlyRecvInfo, 0, INT_LEN+INT_LEN+INT_LEN+onlyRecvInfoNum) ; only_len = 0 ; //: VERSION temp = htonl(speed_set[set_index].version) ; memcpy(&(onlyRecvInfo[only_len]), &temp, INT_LEN) ; only_len += INT_LEN ; if(out.count > 0) temp = makeReadTime2(info[0].recv_date, info[0].recv_time) ; else temp = (time_t) time(&t) ; temp = htonl(temp) ; memcpy(&(onlyRecvInfo[only_len]), &temp, INT_LEN) ; only_len += INT_LEN ; //: SIZE temp = htonl(onlyRecvInfoNum) ; memcpy(&(onlyRecvInfo[only_len]), &temp, INT_LEN) ; only_len += INT_LEN ; ///INFO MAPPING() info_tcon_mapping(speed_set[set_index].tcon_map, speed_set[set_index].tcon_map_num, info, recvInfoNum, onlyRecvInfo) ; ///INFO MAPPING() //: index 공간 초기화 if(speed_set[set_index].tcon_speed_info[index].data != NULL) { free(speed_set[set_index].tcon_speed_info[index].data) ; speed_set[set_index].tcon_speed_info[index].data = NULL ; printLog(PUSH, "((TCON SPEED)) SET_INDEX(%d) INDEX(%d) FREE\n", set_index, index) ; } speed_set[set_index].tcon_speed_info[index].num = onlyRecvInfoNum ; speed_set[set_index].tcon_speed_info[index].realSize = INT_LEN + INT_LEN + INT_LEN + onlyRecvInfoNum ; if(speed_set[set_index].tcon_speed_info[index].realSize > PACKET_SIZE) { speed_set[set_index].tcon_speed_info[index].compFlag = 1 ; if((speed_set[set_index].tcon_speed_info[index].data = (char *) malloc (speed_set[set_index].tcon_speed_info[index].realSize)) == NULL) { printLog(PUSH, "ERR: Mamory Alloc Fail=>Program Exit\n") ; exit_handler() ; } memset(speed_set[set_index].tcon_speed_info[index].data, 0, speed_set[set_index].tcon_speed_info[index].realSize) ; speed_set[set_index].tcon_speed_info[index].compSize = speed_set[set_index].tcon_speed_info[index].realSize ; ret = compress(speed_set[set_index].tcon_speed_info[index].data, (long *)&(speed_set[set_index].tcon_speed_info[index].compSize), onlyRecvInfo, speed_set[set_index].tcon_speed_info[index].realSize) ; printLog(PUSH, "compress() : ret(%d) set_index(%d) index(%d) compFlag(%d) compSize(%d) realSize(%d)\n", ret, set_index, index, speed_set[set_index].tcon_speed_info[index].compFlag, speed_set[set_index].tcon_speed_info[index].compSize, speed_set[set_index].tcon_speed_info[index].realSize) ; } else { speed_set[set_index].tcon_speed_info[index].compFlag = 0 ; if((speed_set[set_index].tcon_speed_info[index].data = (char *) malloc (speed_set[set_index].tcon_speed_info[index].realSize)) == NULL) { printLog(PUSH, "ERR: Mamory Alloc Fail=>Program Exit\n") ; exit_handler() ; } memset(speed_set[set_index].tcon_speed_info[index].data, 0, speed_set[set_index].tcon_speed_info[index].realSize) ; memcpy(speed_set[set_index].tcon_speed_info[index].data, onlyRecvInfo, speed_set[set_index].tcon_speed_info[index].realSize) ; speed_set[set_index].tcon_speed_info[index].compSize = speed_set[set_index].tcon_speed_info[index].realSize ; } if(onlyRecvInfo != NULL) free(onlyRecvInfo) ; onlyRecvInfo = NULL ; printLog(PUSH, "((ROTIS SPEED)) SET_INDEX(%d) INDEX(%d) - NUM(%d) CF(%d) CS(%d) RS(%d) CREATE\n", set_index, index, speed_set[set_index].tcon_speed_info[index].num, speed_set[set_index].tcon_speed_info[index].compFlag, speed_set[set_index].tcon_speed_info[index].compSize, speed_set[set_index].tcon_speed_info[index].realSize) ; DataToFile(speed_set[set_index].version*10, &(speed_set[set_index].tcon_speed_info[index])) ; printLog(PUSH, "DataToFile() - speed_set(%d).tcon_speed_info(%d)END\n", set_index, index) ; } } // END OF FOR if(type == TYPE_TCON_SPEED_INFO) { pthread_mutex_lock(&tc_lock) ; g_tcon_speed_flag = index ; pthread_mutex_unlock(&tc_lock) ; } error_exit : if(info != NULL) free (info) ; info = NULL ; close(sockfd) ; printLog(PUSH, "===GET_SPEED_INFO(%d) END===\n", type) ; return ret ; }
int get_tcon_text(int type) { time_t t ; int index = 0 ; int sockfd ; int wlen, rlen ; struct sockaddr_in serv_addr ; int ret = E_NO_ERR ; SRH_IN in ; SRH_OUT out ; TOTAL_INFO total_info ; TXT_INFO txt_info ; char *data = NULL ; int offset = 0 ; char *content = NULL ; // T_INFO *info = NULL ; int i = 0 ; fd_set readset ; struct timeval tmv ; memset(&in, 0, sizeof(SRH_IN)) ; memset(&out, 0, sizeof(SRH_OUT)) ; memset(&total_info, 0, sizeof(TOTAL_INFO)) ; memset(&txt_info, 0, sizeof(TXT_INFO)) ; printLog(PUSH, "===GET_TEXT_INFO(%d) START===\n", type) ; t = time(&t) ; memset((char *) &serv_addr, 0, sizeof(serv_addr)) ; serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = inet_addr(Config.TRAFFIC_IP) ; serv_addr.sin_port = htons(Config.TRAFFIC_PORT) ; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printLog(PUSH, "clientsoc: can't open stream socket[%s:%d]\n", Config.TRAFFIC_IP, Config.TRAFFIC_PORT) ; ret = E_TCP_FAIL ; goto error_exit ; } if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printLog(PUSH, "clientsoc: can't connect to server[%s:%d]\n", Config.TRAFFIC_IP, Config.TRAFFIC_PORT) ; ret = E_TCP_FAIL ; goto error_exit ; } in.op_code = htonl(TYPE_TCON_TEXT_INFO) ; //: 고속도로 속보(TEXT) // in.limit_time = htonl((int)Config.LIMIT_TIME) ; in.limit_time = htonl(0) ; strcpy(in.req_info, Config.ID) ; if((wlen = writen(sockfd, &in, sizeof(SRH_IN))) != sizeof(SRH_IN)) { printLog(PUSH, "ERR: write SRH_IN[wlen:%d/%d]\n", wlen, sizeof(SRH_IN)) ; ret = E_TCP_FAIL ; goto error_exit ; } printLog(PUSH, "SEND: SRH_IN[wlen:%d]\n", wlen) ; FD_ZERO(&readset) ; FD_SET(sockfd, &readset) ; tmv.tv_sec = 30 ; tmv.tv_usec = 0 ; if(select(sockfd+1, &readset, NULL, NULL, &tmv) < 0) { printLog(PUSH, "ERR: select Error : SOCKET(%d) CLOSE\n", sockfd) ; ret = E_TCP_FAIL ; goto error_exit ; } if (!FD_ISSET(sockfd, &readset)) { // 30초동안 msgid를 받지 못한 경우, printLog(PUSH, "ERR: SockFD(%d) TimeOut wait read_time(%d)\n", sockfd, tmv.tv_sec) ; ret = E_TCP_TIMEOUT ; goto error_exit ; } if((rlen = readn(sockfd, &out, sizeof(SRH_OUT))) != sizeof(SRH_OUT)) { printLog(PUSH, "ERR: read SRH_OUT[rlen:%d/%d]\n", rlen, sizeof(SRH_OUT)) ; ret = E_TCP_FAIL ; goto error_exit ; } out.result = ntohl(out.result) ; out.op_code = ntohl(out.op_code) ; out.count = ntohl(out.count) ; if(out.op_code == TYPE_TCON_TEXT_INFO) G_rev_op7_ret = out.result ; printLog(PUSH, "READ: SRH_OUT[rlen:%d]-RESULT(%d) OPCODE(%d) COUNT(%d) \n", rlen, out.result, out.op_code, out.count) ; if(out.count > 0) { if((data = (char *) malloc(out.count)) == NULL) { printLog(PUSH, "ERR: Memory Alloc Fail ==> Program Exit\n") ; exit_handler() ; } memset(data, 0, out.count) ; FD_ZERO(&readset) ; FD_SET(sockfd, &readset) ; tmv.tv_sec = 30 ; tmv.tv_usec = 0 ; if(select(sockfd+1, &readset, NULL, NULL, &tmv) < 0) { printLog(PUSH, "ERR: select Error : SOCKET(%d) CLOSE\n", sockfd) ; ret = E_TCP_FAIL ; goto error_exit ; } if (!FD_ISSET(sockfd, &readset)) { // 30초동안 msgid를 받지 못한 경우, printLog(PUSH, "ERR: SockFD(%d) TimeOut wait read_time(%d)\n", sockfd, tmv.tv_sec) ; ret = E_TCP_TIMEOUT ; goto error_exit ; } if((rlen = readn(sockfd, data, out.count)) != out.count) { printLog(PUSH, "ERR: read T_INFO[rlen:%d/%d]\n", i, rlen, out.count) ; ret = E_TCP_FAIL ; goto error_exit ; } printLog(PUSH, "READ: DATA[%d]\n", out.count) ; offset = 0 ; memcpy(&total_info, &data[offset], sizeof(TOTAL_INFO)) ; offset += sizeof(TOTAL_INFO) ; total_info.f_cnt = ntohl(total_info.f_cnt) ; printLog(PUSH, "f_cnt[%d]\n", total_info.f_cnt) ; for(i = 0 ; i < total_info.f_cnt; i++) { memset(&txt_info, 0, sizeof(TXT_INFO)) ; memcpy(&txt_info, &data[offset], sizeof(TXT_INFO)) ; offset += sizeof(TXT_INFO) ; txt_info.f_no = ntohl(txt_info.f_no) ; txt_info.f_size = ntohl(txt_info.f_size) ; txt_info.f_cnt = ntohl(txt_info.f_cnt) ; txt_info.date = ntohl(txt_info.date) ; txt_info.time = ntohl(txt_info.time) ; if((content = (char *) malloc(txt_info.f_size+1)) == NULL) { printLog(PUSH, "ERR: Memory Alloc Fail ==> Program Exit\n") ; exit_handler() ; } memset(content, 0, txt_info.f_size+1) ; memcpy(content, &data[offset], txt_info.f_size) ; offset += txt_info.f_size ; // printLog(PUSH, "[%d] f_no[%d] f_name[%s] f_size[%d]f_cnt[%d]date[%d]time[%d]content[%s]\n", // i, txt_info.f_no, txt_info.f_name, txt_info.f_size, txt_info.f_cnt, txt_info.date, txt_info.time, content) ; if(content != NULL) free(content) ; content = NULL ; } } //-----------------// if(type == TYPE_TCON_TEXT_INFO) { index = (g_tcon_text_flag+1) % 2 ; printLog(PUSH, "NEW DATA((HIGHWAY_TEXT_INFO)) SETTING : INDEX(%d)\n", index) ; receive_time[index] = t ; //: 추후 수정 if(text_info[index].data != NULL) { free(text_info[index].data) ; text_info[index].data = NULL ; } memset(&(text_info[index]), 0, sizeof(G_INFO)) ; text_info[index].num = total_info.f_cnt ; text_info[index].realSize = out.count ; if(out.count > PACKET_SIZE) { text_info[index].compFlag = 1 ; if((text_info[index].data = (char *) malloc (out.count)) == NULL) { printLog(PUSH, "ERR: Mamory Alloc Fail=>Program Exit\n") ; exit_handler() ; } memset(text_info[index].data, 0, out.count) ; text_info[index].compSize = out.count; ret = compress(text_info[index].data, (long *)&(text_info[index].compSize), data, out.count) ; printLog(PUSH, "compress() : ret(%d) index(%d) compSize(%d) realSize(%d)\n", ret, index, text_info[index].compSize, text_info[index].realSize) ; if(data != NULL) free(data) ; data = NULL ; } else { text_info[index].compFlag = 0 ; text_info[index].compSize = text_info[index].realSize ; text_info[index].data = data ; } DataToFile(101, &(text_info[index])) ; printLog(PUSH, "DataToFile() - text_info END\n") ; pthread_mutex_lock(&tt_lock) ; g_tcon_text_flag = index ; pthread_mutex_unlock(&tt_lock) ; } error_exit : close(sockfd) ; printLog(PUSH, "===GET_TEXT_INFO(%d) END===\n", type) ; return ret ; }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif #ifdef ENABLE_LOGGING setupDebug(); #endif int seed = time(NULL); // set locale to system default setlocale(LC_ALL, ""); bindtextdomain("cataclysm-dda", "lang/mo"); textdomain("cataclysm-dda"); //args: world seeding only. argc--; argv++; while (argc){ if(std::string(argv[0]) == "--seed"){ argc--; argv++; if(argc){ seed = djb2_hash((unsigned char*)argv[0]); argc--; argv++; } } else // ignore unknown args. argc--; argv++; } // ncurses stuff load_options(); // For getting size options initscr(); // Initialize ncurses noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers init_colors(); // See color.cpp // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); bool quit_game = false; bool delete_world = false; g = new game; g->init_ui(); MAPBUFFER.set_game(g); g->load_artifacts(); //artifacts have to be loaded before any items are created MAPBUFFER.load(); curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif do { g->setup(); while (!g->do_turn()) ; if (g->uquit == QUIT_DELETE_WORLD) delete_world = true; if (g->game_quit()) quit_game = true; } while (!quit_game); if (delete_world) { g->delete_save(); } else { MAPBUFFER.save_if_dirty(); } exit_handler(-999); return 0; }
///[주유소 리스트 정보 추출]/////: 1060 int main(void) { int len, wlen, rlen ; struct sockaddr_in serv_addr; OPW_HEADER hd ; OPW_RESULT rd ; char search_opt[D_SEARCH_OPT_SIZE+1] = {'\0'} ; int i ; OPW_LIST_REQ in ; OPW_LIST_INFO *out = NULL ; int search_num = 0 ; int start_pos = 0 ; int pole = 0 ; int sort_opt = 0 ; memset(&hd, 0, sizeof(OPW_HEADER)) ; memset(&rd, 0, sizeof(OPW_RESULT)) ; memset(&in, 0, sizeof(OPW_LIST_REQ)) ; printf("====[OPW_HEADER]====\n") ; hd.serviceid = htonl(OPW_LIST) ; InputInt("hd.mdn", &(hd.mdn), 1031993325) ; hd.mdn = htonl(hd.mdn) ; InputChar("hd.menu_id", &(hd.menu_id), 'O') ; printf("oiltype: G-휘발유 K-경유 L-LPG A-ALL\n") ; InputChar("hd.oil_type", &(hd.oil_type), 'A') ; printf("search_opt: AL-좌표로 검색 IL-주소로 검색\n") ; InputString("hd.search_opt", search_opt, D_SEARCH_OPT_SIZE+1, "AL") ; memcpy(hd.search_opt, search_opt, D_SEARCH_OPT_SIZE) ; printf("====[OPW_LIST_REQ]====\n") ; memset(&in, 0, sizeof(OPW_LIST_REQ)) ; InputInt("in.search_num", &(search_num), 10) ; InputInt("in.start_pos", &(start_pos), 0) ; printf("pole: 3072-LPG 16-SK 32-GS 64-H-OIL 128-S-OIL 512-기타 144-(SK or S-OIL) 0-ALL\n") ; InputInt("in.pole", &(pole), 0) ; printf("pole: 1-휘발유 가격순 2-경유 가격순 4-LPG 가격순 5-거리순 6-휘발유/경유/LPG 순서\n") ; InputInt("in.sort_opt", &(sort_opt), 6) ; if(!strcmp(search_opt, "AL")) { //좌표로 검색 InputInt("in.x", &(in.x), 320821) ; InputInt("in.y", &(in.y), 551729) ; InputInt("in.radius", &(in.radius), 5000) ; } else if(!strcmp(search_opt, "IL")) { //주소로 검색 InputString("cido", in.sido, D_SIDO_SIZE, "인천광역시") ; InputString("gugun", in.gugun, D_GUGUN_SIZE, "") ; InputString("dong", in.dong, D_DONG_SIZE, "") ; } else { //잘못된 선택 return 0 ; } // sprintf(in.sido, "인천광역시") ; // sprintf(in.gugun, "계양구") ; in.search_num = htonl(search_num) ; in.start_pos = htonl(start_pos) ; in.x = htonl(in.x) ; in.y = htonl(in.y) ; in.radius = htonl(in.radius) ; in.nr_num = htonl(in.nr_num) ; in.pole = pole ; in.sort_opt = sort_opt ; in.pole = htons(in.pole) ; in.sort_opt = htons(in.sort_opt) ; memset((char *) &serv_addr, 0, sizeof(serv_addr)) ; serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = inet_addr(SM_SERVER_IP) ; serv_addr.sin_port = htons(SM_SERVER_PORT) ; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("clientsoc: can't open stream socket") ; close(sockfd), exit(0); } if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printf("clientsoc: can't connect to server") ; close(sockfd), exit(0); } if((wlen = write(sockfd, &hd, sizeof(OPW_HEADER))) <= 0) { printf("ERR: write OPW_HEADER[wlen:%d]\n", wlen) ; close(sockfd), exit(1) ; } printf("SEND: OPW_HEADER[wlen:%d]\n", wlen) ; if((wlen = write(sockfd, &in, sizeof(OPW_LIST_REQ))) < 0) { printf("ERR: write OPW_LIST_REQ\n") ; close(sockfd), exit(1) ; } printf("SEND: OPW_LIST_REQ[wlen:%d]\n", wlen) ; if ((rlen = read(sockfd, &rd, sizeof(OPW_RESULT))) <= 0) { printf("ERR: read OPW_RESULT[rlen:%d]...\n", rlen) ; close(sockfd), exit(1) ; } printf("READ: OPW_RESULT[rlen:%d]\n", rlen) ; rd.res_code = ntohl(rd.res_code) ; rd.total_num = ntohl(rd.total_num) ; rd.search_num = ntohl(rd.search_num) ; printf("OPW_RESULT: res_code[%d] total_num[%d] search_num[%d]\n", rd.res_code, rd.total_num, rd.search_num) ; if(rd.res_code == M_TRUE) { out = (OPW_LIST_INFO *) malloc (rd.search_num * sizeof(OPW_LIST_INFO)) ; memset(out, 0, rd.search_num * sizeof(OPW_LIST_INFO)) ; for(i = 0 ; i < rd.search_num; i++) { if((rlen = read(sockfd, &(out[i]), sizeof(OPW_LIST_INFO))) <= 0) { printf("ERR: [%d] read OPW_LIST_INFO(%d)\n", i, rlen) ; if(out != NULL) free(out), out = NULL ; close(sockfd), exit(1) ; } // printf("READ: OPW_LIST_INFO(%d) Len:[%d]\n", i, rlen) ; } for(i = 0 ; i < rd.search_num; i ++) { out[i].id = ntohl(out[i].id) ; out[i].pole = ntohl(out[i].pole) ; out[i].g_price = ntohs(out[i].g_price) ; out[i].k_price = ntohs(out[i].k_price) ; out[i].d_price = ntohs(out[i].d_price) ; out[i].l_price = ntohs(out[i].l_price) ; out[i].update_date = ntohl(out[i].update_date) ; out[i].update_time = ntohl(out[i].update_time) ; out[i].x = ntohl(out[i].x) ; out[i].y = ntohl(out[i].y) ; out[i].distance = ntohl(out[i].distance) ; printf("[%d]-ID[%d]NAME[%.52s] POLE[%d]G[%d]K[%d]D[%d]L[%d]DATE[%d]TIME[%d]X[%d]Y[%d]DISTANCE[%d]\n", i, out[i].id, out[i].name, out[i].pole, out[i].g_price, out[i].k_price, out[i].d_price, out[i].l_price, out[i].update_date, out[i].update_time, out[i].x, out[i].y, out[i].distance) ; } if(out != NULL) free(out) ; } exit_handler() ; }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif int seed = time(NULL); bool verifyexit = false; bool check_all_mods = false; // Set default file paths #ifdef PREFIX #define Q(STR) #STR #define QUOTE(STR) Q(STR) init_base_path(std::string(QUOTE(PREFIX))); #else PATH_INFO::init_base_path(""); #endif #ifdef USE_HOME_DIR PATH_INFO::init_user_dir(); #else PATH_INFO::init_user_dir("./"); #endif PATH_INFO::set_standart_filenames(); MAP_SHARING::setDefaults(); // Process CLI arguments int saved_argc = --argc; // skip program name char **saved_argv = ++argv; while (argc) { if(std::string(argv[0]) == "--seed") { argc--; argv++; if(argc) { seed = djb2_hash((unsigned char *)argv[0]); argc--; argv++; } } else if(std::string(argv[0]) == "--jsonverify") { argc--; argv++; verifyexit = true; } else if(std::string(argv[0]) == "--check-mods") { argc--; argv++; check_all_mods = true; } else if(std::string(argv[0]) == "--basepath") { argc--; argv++; if(argc) { PATH_INFO::init_base_path(std::string(argv[0])); PATH_INFO::set_standart_filenames(); argc--; argv++; } } else if(std::string(argv[0]) == "--userdir") { argc--; argv++; if (argc) { PATH_INFO::init_user_dir( argv[0] ); PATH_INFO::set_standart_filenames(); argc--; argv++; } } else if(std::string(argv[0]) == "--username") { argc--; argv++; if (argc) { MAP_SHARING::setUsername(std::string(argv[0])); argc--; argv++; } } else if(std::string(argv[0]) == "--addadmin") { argc--; argv++; if (argc) { MAP_SHARING::addAdmin(std::string(argv[0])); argc--; argv++; } } else if(std::string(argv[0]) == "--adddebugger") { argc--; argv++; if (argc) { MAP_SHARING::addDebugger(std::string(argv[0])); argc--; argv++; } } else if(std::string(argv[0]) == "--shared") { argc--; argv++; MAP_SHARING::setSharing(true); MAP_SHARING::setCompetitive(true); MAP_SHARING::setWorldmenu(false); } else if(std::string(argv[0]) == "--competitive") { argc--; argv++; MAP_SHARING::setCompetitive(true); } else { // Skipping other options. argc--; argv++; } } while (saved_argc) { if(std::string(saved_argv[0]) == "--worldmenu") { saved_argc--; saved_argv++; MAP_SHARING::setWorldmenu(true); } else if(std::string(saved_argv[0]) == "--datadir") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("datadir", std::string(saved_argv[0])); PATH_INFO::update_datadir(); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--savedir") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("savedir", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--configdir") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("config_dir", std::string(saved_argv[0])); PATH_INFO::update_config_dir(); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--optionfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("options", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--keymapfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("keymap", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--autopickupfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("autopickup", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--motdfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("motd", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else { // ignore unknown args. saved_argc--; saved_argv++; } } // setup debug loggind #ifdef ENABLE_LOGGING setupDebug(); #endif // set locale to system default setlocale(LC_ALL, ""); #ifdef LOCALIZE const char *locale_dir; #ifdef __linux__ if (!FILENAMES["base_path"].empty()) { locale_dir = std::string(FILENAMES["base_path"] + "share/locale").c_str(); } else { locale_dir = "lang/mo"; } #else locale_dir = "lang/mo"; #endif // __linux__ bindtextdomain("cataclysm-dda", locale_dir); bind_textdomain_codeset("cataclysm-dda", "UTF-8"); textdomain("cataclysm-dda"); #endif // LOCALIZE // ncurses stuff initOptions(); load_options(); // For getting size options #ifdef LOCALIZE setlocale(LC_ALL, OPTIONS["USE_LANG"].getValue().c_str()); #endif // LOCALIZE if (initscr() == NULL) { // Initialize ncurses DebugLog() << "initscr failed!\n"; return 1; } init_interface(); noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers #if !(defined TILES || defined _WIN32 || defined WINDOWS) // For tiles or windows, this is handled already in initscr(). init_colors(); #endif // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); g = new game; // First load and initialize everything that does not // depend on the mods. try { if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) { debugmsg("Can't open or create %s. Check permissions.", FILENAMES["user_dir"].c_str()); exit_handler(-999); } g->load_static_data(); if (verifyexit) { if(g->game_error()) { exit_handler(-999); } exit_handler(0); } if (check_all_mods) { // Here we load all the mods and check their // consistency (both is done in check_all_mod_data). g->init_ui(); popup_nowait("checking all mods"); g->check_all_mod_data(); if(g->game_error()) { exit_handler(-999); } // At this stage, the mods (and core game data) // are find and we could start playing, but this // is only for verifying that stage, so we exit. exit_handler(0); } } catch(std::string &error_message) { if(!error_message.empty()) { debugmsg("%s", error_message.c_str()); } exit_handler(-999); } // Now we do the actuall game g->init_ui(); if(g->game_error()) { exit_handler(-999); } curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif bool quit_game = false; do { if(!g->opening_screen()) { quit_game = true; } while (!quit_game && !g->do_turn()) ; if (g->game_quit() || g->game_error()) { quit_game = true; } } while (!quit_game); exit_handler(-999); return 0; }
int main(int argc, char *argv[]) { #ifdef ENABLE_LOGGING setupDebug(); #endif int seed = time(NULL); //args: world seeding only. argc--; argv++; while (argc){ if(std::string(argv[0]) == "--seed"){ argc--; argv++; if(argc){ seed = djb2_hash((unsigned char*)argv[0]); argc--; argv++; } } else // ignore unknown args. argc--; argv++; } // ncurses stuff load_options(); // For getting size options initscr(); // Initialize ncurses noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers init_colors(); // See color.cpp curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); bool quit_game = false; bool delete_world = false; game *g = new game; g->init_ui(); MAPBUFFER.set_game(g); MAPBUFFER.load(); #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif do { g->setup(); while (!g->do_turn()) ; if (g->uquit == QUIT_DELETE_WORLD) delete_world = true; if (g->game_quit()) quit_game = true; } while (!quit_game); if (delete_world) { g->delete_save(); } else { MAPBUFFER.save_if_dirty(); } exit_handler(-999); return 0; }
int main(int argc, char *argv[]) { pid_t pid ; int stat ; pthread_t pthread_ping_id; int ret ; isDup(argv[0]) ; if((pid = fork()) < 0) return -1; else if(pid != 0) exit(0); setsid() ; set_signal() ; if (argc > 1) { if (argc == 3) { if (strcmp(argv[1], "-f") == 0) { strcpy(config_file_path, argv[2]); } else { printf("---------------------------------\n"); printf("-%s [-f ConfigFilePath]\n", argv[0]); printf("---------------------------------\n"); } } else { printf("---------------------------------\n"); printf("-%s [-f ConfigFilePath]\n", argv[0]); printf("---------------------------------\n"); } } else sprintf(config_file_path, "../config/CCTVSvr.Config"); memset(&Config, 0, sizeof(CONFIG_T)) ; readConfig(config_file_path, &Config) ; Log = openLog(argv[0], Config.LOG_FILE, LOG_MODE) ; printLog(HEAD, "=====[Program Start]=====\n") ; printConfig(&Config); #ifdef _USEDB if((ret = mydbc_connect(Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, Config.DB_HOST, Config.DB_PORT, Config.DB_CONN_COUNT)) != DB_SUCCESS) { printLog(HEAD, "DB Connection ERROR[%d]\n", ret); exit(0); } else { printLog(HEAD, "DB Connection Success...\n"); } #endif pthread_mutex_init(&p_lock, NULL); thread_count = 0; #ifdef _USEDB // DB PING-PONG if((stat = pthread_create(&pthread_ping_id, NULL, db_conn_check, (void *)NULL)) != 0) { printLog(HEAD, "ERR: (%s)(%d)\n", strerror(errno), errno); if(stat == EAGAIN) { printLog(HEAD, "ERR: not enough system resources to create a process for the new thread. (%d)(%d)\n", EAGAIN, stat); } exit_handler() ; } #endif Worker(); exit_handler() ; return M_TRUE ; }
int main( int argc, char *argv[]) { int c; int error; void *fs_hanp; size_t fs_hlen; char buf[BUFSIZ + 8]; Progname = argv[0]; fsname = NULL; while ((c = getopt(argc, argv, "vs:S:")) != EOF) { switch (c) { case 's': Sleep = atoi(optarg); break; case 'S': oldsid = atoi(optarg); break; case 'v': Verbose = 1; break; case '?': default: usage(Progname); exit(1); } } if (optind >= argc) { usage(Progname); exit(1); } fsname = argv[optind]; if (fsname == NULL) { usage(Progname); exit(1); } /* * Establish an exit handler */ error = establish_handler(); if (error) exit(1); /* * Init the dmapi, and get a filesystem handle so * we can set up our events */ if (oldsid) { sid = oldsid; } else { error = setup_dmapi(&sid); if (error) exit(1); } error = get_fs_handle(fsname, &fs_hanp, &fs_hlen); if (error) goto cleanup; /* * Set the event disposition so that our session will receive * all the events for the given file system */ error = set_disposition(sid, fs_hanp, fs_hlen); if (error) goto cleanup; /* * Enable monitoring for all events in the given file system */ error = set_events(sid, fs_hanp, fs_hlen); if (error) goto cleanup; /* * Set line buffering!! */ error = setvbuf(stdout, buf, _IOLBF, BUFSIZ); if (error) goto cleanup; /* * Now sit in an infinite loop, reporting on any events that occur. * The program is exited after a signal through exit_handler(). */ printf("\n"); event_loop(sid, 1 /*waitflag*/); /* * If we get here, cleanup after the event_loop failure */ cleanup: exit_handler(0); return(1); }
/* Open LDAP and Notifier connection. * @return 0 on success, 1 on error. */ static int do_connection(univention_ldap_parameters_t *lp) { LDAPMessage *res; int rc; struct timeval timeout = { .tv_sec = 10, .tv_usec = 0, }; if (univention_ldap_open(lp) != LDAP_SUCCESS) goto fail; if (notifier_client_new(NULL, lp->host, 1) != 0) goto fail; /* check if we are connected to an OpenLDAP */ rc = ldap_search_ext_s(lp->ld, lp->base, LDAP_SCOPE_BASE, "objectClass=univentionBase", NULL, 0, NULL, NULL, &timeout, 0, &res); ldap_msgfree(res); switch (rc) { case LDAP_SUCCESS: return 0; case LDAP_NO_SUCH_OBJECT: univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "Failed to find \"(objectClass=univentionBase)\" on LDAP server %s:%d", lp->host, lp->port); break; default: univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "Failed to search for \"(objectClass=univentionBase)\" on LDAP server %s:%d with message %s", lp->host, lp->port, ldap_err2string(rc)); break; } fail: notifier_client_destroy(NULL); if (lp->ld) ldap_unbind_ext(lp->ld, NULL, NULL); lp->ld = NULL; return 1; } int main(int argc, char* argv[]) { univention_ldap_parameters_t *lp; univention_ldap_parameters_t *lp_local; char *server_role; #ifdef WITH_KRB5 univention_krb5_parameters_t *kp = NULL; bool do_kinit = false; #else void *kp = NULL ; #endif int debugging = 0; bool from_scratch = false; bool foreground = false; bool initialize_only = false; bool write_transaction_file = false; int rv; NotifierID id = -1; #ifndef WITH_DB42 NotifierID old_id = -1; #else CacheMasterEntry master_entry; #endif struct stat stbuf; char *f = NULL; univention_debug_init("stderr", 1, 1); if ((lp = univention_ldap_new()) == NULL) exit(1); lp->authmethod = LDAP_AUTH_SASL; if ((lp_local = univention_ldap_new()) == NULL) exit(1); #if WITH_KRB5 if ((kp=univention_krb5_new()) == NULL) exit(1); #endif /* parse arguments */ for (;;) { int c; c = getopt(argc, argv, "d:FH:h:p:b:D:w:y:xZY:U:R:Km:Bc:giol:"); if (c < 0) break; switch (c) { case 'd': debugging=atoi(optarg); break; case 'F': foreground = true; break; case 'H': lp->uri=strdup(optarg); break; case 'h': lp->host=strdup(optarg); break; case 'p': lp->port=atoi(optarg); break; case 'b': lp->base=strdup(optarg); break; case 'm': if ((module_dirs = realloc(module_dirs, (module_dir_count+2)*sizeof(char*))) == NULL) { return 1; } module_dirs[module_dir_count] = strdup(optarg); module_dirs[module_dir_count+1] = NULL; module_dir_count++; break; case 'c': cache_dir=strdup(optarg); break; case 'l': ldap_dir = strdup(optarg); if (asprintf(&transaction_file, "%s/listener/listener", ldap_dir) < 0) abort(); break; case 'D': lp->binddn=strdup(optarg); break; case 'w': lp->bindpw=strdup(optarg); #ifdef WITH_KRB5 kp->password=strdup(optarg); #endif /* remove password from process list */ memset(optarg, 'X', strlen(optarg)); break; case 'Z': lp->start_tls++; break; case 'x': lp->authmethod = LDAP_AUTH_SIMPLE; break; case 'y': lp->bindpw=read_pwd_from_file(optarg); #ifdef WITH_KRB5 kp->password=strdup(lp->bindpw); #endif break; case 'Y': lp->sasl_mech=strdup(optarg); break; case 'U': asprintf(&lp->sasl_authzid, "u:%s", optarg); /* kp->username=strdup(optarg); */ case 'R': lp->sasl_realm=strdup(optarg); #ifdef WITH_KRB5 kp->realm=strdup(optarg); #endif break; #ifdef WITH_KRB5 case 'K': do_kinit = true; break; #endif case 'g': from_scratch = true; break; case 'i': initialize_only = true; from_scratch = true; foreground = true; break; case 'o': write_transaction_file = true; break; case 'B': backup_notifier = 1; break; default: usage(); exit(1); } } if (asprintf(&f, "%s/bad_cache", cache_dir) < 0) abort(); if (stat(f, &stbuf) == 0) { exit(3); } free(f); univention_debug_set_level(UV_DEBUG_LISTENER, debugging); univention_debug_set_level(UV_DEBUG_LDAP, debugging); univention_debug_set_level(UV_DEBUG_KERBEROS, debugging); snprintf(pidfile, PATH_MAX, "%s/pid", cache_dir); signals_init(); if (!foreground && daemonize() != 0) exit(EXIT_FAILURE); drop_privileges(); if (from_scratch) purge_cache(cache_dir); prepare_cache(cache_dir); /* choose server to connect to */ if (lp->host == NULL && lp->uri == NULL) { select_server(lp); univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_INFO, "no server given, choosing one by myself (%s)", lp->host); } #ifdef WITH_KRB5 if (!do_kinit) kp = NULL; if (kp != NULL && univention_krb5_init(kp) != 0) { univention_debug(UV_DEBUG_KERBEROS, UV_DEBUG_ERROR, "kinit failed"); exit(1); } #endif while (do_connection(lp) != 0) { univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_WARN, "can not connect to ldap server %s:%d", lp->host, lp->port); if (suspend_connect()) { if (initialize_only) { univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "can not connect to any ldap server, exit"); exit(1); } univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_WARN, "can not connect to any ldap server, retrying in 30 seconds"); sleep(30); } select_server(lp); univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_WARN, "chosen server: %s:%d", lp->host, lp->port); } univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_INFO, "connection okay to host %s:%d", lp->host, lp->port); /* connect to local LDAP server */ server_role = univention_config_get_string("server/role"); if ( server_role != NULL ) { if (!strcmp(server_role, "domaincontroller_backup") || !strcmp(server_role, "domaincontroller_slave")) { // if not master lp_local->host = strdup("localhost"); // or fqdn e.g. from univention_config_get_string("ldap/server/name"); lp_local->base = strdup(lp->base); lp_local->binddn = strdup(lp->binddn); lp_local->bindpw = strdup(lp->bindpw); } free(server_role); } /* XXX: we shouldn't block all signals for so long */ signals_block(); cache_init(); handlers_init(); /* pass data to handlers */ if (lp->base != NULL) handlers_set_data_all("basedn", lp->base); if (lp->binddn != NULL) handlers_set_data_all("binddn", lp->binddn); if (lp->bindpw != NULL) handlers_set_data_all("bindpw", lp->bindpw); if (lp->host != NULL) handlers_set_data_all("ldapserver", lp->host); convert_cookie(); if (notifier_get_id_s(NULL, &id) != 0) { univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "failed to receive current ID"); return 1; } if (initialize_only) { INIT_ONLY=1; } /* update schema */ if ((rv=change_update_schema(lp)) != LDAP_SUCCESS) return rv; /* do initial import of entries */ if ((rv=change_new_modules(lp)) != LDAP_SUCCESS) { univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "change_new_modules: %s", ldap_err2string(rv)); return rv; } signals_unblock(); /* if no ID is set, assume the database has just been initialized */ #ifdef WITH_DB42 if ((rv=cache_get_master_entry(&master_entry)) == DB_NOTFOUND) { master_entry.id = id; if ((rv=cache_update_master_entry(&master_entry, NULL)) != 0) exit(1); } else if (rv != 0) exit(1); #else cache_get_int("notifier_id", &old_id, -1); if ((long)old_id == -1) { cache_set_int("notifier_id", id); } #endif if (!initialize_only) { rv = notifier_listen(lp, kp, write_transaction_file, lp_local); } if (rv != 0) univention_debug(UV_DEBUG_LISTENER, UV_DEBUG_ERROR, "listener: %d", rv); univention_ldap_close(lp); univention_ldap_close(lp_local); exit_handler(0); }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif #ifdef ENABLE_LOGGING setupDebug(); #endif int seed = time(NULL); // set locale to system default setlocale(LC_ALL, ""); #ifdef LOCALIZE bindtextdomain("cataclysm-dda", "lang/mo"); bind_textdomain_codeset("cataclysm-dda", "UTF-8"); textdomain("cataclysm-dda"); #endif //args: world seeding only. argc--; argv++; while (argc){ if(std::string(argv[0]) == "--seed"){ argc--; argv++; if(argc){ seed = djb2_hash((unsigned char*)argv[0]); argc--; argv++; } } else // ignore unknown args. argc--; argv++; } // ncurses stuff initOptions(); load_options(); // For getting size options initscr(); // Initialize ncurses #ifdef SDLTILES init_tiles(); #endif // SDLTILES noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers init_colors(); // See color.cpp // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); bool quit_game = false; g = new game; g->init_data(); if(g->game_error()) exit_handler(-999); g->init_ui(); MAPBUFFER.set_game(g); if(g->game_error()) exit_handler(-999); curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif do { if(!g->opening_screen()) { quit_game = true; } while (!g->do_turn()) ; if (g->game_quit() || g->game_error()) quit_game = true; } while (!quit_game); exit_handler(-999); return 0; }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif #ifdef ENABLE_LOGGING setupDebug(); #endif int seed = time(NULL); bool verifyexit = false; // set locale to system default setlocale(LC_ALL, ""); #ifdef LOCALIZE bindtextdomain("cataclysm-dda", "lang/mo"); bind_textdomain_codeset("cataclysm-dda", "UTF-8"); textdomain("cataclysm-dda"); #endif //args: world seeding only. argc--; argv++; while (argc) { if(std::string(argv[0]) == "--seed") { argc--; argv++; if(argc) { seed = djb2_hash((unsigned char *)argv[0]); argc--; argv++; } } else if(std::string(argv[0]) == "--jsonverify") { argc--; verifyexit = true; } else { // ignore unknown args. argc--; } argv++; } // ncurses stuff initOptions(); load_options(); // For getting size options initscr(); // Initialize ncurses init_interface(); noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers #if !(defined TILES || defined _WIN32 || defined WINDOWS) // For tiles or windows, this is handled already in initscr(). init_colors(); #endif // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); bool quit_game = false; g = new game; g->init_data(); if(g->game_error()) { exit_handler(-999); } if ( verifyexit ) { item_controller->check_itype_definitions(); item_controller->check_items_of_groups_exist(); MonsterGenerator::generator().check_monster_definitions(); MonsterGroupManager::check_group_definitions(); check_recipe_definitions(); exit_handler(0); } g->init_ui(); if(g->game_error()) { exit_handler(-999); } curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif do { if(!g->opening_screen()) { quit_game = true; } while (!quit_game && !g->do_turn()) ; if (g->game_quit() || g->game_error()) { quit_game = true; } } while (!quit_game); exit_handler(-999); return 0; }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif int seed = time(NULL); bool verifyexit = false; bool check_mods = false; std::string dump; dump_mode dmode = dump_mode::TSV; std::vector<std::string> opts; std::string world; /** if set try to load first save in this world on startup */ // Set default file paths #ifdef PREFIX #define Q(STR) #STR #define QUOTE(STR) Q(STR) PATH_INFO::init_base_path(std::string(QUOTE(PREFIX))); #else PATH_INFO::init_base_path(""); #endif #if (defined USE_HOME_DIR || defined USE_XDG_DIR) PATH_INFO::init_user_dir(); #else PATH_INFO::init_user_dir("./"); #endif PATH_INFO::set_standard_filenames(); MAP_SHARING::setDefaults(); { const char *section_default = nullptr; const char *section_map_sharing = "Map sharing"; const char *section_user_directory = "User directories"; const std::array<arg_handler, 12> first_pass_arguments = {{ { "--seed", "<string of letters and or numbers>", "Sets the random number generator's seed value", section_default, [&seed](int num_args, const char **params) -> int { if (num_args < 1) return -1; const unsigned char *hash_input = (const unsigned char *) params[0]; seed = djb2_hash(hash_input); return 1; } }, { "--jsonverify", nullptr, "Checks the cdda json files", section_default, [&verifyexit](int, const char **) -> int { verifyexit = true; return 0; } }, { "--check-mods", "[mods...]", "Checks the json files belonging to cdda mods", section_default, [&check_mods,&opts]( int n, const char *params[] ) -> int { check_mods = true; test_mode = true; for( int i = 0; i < n; ++i ) { opts.emplace_back( params[ i ] ); } return 0; } }, { "--dump-stats", "<what> [mode = TSV] [opts...]", "Dumps item stats", section_default, [&dump,&dmode,&opts](int n, const char *params[]) -> int { if( n < 1 ) { return -1; } test_mode = true; dump = params[ 0 ]; for( int i = 2; i < n; ++i ) { opts.emplace_back( params[ i ] ); } if( n >= 2 ) { if( !strcmp( params[ 1 ], "TSV" ) ) { dmode = dump_mode::TSV; return 0; } else if( !strcmp( params[ 1 ], "HTML" ) ) { dmode = dump_mode::HTML; return 0; } else { return -1; } } return 0; } }, { "--world", "<name>", "Load world", section_default, [&world](int n, const char *params[]) -> int { if( n < 1 ) { return -1; } world = params[0]; return 1; } }, { "--basepath", "<path>", "Base path for all game data subdirectories", section_default, [](int num_args, const char **params) { if (num_args < 1) return -1; PATH_INFO::init_base_path(params[0]); PATH_INFO::set_standard_filenames(); return 1; } }, { "--shared", nullptr, "Activates the map-sharing mode", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setSharing(true); MAP_SHARING::setCompetitive(true); MAP_SHARING::setWorldmenu(false); return 0; } }, { "--username", "<name>", "Instructs map-sharing code to use this name for your character.", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::setUsername(params[0]); return 1; } }, { "--addadmin", "<username>", "Instructs map-sharing code to use this name for your character and give you " "access to the cheat functions.", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::addAdmin(params[0]); return 1; } }, { "--adddebugger", "<username>", "Informs map-sharing code that you're running inside a debugger", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::addDebugger(params[0]); return 1; } }, { "--competitive", nullptr, "Instructs map-sharing code to disable access to the in-game cheat functions", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setCompetitive(true); return 0; } }, { "--userdir", "<path>", "Base path for user-overrides to files from the ./data directory and named below", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::init_user_dir(params[0]); PATH_INFO::set_standard_filenames(); return 1; } } }}; // The following arguments are dependent on one or more of the previous flags and are run // in a second pass. const std::array<arg_handler, 9> second_pass_arguments = {{ { "--worldmenu", nullptr, "Enables the world menu in the map-sharing code", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setWorldmenu(true); return true; } }, { "--datadir", "<directory name>", "Sub directory from which game data is loaded", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("datadir", params[0]); PATH_INFO::update_datadir(); return 1; } }, { "--savedir", "<directory name>", "Subdirectory for game saves", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("savedir", params[0]); return 1; } }, { "--configdir", "<directory name>", "Subdirectory for game configuration", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("config_dir", params[0]); PATH_INFO::update_config_dir(); return 1; } }, { "--memorialdir", "<directory name>", "Subdirectory for memorials", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("memorialdir", params[0]); return 1; } }, { "--optionfile", "<filename>", "Name of the options file within the configdir", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("options", params[0]); return 1; } }, { "--keymapfile", "<filename>", "Name of the keymap file within the configdir", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("keymap", params[0]); return 1; } }, { "--autopickupfile", "<filename>", "Name of the autopickup options file within the configdir", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("autopickup", params[0]); return 1; } }, { "--motdfile", "<filename>", "Name of the message of the day file within the motd directory", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("motd", params[0]); return 1; } }, }}; // Process CLI arguments. const size_t num_first_pass_arguments = sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]); const size_t num_second_pass_arguments = sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]); int saved_argc = --argc; // skip program name const char **saved_argv = (const char **)++argv; while (argc) { if(!strcmp(argv[0], "--help")) { printHelpMessage(first_pass_arguments.data(), num_first_pass_arguments, second_pass_arguments.data(), num_second_pass_arguments); return 0; } else { bool arg_handled = false; for (size_t i = 0; i < num_first_pass_arguments; ++i) { auto &arg_handler = first_pass_arguments[i]; if (!strcmp(argv[0], arg_handler.flag)) { argc--; argv++; int args_consumed = arg_handler.handler(argc, (const char **)argv); if (args_consumed < 0) { printf("Failed parsing parameter '%s'\n", *(argv - 1)); exit(1); } argc -= args_consumed; argv += args_consumed; arg_handled = true; break; } } // Skip other options. if (!arg_handled) { --argc; ++argv; } } } while (saved_argc) { bool arg_handled = false; for (size_t i = 0; i < num_second_pass_arguments; ++i) { auto &arg_handler = second_pass_arguments[i]; if (!strcmp(saved_argv[0], arg_handler.flag)) { --saved_argc; ++saved_argv; int args_consumed = arg_handler.handler(saved_argc, saved_argv); if (args_consumed < 0) { printf("Failed parsing parameter '%s'\n", *(argv - 1)); exit(1); } saved_argc -= args_consumed; saved_argv += args_consumed; arg_handled = true; break; } } // Ingore unknown options. if (!arg_handled) { --saved_argc; ++saved_argv; } } } if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) { printf("Can't open or create %s. Check permissions.\n", FILENAMES["user_dir"].c_str()); exit(1); } setupDebug(); /** * OS X does not populate locale env vars correctly (they usually default to * "C") so don't bother trying to set the locale based on them. */ #if (!defined MACOSX) if (setlocale(LC_ALL, "") == NULL) { DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '')."; } else { #endif try { std::locale::global( std::locale( "" ) ); } catch( const std::exception& ) { // if user default locale retrieval isn't implemented by system try{ // default to basic C locale std::locale::global( std::locale::classic() ); } catch( const std::exception &err ) { debugmsg( "%s", err.what() ); exit_handler(-999); } } #if (!defined MACOSX) } #endif get_options().init(); get_options().load(); set_language(); // in test mode don't initialize curses to avoid escape sequences being inserted into output stream if( !test_mode ) { try { catacurses::init_interface(); } catch( const std::exception &err ) { // can't use any curses function as it has not been initialized std::cerr << "Error while initializing the interface: " << err.what() << std::endl; DebugLog( D_ERROR, DC_ALL ) << "Error while initializing the interface: " << err.what() << "\n"; return 1; } } srand(seed); g = new game; // First load and initialize everything that does not // depend on the mods. try { g->load_static_data(); if (verifyexit) { exit_handler(0); } if( !dump.empty() ) { init_colors(); exit( g->dump_stats( dump, dmode, opts ) ? 0 : 1 ); } if( check_mods ) { init_colors(); loading_ui ui( false ); exit( g->check_mod_data( opts, ui ) && !test_dirty ? 0 : 1 ); } } catch( const std::exception &err ) { debugmsg( "%s", err.what() ); exit_handler(-999); } // Now we do the actual game. g->init_ui(); curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif #ifdef LOCALIZE std::string lang = ""; #if (defined _WIN32 || defined WINDOWS) lang = getLangFromLCID( GetUserDefaultLCID() ); #else const char *v = setlocale( LC_ALL, NULL ); if( v != NULL ) { lang = v; if( lang == "C" ) { lang = "en"; } } #endif if( get_option<std::string>( "USE_LANG" ).empty() && ( lang.empty() || !isValidLanguage( lang ) ) ) { select_language(); set_language(); } #endif while( true ) { if( !world.empty() ) { if( !g->load( world ) ) { break; } world.clear(); // ensure quit returns to opening screen } else { main_menu menu; if( !menu.opening_screen() ) { break; } } while( !g->do_turn() ); }; exit_handler(-999); return 0; }
int main(void) { SRH_IN srh_in ; SRH_OUT srh_out ; int i, len, wlen, rlen ; struct sockaddr_in serv_addr; int ret, ret_size = 0 ; time_t t ; int c_size = 0 ; int temp ; char *cookies = NULL; memset(&srh_in, 0, sizeof(SRH_IN)) ; memset(&srh_out, 0, sizeof(SRH_OUT)) ; c_size = strlen(COOKIES); cookies = (char *)malloc(c_size); memset(cookies, 0x00, c_size); memcpy(cookies, COOKIES, c_size); printf("====[SRH_IN]====\n") ; InputInt("srh_in.engVersion", &(srh_in.engVersion), 20060101) ; srh_in.engVersion = htonl(srh_in.engVersion) ; srh_in.mapVersion = htonl(1) ; srh_in.serviceId = htonl(1000) ; InputInt("srh_in.resourceVersion", &(srh_in.resourceVersion), 20041029) ; srh_in.resourceVersion = htonl(srh_in.resourceVersion) ; InputInt("srh_in.mdn", &(srh_in.mdn), 1199981076) ; srh_in.mdn = htonl(srh_in.mdn) ; memset((char *) &serv_addr, 0, sizeof(serv_addr)) ; serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = inet_addr(SM_SERVER_IP) ; serv_addr.sin_port = htons(SM_SERVER_PORT) ; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("clientsoc: can't open stream socket") ; close(sockfd), exit(0); } if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printf("clientsoc: can't connect to server") ; close(sockfd), exit(0); } if((wlen = write(sockfd, &srh_in, sizeof(SRH_IN))) <= 0) { printf("ERR: write SRH_IN[wlen:%d]\n", wlen) ; close(sockfd), exit(1) ; } printf("SEND: SRH_IN[wlen:%d]\n", wlen) ; printf("[%d] / COOKIE(%s)\n", c_size, cookies); c_size = htonl(c_size); if((wlen = write(sockfd, &c_size, sizeof(int))) <= 0) { printf("ERR: write c_size[wlen:%d]\n", wlen) ; close(sockfd), exit(1) ; } c_size = ntohl(c_size); if((wlen = write(sockfd, cookies, c_size)) <= 0) { printf("ERR: write cookies[wlen:%d]\n", wlen) ; close(sockfd), exit(1) ; } printf("SEND: COOKIES(%d)\n", c_size+sizeof(int)); if ((rlen = read(sockfd, &srh_out, sizeof(SRH_OUT))) <= 0) { printf("ERR: read SRH_OUT[rlen:%d]...\n", rlen) ; close(sockfd), exit(1) ; } printf("READ: SRH_OUT[rlen:%d]\n", rlen) ; srh_out.engVersion = ntohl(srh_out.engVersion) ; srh_out.mapVersion = ntohl(srh_out.mapVersion) ; srh_out.serviceId = ntohl(srh_out.serviceId) ; srh_out.resourceVersion = ntohl(srh_out.resourceVersion) ; srh_out.totalCount = ntohl(srh_out.totalCount) ; srh_out.count = ntohl(srh_out.count) ; srh_out.errorCode = ntohl(srh_out.errorCode) ; srh_out.compFlag = ntohl(srh_out.compFlag) ; srh_out.uncompSize = ntohl(srh_out.uncompSize) ; srh_out.compSize = ntohl(srh_out.compSize) ; printf("SRH_OUT-engVer[%d] mapVer[%d] SerId[%d] ResVer[%d] Total[%d] Cnt[%d] Err[%d] CompFlag[%d] UNCOM[%d] COM[%d]\n", srh_out.engVersion, srh_out.mapVersion, srh_out.serviceId, srh_out.resourceVersion, srh_out.totalCount, srh_out.count, srh_out.errorCode, srh_out.compFlag, srh_out.uncompSize, srh_out.compSize) ; if(srh_out.errorCode == 0) { printf("===OK!!! (DONE)===\n"); } exit_handler() ; }
int Worker(void) { int orig_sock; int clnt_len; int binderr; int sendbuf = 1; int stat; Sock_ID_IP *id_ip; pthread_t pthread_id; struct sockaddr_in serv_adr, clnt_adr; printLog(HEAD, "Now Init Socket..\n"); if((orig_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printLog(HEAD, "ERR: Set socket option error (%s)\n", strerror(errno)); exit_handler() ; } if(setsockopt(orig_sock, SOL_SOCKET, SO_REUSEADDR, (char *) &sendbuf, sizeof(sendbuf)) < 0) { printLog(HEAD, "ERR: Set socket option error (%s)\n", strerror(errno)); exit_handler() ; } memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family = AF_INET; serv_adr.sin_addr.s_addr = htonl(INADDR_ANY); serv_adr.sin_port = htons(Config.SERVICE_PORT); #ifdef _HPUX_SOURCE if((binderr = bind(orig_sock, reinterpret_cast <struct sockaddr *> (&serv_adr), sizeof(serv_adr))) < 0) { #else if((binderr = bind(orig_sock, (struct sockaddr *) & serv_adr, sizeof(serv_adr))) < 0) { #endif printLog(HEAD, "ERR: Bind Fail...(%s)\n", strerror(errno)) ; close(orig_sock); exit_handler() ; } printLog(HEAD, "Successfully Connect socket and now wailting.. \n"); if(listen(orig_sock, 10) < 0) { close(orig_sock) ; exit_handler() ; } clnt_len = sizeof(clnt_adr); while(1) { id_ip = (Sock_ID_IP *) malloc(sizeof(Sock_ID_IP)); #ifdef _HPUX_SOURCE if((id_ip->new_sock_id = accept(orig_sock, reinterpret_cast <struct sockaddr *> (&clnt_adr), &clnt_len)) < 0) { #elif _SUNOS_SOURCE if((id_ip->new_sock_id = accept(orig_sock, (struct sockaddr *) &clnt_adr, &clnt_len)) < 0) { #else // Solaris 7 or more... linux etc... if((id_ip->new_sock_id = accept(orig_sock, (struct sockaddr *) &clnt_adr, (socklen_t *) &clnt_len)) < 0) { #endif printLog(HEAD, "ERR: (%s)\n", strerror(errno)); printLog(HEAD, "ERR: Accept Error\n"); printLog(HEAD, "Program Terminated..\n"); close(orig_sock); exit_handler() ; } // For Debugging pthread_mutex_lock(&p_lock); thread_count++ ; pthread_mutex_unlock(&p_lock); sprintf(id_ip->ip_address, "%s", inet_ntoa(clnt_adr.sin_addr)); if((stat = pthread_create(&pthread_id, NULL, do_process, (void *)id_ip)) != 0) { printLog(HEAD, "ERR: (%s)(%d)\n", strerror(errno), errno); if(stat == EAGAIN) { printLog(HEAD, "ERR: not enough system resources to create a process for the new thread. (%d)(%d)\n", EAGAIN, stat); } close(orig_sock) ; exit_handler() ; } } return 1; }
int main(void) { REQUEST_HD hd; REQUEST_MULTI_CCTV hdc; RESPONSE_HD rd; int i, rlen, wlen, len; struct sockaddr_in serv_addr; int ret, ret_size = 0; char *info = NULL; char *data = NULL; char filename[256]; FILE *fp; FILE *cmd_line; char line[256]; char cmd[256]; int cnt = 0; char *fdata = NULL; short fnum = 0; short fclass = 0; int fsize = 0; long uncompsize = 0; char data_time[12+1]; char f_h; int f_e = 0, f_id = 0; int sendid = 0; ex_cctv ex_unit; memset(&hd, 0x00, sizeof(hd)); memset(&rd, 0x00, sizeof(rd)); memset(&hdc, 0x00, sizeof(hdc)); memset(cmd, 0x00, sizeof(cmd)); sprintf(cmd, "wc -l %s", EX_DAT_FILE); cmd_line = popen(cmd, "r"); memset(line, 0x00, sizeof(line)); ex_cctv_num = atoi(fgets(line, 256, cmd_line)); printf("---도로공사 CCTV 갯수 : %d\n", ex_cctv_num); pclose(cmd_line); exlist = (ex_cctv *)malloc(sizeof(ex_cctv) * ex_cctv_num); memset(exlist, 0x00, sizeof(ex_cctv) * ex_cctv_num); fp = fopen(EX_DAT_FILE, "r"); while(!feof(fp)) { memset(line, 0x00, sizeof(line)); fgets(line, 256, fp); ret = lineToValue(line, &exlist[cnt]); if (ret == 0) cnt++; } hd.version = htonl(100); hd.serviceid = htonl(2000); hdc.sourceFlag = 'D'; memset((char *) &serv_addr, 0, sizeof(serv_addr)) ; serv_addr.sin_family = AF_INET ; serv_addr.sin_addr.s_addr = inet_addr(SM_SERVER_IP) ; serv_addr.sin_port = htons(SM_SERVER_PORT) ; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("clientsoc: can't open stream socket") ; close(sockfd), exit(0); } if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printf("clientsoc: can't connect to server") ; close(sockfd), exit(0); } if ((wlen = write(sockfd, &hd, sizeof(hd))) <= 0) { printf("ERR: IN(wlen:%d)\n", wlen); close(sockfd), exit(1); } printf("SEND: IN[wlen:%d]\n", wlen); hdc.IDNum = htons(ex_cctv_num); if ((wlen = write(sockfd, &hdc, sizeof(hdc))) <= 0) { printf("ERR: IN(wlen:%d)\n", wlen); close(sockfd), exit(1); } for (i = 0; i < ex_cctv_num; i++) { printf("ID(%d)", exlist[i].id); sendid = htonl(exlist[i].id); if ((wlen = write(sockfd, &sendid, sizeof(int))) <= 0) { printf("ERR: IN(wlen:%d)\n", wlen); close(sockfd), exit(1); } } printf("\n"); printf(">>SEND: IDLIST\n"); if ((rlen = read(sockfd, &rd, sizeof(rd))) <= 0) { printf("ERR: OUT(rlen:%d)\n", rlen); close(sockfd), exit(1); } printf("RECEIVE: OUT[rlen:%d]\n", rlen); rd.error_code = ntohl(rd.error_code); rd.version = ntohl(rd.version); rd.serviceid = ntohl(rd.serviceid); rd.file_num = ntohl(rd.file_num); rd.comp_flag = ntohl(rd.comp_flag); rd.uncomp_size = ntohl(rd.uncomp_size); rd.comp_size = ntohl(rd.comp_size); printf("ECODE[%d] VER[%d] SID[%d] FNUM[%d] CFLAG[%d] UNC_SIZE[%d] C_SIZE[%d]\n", rd.error_code, rd.version, rd.serviceid, rd.file_num, rd.comp_flag, rd.uncomp_size, rd.comp_size); if (rd.error_code == 0) { if (rd.comp_flag == 0) ret_size = rd.uncomp_size; else ret_size = rd.comp_size; if ((info = (char *)malloc(rd.uncomp_size)) == NULL) { printf("ERR: Memory Alloc Fail\n"); close(sockfd), exit(1); } memset(info, 0, rd.uncomp_size); printf("---------------------start\n"); if ((rlen = readn(sockfd, info, ret_size)) <= 0) { printf("ERR: read info[rlen:%d/%d]\n", rlen, ret_size); close(sockfd), exit(1); } printf("READ: DATA[rlen:%d]\n", rlen); len = 0; memcpy(&fnum, info+len, sizeof(short)); len += sizeof(short); memcpy(&fclass, info+len, sizeof(short)); len += sizeof(short); fnum = ntohs(fnum); fclass = ntohs(fclass); printf("---- FILE_COUNT(%d) FCLASS(%d)\n", fnum, fclass); for (i = 0; i < fnum; i++) { memset(filename, 0x00, sizeof(filename)); memset(data_time, 0x00, sizeof(data_time)); memcpy(&f_h, info+len, sizeof(char)); len += sizeof(char); if (f_h != 'T') { printf("-------------ERROR!!!(%c)\n", f_h); exit(-1); } memcpy(&f_h, info+len, sizeof(char)); len += sizeof(char); if (f_h != 'W') { printf("-------------ERROR!!!(%c)\n", f_h); exit(-1); } memcpy(&f_e, info+len, sizeof(int)); len += sizeof(int); f_e = ntohl(f_e); memcpy(&f_id, info+len, sizeof(int)); len += sizeof(int); f_id = ntohl(f_id); memcpy(data_time, info+len, 12); len += 12; if (f_e != 0) { memset(&ex_unit, 0x00, sizeof(ex_unit)); memset(line, 0x00, sizeof(line)); ret = getcctvinfo(f_e, f_id, &ex_unit, line); printf("---ERR: ID(%d) NAME(%s) DIR(%s) EMSG(%s)\n", f_id, ex_unit.cctv_name, ex_unit.direction, line); } memcpy(&fsize, info+len, sizeof(int)); len += sizeof(int); fsize = ntohl(fsize); fdata = (char *)malloc(fsize); memset(fdata, 0x00, fsize); memcpy(fdata, info+len, fsize); len += fsize; sprintf(filename, "%d_cctv.jpg", f_id); fp = fopen(filename, "wb"); fwrite(fdata, fsize, 1, fp); fclose(fp); printf("Write Complete! ---- [%s](%d) (len:%d)\n", filename, fsize, len); free(fdata); } if (info != NULL) free(info); info = NULL; if (data != NULL) free(data); data = NULL; } exit_handler(); }
static void syscall_handler(struct intr_frame *f) { void *esp = f->esp; thread_current()->saved_esp = f->esp; // printf("$esp = %p\n",esp); byte_access_ok(esp,false); // hex_dump(esp, esp,16,true); // printf("\n"); int sys_call_num = *(int*) esp; esp += sizeof(int *); byte_access_ok(esp,false); // printf("$sys_call_num = %p\n",sys_call_num); char* argv[5]; switch (sys_call_num) { /* Projects 2 and later. */ //TODO: please retrieve parameters from the stack // and pass them to the handlers. case SYS_HALT: /* Halt the operating system. */ halt_handler(); break; case SYS_EXIT: /* Terminate this process. */ parse_arg(esp, 1, argv); exit_handler((int) argv[0]); break; case SYS_EXEC: /* Start another process. */ parse_arg(esp, 1, argv); f->eax=exec_handler((void*)argv[0]); break; case SYS_WAIT: /* Wait for a child process to die. */ parse_arg(esp, 1, argv); f->eax=wait_handler((int) argv[0]); break; case SYS_CREATE: /* Create a file. */ parse_arg(esp, 2, argv); f->eax=create_handler((void*)argv[0], (unsigned) argv[1]); break; case SYS_REMOVE: /* Delete a file. */ parse_arg(esp, 1, argv); f->eax=remove_handler((void*)argv[0]); break; case SYS_OPEN: /* Open a file. */ parse_arg(esp, 1, argv); f->eax=open_handler((void*)argv[0]); break; case SYS_FILESIZE: /* Obtain a file's size. */ parse_arg(esp, 1, argv); f->eax=filesize_handler((int) argv[0]); break; case SYS_READ: /* Read from a file. */ parse_arg(esp, 3, argv); f->eax=read_handler((int) argv[0], (void*) argv[1], (unsigned) argv[2]); break; case SYS_WRITE: /* Write to a file. */ parse_arg(esp, 3, argv); f->eax=write_handler((int) argv[0], (void*) argv[1], (unsigned) argv[2]); break; case SYS_SEEK: /* Change position in a file. */ parse_arg(esp, 2, argv); seek_handler((int) argv[0], (unsigned) argv[1]); break; case SYS_TELL: /* Report current position in a file. */ parse_arg(esp, 1, argv); f->eax=tell_handler((int) argv[0]); break; case SYS_CLOSE: /* Close a file. */ parse_arg(esp, 1, argv); close_handler((int) argv[0]); break; case SYS_MMAP: parse_arg(esp, 2, argv); f->eax=mmap_handler ((int) argv[0], (void*)argv[1]); break; case SYS_MUNMAP: parse_arg(esp, 1, argv); munmap_handler ((mapid_t) argv[0]); break; default: printf("system call %d not implemented!\n", sys_call_num); } //thread_exit(); }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif int seed = time(NULL); bool verifyexit = false; bool check_all_mods = false; // Set default file paths #ifdef PREFIX #define Q(STR) #STR #define QUOTE(STR) Q(STR) PATH_INFO::init_base_path(std::string(QUOTE(PREFIX))); #else PATH_INFO::init_base_path(""); #endif #if (defined USE_HOME_DIR || defined USE_XDG_DIR) PATH_INFO::init_user_dir(); #else PATH_INFO::init_user_dir("./"); #endif PATH_INFO::set_standard_filenames(); MAP_SHARING::setDefaults(); { const char *section_default = nullptr; const char *section_map_sharing = "Map sharing"; const char *section_user_directory = "User directories"; const arg_handler first_pass_arguments[] = { { "--seed", "<string of letters and or numbers>", "Sets the random number generator's seed value", section_default, [&seed](int num_args, const char **params) -> int { if (num_args < 1) return -1; const unsigned char *hash_input = (const unsigned char *) params[0]; seed = djb2_hash(hash_input); return 1; } }, { "--jsonverify", nullptr, "Checks the cdda json files", section_default, [&verifyexit](int, const char **) -> int { verifyexit = true; return 0; } }, { "--check-mods", nullptr, "Checks the json files belonging to cdda mods", section_default, [&check_all_mods](int, const char **) -> int { check_all_mods = true; return 0; } }, { "--basepath", "<path>", "Base path for all game data subdirectories", section_default, [](int num_args, const char **params) { if (num_args < 1) return -1; PATH_INFO::init_base_path(params[0]); PATH_INFO::set_standard_filenames(); return 1; } }, { "--shared", nullptr, "Activates the map-sharing mode", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setSharing(true); MAP_SHARING::setCompetitive(true); MAP_SHARING::setWorldmenu(false); return 0; } }, { "--username", "<name>", "Instructs map-sharing code to use this name for your character.", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::setUsername(params[0]); return 1; } }, { "--addadmin", "<username>", "Instructs map-sharing code to use this name for your character and give you " "access to the cheat functions.", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::addAdmin(params[0]); return 1; } }, { "--adddebugger", "<username>", "Informs map-sharing code that you're running inside a debugger", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::addDebugger(params[0]); return 1; } }, { "--competitive", nullptr, "Instructs map-sharing code to disable access to the in-game cheat functions", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setCompetitive(true); return 0; } }, { "--userdir", "<path>", "Base path for user-overrides to files from the ./data directory and named below", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::init_user_dir(params[0]); PATH_INFO::set_standard_filenames(); return 1; } } }; // The following arguments are dependent on one or more of the previous flags and are run // in a second pass. const arg_handler second_pass_arguments[] = { { "--worldmenu", nullptr, "Enables the world menu in the map-sharing code", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setWorldmenu(true); return true; } }, { "--datadir", "<directory name>", "Sub directory from which game data is loaded", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("datadir", params[0]); PATH_INFO::update_datadir(); return 1; } }, { "--savedir", "<directory name>", "Subdirectory for game saves", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("savedir", params[0]); return 1; } }, { "--configdir", "<directory name>", "Subdirectory for game configuration", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("config_dir", params[0]); PATH_INFO::update_config_dir(); return 1; } }, { "--memorialdir", "<directory name>", "Subdirectory for memorials", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("memorialdir", params[0]); return 1; } }, { "--optionfile", "<filename>", "Name of the options file within the configdir", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("options", params[0]); return 1; } }, { "--keymapfile", "<filename>", "Name of the keymap file within the configdir", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("keymap", params[0]); return 1; } }, { "--autopickupfile", "<filename>", "Name of the autopickup options file within the configdir", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("autopickup", params[0]); return 1; } }, { "--motdfile", "<filename>", "Name of the message of the day file within the motd directory", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("motd", params[0]); return 1; } }, }; // Process CLI arguments. const size_t num_first_pass_arguments = sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]); const size_t num_second_pass_arguments = sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]); int saved_argc = --argc; // skip program name const char **saved_argv = (const char **)++argv; while (argc) { if(!strcmp(argv[0], "--help")) { printHelpMessage(first_pass_arguments, num_first_pass_arguments, second_pass_arguments, num_second_pass_arguments); return 0; } else { bool arg_handled = false; for (size_t i = 0; i < num_first_pass_arguments; ++i) { auto &arg_handler = first_pass_arguments[i]; if (!strcmp(argv[0], arg_handler.flag)) { argc--; argv++; int args_consumed = arg_handler.handler(argc, (const char **)argv); if (args_consumed < 0) { printf("Failed parsing parameter '%s'\n", *(argv - 1)); exit(1); } argc -= args_consumed; argv += args_consumed; arg_handled = true; break; } } // Skip other options. if (!arg_handled) { --argc; ++argv; } } } while (saved_argc) { bool arg_handled = false; for (size_t i = 0; i < num_second_pass_arguments; ++i) { auto &arg_handler = second_pass_arguments[i]; if (!strcmp(saved_argv[0], arg_handler.flag)) { --saved_argc; ++saved_argv; int args_consumed = arg_handler.handler(saved_argc, saved_argv); if (args_consumed < 0) { printf("Failed parsing parameter '%s'\n", *(argv - 1)); exit(1); } saved_argc -= args_consumed; saved_argv += args_consumed; arg_handled = true; break; } } // Ingore unknown options. if (!arg_handled) { --saved_argc; ++saved_argv; } } } if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) { printf("Can't open or create %s. Check permissions.\n", FILENAMES["user_dir"].c_str()); exit(1); } setupDebug(); if (setlocale(LC_ALL, "") == NULL) { DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '')."; } // Options strings loaded with system locale get_options().init(); get_options().load(); set_language(true); if (initscr() == NULL) { // Initialize ncurses DebugLog( D_ERROR, DC_ALL ) << "initscr failed!"; return 1; } init_interface(); noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers #if !(defined TILES || defined _WIN32 || defined WINDOWS) // For tiles or windows, this is handled already in initscr(). init_colors(); #endif // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); g = new game; // First load and initialize everything that does not // depend on the mods. try { g->load_static_data(); if (verifyexit) { if(g->game_error()) { exit_handler(-999); } exit_handler(0); } if (check_all_mods) { // Here we load all the mods and check their // consistency (both is done in check_all_mod_data). g->init_ui(); popup_nowait("checking all mods"); g->check_all_mod_data(); if(g->game_error()) { exit_handler(-999); } // At this stage, the mods (and core game data) // are find and we could start playing, but this // is only for verifying that stage, so we exit. exit_handler(0); } } catch( const std::exception &err ) { debugmsg( "%s", err.what() ); exit_handler(-999); } // Now we do the actual game. g->init_ui(); if(g->game_error()) { exit_handler(-999); } curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif bool quit_game = false; do { if(!g->opening_screen()) { quit_game = true; } while (!quit_game && !g->do_turn()) ; if (g->game_quit() || g->game_error()) { quit_game = true; } } while (!quit_game); exit_handler(-999); return 0; }