static void read_ascii (FILE *fd, io_t *IO) { LINKED_LIST *ll_ann, *ll_with; bgp_attr_t *attr; int announce_flag = 0; int line_num = 0; int have_data = 0; int have_data2 = 0; time_t tstamp = 0; int type = 0; int subtype = 0; int bgptype = 0; int newtype = 0; gateway_t *gateway_from = NULL; gateway_t *gateway_to = NULL; int first = 1; u_char bgp_packet[BGPMAXPACKETSIZE], *bp = bgp_packet; u_char buffer[MAX_MSG_SIZE], *buffer_p = buffer; u_char *end = buffer + sizeof (buffer); int eof = 0; buffer_t *stdbuf; int state1 = 0, state2 = 0; int version = 0, as = 0, holdtime = 0, optlen = 0; u_long id = 0; int code = 0, subcode = 0; int viewno = 0; char *filename = NULL; prefix_t *route_prefix = NULL; time_t originated = 0; u_long status = 0; int seq_num = 0; attr = bgp_new_attr (PROTO_BGP); ll_ann = LL_Create (LL_DestroyFunction, Deref_Prefix, 0); ll_with = LL_Create (LL_DestroyFunction, Deref_Prefix, 0); stdbuf = New_Buffer_Stream (fd); for (;;) { char *line = NULL, *ret = NULL; int len = 0; int ok = 0; char *cp; if (buffer_gets (stdbuf) <= 0) { eof++; } else { len = buffer_data_len (stdbuf); line = buffer_data (stdbuf); if (line[len - 1] == '\n') { line[len - 1] = '\0'; len--; } trace (TR_TRACE, MRT->trace, "++%s\n", line); line_num++; if ((cp = strpbrk (line, "#!")) != NULL) { *cp = '\0'; len = cp - line; } if (first && nulline (line)) continue; first = 0; } if (eof || nulline (line)) { if (have_data && have_data2) { trace (TR_ERROR, MRT->trace, "Mixture of two formats\n"); goto error; } if (bgptype == BGP_UPDATE && have_data) { flushout (IO, tstamp, type, subtype, attr, ll_ann, ll_with, gateway_to); } else if (have_data2) { flushout2 (IO, tstamp, type, subtype, bgp_packet, bp - bgp_packet, gateway_from, gateway_to); } else if (bgptype == BGP_KEEPALIVE) { if (type == MSG_PROTOCOL_BGP4MP) { memset (bgp_packet, 0xff, BGP_HEADER_MARKER_LEN); BGP_PUT_HDRTYPE (bgptype, bgp_packet); bp = bgp_packet + BGP_HEADER_LEN; BGP_PUT_HDRLEN (bp - bgp_packet, bgp_packet); } else { bp = bgp_packet; } flushout2 (IO, tstamp, type, subtype, bgp_packet, bp - bgp_packet, gateway_from, gateway_to); } else if (bgptype == BGP_OPEN) { if (type == MSG_PROTOCOL_BGP4MP) { memset (bgp_packet, 0xff, BGP_HEADER_MARKER_LEN); BGP_PUT_HDRTYPE (bgptype, bgp_packet); bp = bgp_packet + BGP_HEADER_LEN; } else { bp = bgp_packet; } BGP_PUT_BYTE (version, bp); BGP_PUT_SHORT (as, bp); BGP_PUT_SHORT (holdtime, bp); BGP_PUT_NETLONG (id, bp); BGP_PUT_BYTE (0, bp); /* XXX */ if (type == MSG_PROTOCOL_BGP4MP) { BGP_PUT_HDRLEN (bp - bgp_packet, bgp_packet); } flushout2 (IO, tstamp, type, subtype, bgp_packet, bp - bgp_packet, gateway_from, gateway_to); } else if (bgptype == BGP_NOTIFY) { if (type == MSG_PROTOCOL_BGP4MP) { memset (bgp_packet, 0xff, BGP_HEADER_MARKER_LEN); BGP_PUT_HDRTYPE (bgptype, bgp_packet); bp = bgp_packet + BGP_HEADER_LEN; } else { bp = bgp_packet; } BGP_PUT_BYTE (code, bp); BGP_PUT_BYTE (subcode, bp); if (type == MSG_PROTOCOL_BGP4MP) { BGP_PUT_HDRLEN (bp - bgp_packet, bgp_packet); } flushout2 (IO, tstamp, type, subtype, bgp_packet, bp - bgp_packet, gateway_from, gateway_to); } else if (newtype == BGP4MP_STATE_CHANGE) { bp = bgp_packet; BGP_PUT_SHORT (state1, bp); BGP_PUT_SHORT (state2, bp); flushout2 (IO, tstamp, type, subtype, bgp_packet, bp - bgp_packet, gateway_from, NULL); } else if (newtype == BGP4MP_SNAPSHOT) { bp = bgp_packet; BGP_PUT_SHORT (viewno, bp); if (filename) BGP_PUT_DATA (filename, strlen (filename), bp); BGP_PUT_BYTE (0, bp); trace_mrt_header (MRT->trace, tstamp, type, subtype); io_write (IO, tstamp, type, subtype, bp - bgp_packet, bgp_packet); } else if (newtype == BGP4MP_ENTRY) { if (route_prefix != NULL) { buffer_p = bgp_table_dump_entry (buffer_p, end, type, subtype, viewno, route_prefix, status, originated, attr); } if (buffer_p - buffer > 0) { trace_mrt_header (MRT->trace, tstamp, type, subtype); io_write (IO, tstamp, type, subtype, buffer_p - buffer, buffer); } } if (eof) break; if (MRT->force_exit_flag) exit (1); bgp_deref_attr (attr); attr = bgp_new_attr (PROTO_BGP); LL_Clear (ll_ann); LL_Clear (ll_with); announce_flag = 0; have_data = 0; have_data2 = 0; tstamp = 0; type = 0; subtype = 0; bgptype = 0; newtype = 0; gateway_to = NULL; gateway_from = NULL; route_prefix = NULL; seq_num = 0; first = 1; if (filename) free (filename); filename = NULL; continue; } if (have_data) { /* a prefix -- line begins with a space */ if (isspace (line[0])) { prefix_t *prefix; char *cp = line +1; while (isspace (*cp)) cp++; if ((prefix = ascii2prefix (0, cp)) != NULL) { if (announce_flag == 1) { LL_Add (ll_ann, prefix); } else { LL_Add (ll_with, prefix); } continue; } } } if (have_data2) { prefix_t *prefix; int num; u_long value; if (isspace (line[0]) && strpbrk (line, ".:") && strchr (line, '/') && parse_line (line, "%d %m", &num, &prefix) == 2) { u_char *here = bp; /* v4 or v6 address with prefixlen */ #ifdef HAVE_IPV6 if (prefix->family == AF_INET6) BGP_PUT_PREFIX6 (prefix->bitlen, prefix_tochar (prefix), bp); else #endif /* HAVE_IPV6 */ BGP_PUT_PREFIX (prefix->bitlen, prefix_tochar (prefix), bp); Deref_Prefix (prefix); if (num != bp - here) { trace (TR_ERROR, MRT->trace, "length was %d but must be %d\n", num, bp - here); goto error; } continue; } else if (isspace (line[0]) && strpbrk (line, ".:") && parse_line (line, "%d %M", &num, &prefix) == 2) { /* v4 or v6 address w/o prefixlen */ if (prefix->family == AF_INET6 && num > 16) { trace (TR_ERROR, MRT->trace, "length was %d but must be less than or equal %d\n", num, 16); Deref_Prefix (prefix); goto error; } if (prefix->family == AF_INET && num > 4) { trace (TR_ERROR, MRT->trace, "length was %d but must be less than or equal %d\n", num, 4); Deref_Prefix (prefix); goto error; } BGP_PUT_DATA (prefix_tochar (prefix), num, bp); Deref_Prefix (prefix); continue; } else if (isspace (line[0]) && parse_line (line, "%d %i", &num, &value) == 2) { if (num == 1) BGP_PUT_BYTE (value, bp); else if (num == 2) BGP_PUT_SHORT (value, bp); else if (num == 4) BGP_PUT_LONG (value, bp); else { trace (TR_ERROR, MRT->trace, "unknown length %d\n", num); goto error; } continue; } } if ((ret = checkstradvance (line, "TIME"))) { struct tm tm; if (strptime (ret, "%D %T", &tm)) { time_t now; time (&now); tm.tm_isdst = localtime (&now)->tm_isdst; adjust_y2k (&tm); tstamp = mktime (&tm); } } else if ((ret = checkstradvance (line, "TO"))) { int as; char data[MAXLINE]; prefix_t *prefix; if (sscanf (ret, "%s AS%d", data, &as) >= 2 || sscanf (ret, "AS%d %s", &as, data) >= 2 /* obsolete */) { prefix = ascii2prefix (0, data); gateway_to = add_gateway (prefix, as, NULL); Deref_Prefix (prefix); } } else if ((ret = checkstradvance (line, "FROM"))) { int as; char data[MAXLINE]; if (sscanf (ret, "%s AS%d", data, &as) >= 2 || sscanf (ret, "AS%d %s", &as, data) >= 2 /* obsolete */) { prefix_t *prefix = ascii2prefix (0, data); gateway_from = add_gateway (prefix, as, NULL); attr->gateway = gateway_from; Deref_Prefix (prefix); } } /* type BGP/UPDATE */ else if ((ret = checkstradvance (line, "TYPE"))) { char *subtypestr; char **cpp; int i; if ((subtypestr = strchr (ret, '/')) != NULL) *subtypestr++ = '\0'; cpp = S_MRT_MSG_TYPES; for (i = 0; cpp[i]; i++) { if (strcasecmp (cpp[i], ret) == 0) break; } type = (enum MRT_MSG_TYPES) i; if (subtypestr) { char *subsubtypestr; if ((subsubtypestr = strchr (subtypestr, '/')) != NULL) *subsubtypestr++ = '\0'; if ((cpp = S_MRT_MSG_SUBTYPES[type]) != NULL) { for (i = 0; cpp[i]; i++) { if (strcasecmp (cpp[i], subtypestr) == 0) break; } subtype = i; } newtype = subtype; if (type == MSG_PROTOCOL_BGP || type == MSG_PROTOCOL_BGP4PLUS || type == MSG_PROTOCOL_BGP4PLUS_01) { if (subtype == MSG_BGP_UPDATE) { bgptype = BGP_UPDATE; newtype = BGP4MP_MESSAGE; } else if (subtype == MSG_BGP_KEEPALIVE) { bgptype = BGP_KEEPALIVE; newtype = BGP4MP_MESSAGE; } else if (subtype == MSG_BGP_NOTIFY) { bgptype = BGP_NOTIFY; newtype = BGP4MP_MESSAGE; } else if (subtype == MSG_BGP_OPEN) { bgptype = BGP_OPEN; newtype = BGP4MP_MESSAGE; } else if (subtype == MSG_BGP_SYNC) { newtype = BGP4MP_SNAPSHOT; } else if (subtype == MSG_BGP_STATE_CHANGE) { newtype = BGP4MP_STATE_CHANGE; } else if (subtype == MSG_TABLE_DUMP) { newtype = BGP4MP_ENTRY; } } else if (type == MSG_PROTOCOL_BGP4MP && ( subtype == BGP4MP_MESSAGE || subtype == BGP4MP_MESSAGE_OLD)) { for (i = 0; sbgp_pdus[i]; i++) { if (strcasecmp (sbgp_pdus[i], subsubtypestr) == 0) { bgptype = i; break; } } } } if (type == MSG_PROTOCOL_BGP || type == MSG_PROTOCOL_BGP4PLUS || type == MSG_PROTOCOL_BGP4PLUS_01 || type == MSG_TABLE_DUMP || type == MSG_PROTOCOL_BGP4MP ) { /* OK */ } else { trace (TR_ERROR, MRT->trace, "Unknown message type %s at line %d\n", ret, line_num); goto error; } } else if ((ret = checkstradvance (line, "DATA"))) { bp = bgp_packet; have_data2++; } else if (newtype == BGP4MP_STATE_CHANGE && (ret = checkstradvance (line, "PEER"))) { int as; char data[MAXLINE]; if (sscanf (ret, "%s AS%d", data, &as) >= 2 || sscanf (ret, "AS%d %s", &as, data) >= 2 /* obsolete */) { prefix_t *prefix = ascii2prefix (0, data); gateway_from = add_gateway (prefix, as, NULL); Deref_Prefix (prefix); } } else if (newtype == BGP4MP_STATE_CHANGE && (ret = checkstradvance (line, "STATE"))) { char *cp = strchr (ret, '/'); int i; if (cp == NULL) goto error; *cp++ = '\0'; for (i = 0; sbgp_states[i]; i++) { if (strcasecmp (sbgp_states[i], ret) == 0) { state1 = i; } } for (i = 0; sbgp_states[i]; i++) { if (strcasecmp (sbgp_states[i], cp) == 0) { state2 = i; } } } else if ((newtype == BGP4MP_SNAPSHOT || newtype == BGP4MP_ENTRY) && (ret = checkstradvance (line, "VIEW"))) { viewno = atoi (ret); } else if (newtype == BGP4MP_SNAPSHOT && (ret = checkstradvance (line, "FILE"))) { if (filename) free (filename); filename = strdup (ret); } else if (newtype == BGP4MP_ENTRY && (ret = checkstradvance (line, "PREFIX"))) { if (route_prefix == NULL) { buffer_p = buffer; if (type == MSG_TABLE_DUMP) { BGP_PUT_SHORT (viewno, buffer_p); BGP_PUT_SHORT (seq_num, buffer_p); } } else { buffer_p = bgp_table_dump_entry (buffer_p, end, type, subtype, viewno, route_prefix, status, originated, attr); } route_prefix = ascii2prefix (0, ret); bgp_deref_attr (attr); attr = bgp_new_attr (PROTO_BGP); } else if (newtype == BGP4MP_ENTRY && (ret = checkstradvance (line, "SEQUENCE"))) { seq_num = atoi (ret); } else if (newtype == BGP4MP_ENTRY && (ret = checkstradvance (line, "ORIGINATED"))) { struct tm tm; if (strptime (ret, "%D %T", &tm)) { time_t now; time (&now); tm.tm_isdst = localtime (&now)->tm_isdst; adjust_y2k (&tm); originated = mktime (&tm); } } else if (newtype == BGP4MP_ENTRY && (ret = checkstradvance (line, "STATUS"))) { sscanf (ret, "%li", &status); } else if (bgptype == BGP_OPEN && (ret = checkstradvance (line, "VERSION"))) { version = atoi (ret); } else if (bgptype == BGP_OPEN && (ret = checkstradvance (line, "AS"))) { as = atoi (ret); } else if (bgptype == BGP_OPEN && (ret = checkstradvance (line, "HOLD_TIME"))) { holdtime = atoi (ret); } else if (bgptype == BGP_OPEN && (ret = checkstradvance (line, "ID"))) { inet_pton (AF_INET, ret, &id); } else if (bgptype == BGP_OPEN && (ret = checkstradvance (line, "OPT_PARM_LEN"))) { optlen = atoi (ret); } else if (bgptype == BGP_NOTIFY && (ret = checkstradvance (line, "CODE"))) { char *cp; code = atoi (ret); if ((cp = strchr (ret, '/')) != NULL) subcode = atoi (cp + 1); } else if (bgptype == BGP_UPDATE && (ret = checkstradvance (line, "ANNOUNCE"))) { announce_flag = 1; have_data++; } else if (bgptype == BGP_UPDATE && (ret = checkstradvance (line, "WITHDRAW"))) { announce_flag = 0; have_data++; } else if ((bgptype == BGP_UPDATE || newtype == BGP4MP_ENTRY) && (ok = bgp_scan_attr (line, attr, MRT->trace)) > 0) { /* OK */ } else if ((bgptype == BGP_UPDATE || newtype == BGP4MP_ENTRY) && ok < 0) { trace (TR_ERROR, MRT->trace, "Invalid BGP attribute at line %d\n", line_num); goto error; } else { trace (TR_ERROR, MRT->trace, "Unrecognized line at %d\n", line_num); goto error; } } error: if (filename) free (filename); bgp_deref_attr (attr); LL_Destroy (ll_ann); LL_Destroy (ll_with); Delete_Buffer (stdbuf); }
void tetris(void) { char c, part_no; byte i, stop, start; show_splashscreen(); io_write(5, 42); io_write(6, 15); draw_playfield(); start_song(); start = 1; while (1) { if (start) { next_part_no = rand() % 7; lines = 0; curr_y = 10; remove_complete_lines(); clear_next_part(); while (io_read(128) != 255); do { vputs(95, 65, "GET READY"); buf2screen(); delay_ms(300); vputs(95, 65, " "); buf2screen(); delay_ms(300); } while (io_read(128) == 255); start = 0; } stop = 0; curr_x = 5; curr_y = 1; clear_next_part(); part_no = next_part_no; next_part_no = rand() % 7; draw_next_part(); select_part(part_no); draw_curr_part(); buf2screen(); while (!stop) { for (i = 0; i < 20 && !stop; i++) { if (lines < 20) delay_ms(35); else if (lines < 50) delay_ms(25); else if (lines < 70) delay_ms(18); else if (lines < 100) delay_ms(12); else delay_ms(8); if (!stop) { c = io_read(128); if (c == ' ') { // rotate part rotate_curr_part(); buf2screen(); } else if (c == 0) { // left, right, down c = io_read(128); if (c == 75) { // left move_left(); buf2screen(); } else if (c == 77) { // right move_right(); buf2screen(); } else if (c == 80) { // down while (!move_down()) buf2screen(); buf2screen(); stop = 1; } } else if (c == 27) return; } // if (!stop) } if (!stop) { stop = move_down(); buf2screen(); } } remove_complete_lines(); if (curr_y <= 2) { clear_playfield(); vputs(95, 65, "GAME OVER"); buf2screen(); getchar(); vputs(95, 65, " "); start = 1; } } }
static void Output_write(Output* output, Buffer** buffer, Error* error) { Pager* pager = (Pager*) output->arg; if (pager->fd == IO_INVALID_FD) { if (buffer_input(pager, buffer, error)) { return; } Array argv; init_argv(&argv, pager->options, error); if (ERROR_HAS(error)) { return; } int read_write_fds[2]; if (pipe(read_write_fds) == -1) { Error_add(error, strerror(errno)); Array_deinit(&argv); return; } // FIXME: reuse fork_exec_fd? int child_pid = fork(); if (child_pid == -1) { Error_add(error, strerror(errno)); Array_deinit(&argv); return; } else if (child_pid) { // FIXME: cleanup fork if (dup2(read_write_fds[0], STDIN_FILENO) == -1) { Error_add(error, strerror(errno)); Array_deinit(&argv); return; } close(read_write_fds[0]); close(read_write_fds[1]); execvp((char*) argv.data[0], (char**) argv.data); // FIXME: cleanup fork Error_add(error, strerror(errno)); Array_deinit(&argv); return; } Array_deinit(&argv); close(read_write_fds[0]); flush_buffer(pager, read_write_fds[1], error); // FIXME: cleanup fork if (ERROR_HAS(error)) { return; } } io_write(pager->fd, *buffer, error); (*buffer)->length = 0; }
PDBfile * lite_PD_create (char *name) { char str[MAXLINE]; PDBfile *file; static FILE *fp; file = NULL; switch (setjmp(_lite_PD_create_err)) { case ABORT: io_close(fp); return(NULL); case ERR_FREE: return(file); default: memset(lite_PD_err, 0, MAXLINE); break; } /* * Open the file. */ strcpy(str, name); fp = io_open(str, BINARY_MODE_WPLUS); if (!fp) lite_PD_error("CAN'T CREATE FILE - PD_CREATE", PD_CREATE); if (lite_PD_buffer_size != -1) { if (io_setvbuf(fp, NULL, _IOFBF, (size_t) lite_PD_buffer_size)) { lite_PD_error("CAN'T SET FILE BUFFER - PD_CREATE", PD_OPEN); } } /* * Make the PDBfile. */ file = _lite_PD_mk_pdb(str); if (file == NULL) { lite_PD_error("CAN'T ALLOCATE PDBFILE - PD_CREATE", PD_OPEN); } file->stream = fp; file->mode = PD_CREATE; /* * Set the file data conversion standard - and yes someone might pick * a target standard which is the current standard */ file->std = _lite_PD_copy_standard(file->host_std); file->align = _lite_PD_copy_alignment(file->host_align); if (lite_REQ_STANDARD != NULL) { if (!_lite_PD_compare_std(lite_REQ_STANDARD, file->std, lite_REQ_ALIGNMENT, file->align)) { _lite_PD_rl_standard(file->std); file->std = _lite_PD_copy_standard(lite_REQ_STANDARD); _lite_PD_rl_alignment(file->align); file->align = _lite_PD_copy_alignment(lite_REQ_ALIGNMENT); } lite_REQ_STANDARD = NULL; } /* * Write the ASCII header. */ io_printf(fp, "%s\n", HeadTok); if (io_flush(fp)) { lite_PD_error("FFLUSH FAILED BEFORE HEADER - PD_CREATE", PD_CREATE); } /* * Write the primitive data type formats. */ if (!_lite_PD_wr_format(file)) { lite_PD_error("FAILED TO WRITE FORMATS - PD_CREATE", PD_CREATE); } /* * Record the current file position as the location of the symbol table * address and sequentially the chart address */ if ((file->headaddr = io_tell(fp)) == -1L) { lite_PD_error("CAN'T FIND HEADER ADDRESS - PD_CREATE", PD_CREATE); } /* * Initialize the pdb system defs and structure chart. */ _lite_PD_init_chrt(file); if (io_flush(fp)) { lite_PD_error("FFLUSH FAILED AFTER HEADER - PD_CREATE", PD_CREATE); } memset(str, 0, PAD_SIZE); if (io_write(str, (size_t) 1, PAD_SIZE, fp) != PAD_SIZE) { lite_PD_error("FAILED TO PAD FILE FOR MPW - PD_CREATE", PD_CREATE); } file->chrtaddr = file->headaddr + 128L; if (io_seek(fp, file->chrtaddr, SEEK_SET)) { lite_PD_error("FAILED TO FIND START OF DATA - PD_CREATE", PD_CREATE); } file->system_version = PDB_SYSTEM_VERSION; file->date = lite_SC_date(); return(file); }
void CMain::JSONUpdateThread(void *pUser) { CJSONUpdateThreadData *m_pJSONUpdateThreadData = (CJSONUpdateThreadData *)pUser; CClient *pClients = m_pJSONUpdateThreadData->pClients; CConfig *pConfig = m_pJSONUpdateThreadData->pConfig; while(gs_Running) { char aFileBuf[2048*NET_MAX_CLIENTS]; char *pBuf = aFileBuf; str_format(pBuf, sizeof(aFileBuf), "{\n\"servers\": [\n"); pBuf += strlen(pBuf); for(int i = 0; i < NET_MAX_CLIENTS; i++) { if(!pClients[i].m_Active || pClients[i].m_Disabled) continue; if(pClients[i].m_Connected) { // Connectivity bool Online4; bool Online6; Online4 = pClients[i].m_Stats.m_Online4; Online6 = pClients[i].m_Stats.m_Online6; // Uptime char aUptime[16]; int Days = pClients[i].m_Stats.m_Uptime/60.0/60.0/24.0; if(Days > 0) { if(Days > 1) str_format(aUptime, sizeof(aUptime), "%d days", Days); else str_format(aUptime, sizeof(aUptime), "%d day", Days); } else str_format(aUptime, sizeof(aUptime), "%02d:%02d:%02d", (int)(pClients[i].m_Stats.m_Uptime/60.0/60.0), (int)((pClients[i].m_Stats.m_Uptime/60)%60), (int)((pClients[i].m_Stats.m_Uptime)%60)); // Load float Load = pClients[i].m_Stats.m_Load; // CPU int CPU = pClients[i].m_Stats.m_CPU; // Memory int Memory; if(pClients[i].m_Stats.m_MemTotal) Memory = round(((float)pClients[i].m_Stats.m_MemUsed/pClients[i].m_Stats.m_MemTotal)*100.0); else Memory = 0; // HDD int HDD; if(pClients[i].m_Stats.m_HDDTotal) HDD = round(((float)pClients[i].m_Stats.m_HDDUsed/pClients[i].m_Stats.m_HDDTotal)*100.0); else HDD = 0; str_format(pBuf, sizeof(aFileBuf) - (pBuf - aFileBuf), "{ \"name\": \"%s\", \"type\": \"%s\", \"host\": \"%s\", \"location\": \"%s\", \"online4\": %s, \"online6\": %s, \"uptime\": \"%s\", \"load\": \"%.2f\", \"network_rx\": %d, \"network_tx\": %d, \"cpu\": %d, \"memory\": %d, \"memory_total\": %" PRId64 ", \"memory_used\": %" PRId64 ", \"hdd\": %d, \"hdd_total\": %" PRId64 ", \"hdd_used\": %" PRId64 " },\n", pClients[i].m_aName, pClients[i].m_aType, pClients[i].m_aHost, pClients[i].m_aLocation, Online4 ? "true" : "false", Online6 ? "true" : "false", aUptime, Load, pClients[i].m_Stats.m_NetworkRx, pClients[i].m_Stats.m_NetworkTx, CPU, Memory, pClients[i].m_Stats.m_MemTotal, pClients[i].m_Stats.m_MemUsed, HDD, pClients[i].m_Stats.m_HDDTotal, pClients[i].m_Stats.m_HDDUsed); pBuf += strlen(pBuf); } else { str_format(pBuf, sizeof(aFileBuf) - (pBuf - aFileBuf), "{ \"name\": \"%s\", \"type\": \"%s\", \"host\": \"%s\", \"location\": \"%s\", \"online4\": false, \"online6\": false },\n", pClients[i].m_aName, pClients[i].m_aType, pClients[i].m_aHost, pClients[i].m_aLocation); pBuf += strlen(pBuf); } } if(!m_pJSONUpdateThreadData->m_ReloadRequired) str_format(pBuf - 2, sizeof(aFileBuf) - (pBuf - aFileBuf), "\n],\n\"updated\": \"%lld\"\n}", (long long)time(/*ago*/0)); else { str_format(pBuf - 2, sizeof(aFileBuf) - (pBuf - aFileBuf), "\n],\n\"updated\": \"%lld\",\n\"reload\": true\n}", (long long)time(/*ago*/0)); m_pJSONUpdateThreadData->m_ReloadRequired--; } pBuf += strlen(pBuf); char aJSONFileTmp[1024]; str_format(aJSONFileTmp, sizeof(aJSONFileTmp), "%s~", pConfig->m_aJSONFile); IOHANDLE File = io_open(aJSONFileTmp, IOFLAG_WRITE); if(!File) { dbg_msg("main", "Couldn't open %s", aJSONFileTmp); exit(1); } io_write(File, aFileBuf, (pBuf - aFileBuf)); io_flush(File); io_close(File); fs_rename(aJSONFileTmp, pConfig->m_aJSONFile); thread_sleep(1000); } fs_remove(pConfig->m_aJSONFile); }
int main(int argc, char** argv) { pwr_tStatus sts; io_tCtx io_ctx; float ctime = 1; pwr_sClass_EplHandler* plhp; pwr_tOid oid; int tmo; char mp[2000]; qcom_sGet get; qcom_sQattr qAttr; qcom_sQid qini; qcom_sQid qid = qcom_cNQid; if (argc > 1) { if (streq(argv[1], "-m")) { io_methods_print(); exit(0); } if (streq(argv[1], "-h")) { usage(); exit(0); } } // Make connection to error handler errh_Init("pwr_powerlink", errh_eAnix_powerlink); errh_SetStatus(PWR__SRVSTARTUP); if (!qcom_Init(&sts, 0, "pwr_powerlink")) { errh_Fatal("qcom_Init, %m", sts); exit(sts); } qAttr.type = qcom_eQtype_private; qAttr.quota = 100; if (!qcom_CreateQ(&sts, &qid, &qAttr, "events")) { errh_Fatal("qcom_CreateQ, %m", sts); exit(sts); } qini = qcom_cQini; if (!qcom_Bind(&sts, &qid, &qini)) { errh_Fatal("qcom_Bind(Qini), %m", sts); exit(-1); } // Make connection to realtime database sts = gdh_Init("rt_powerlink"); if (EVEN(sts)) { errh_Fatal("rt_powerlink aborted, gdh_Init failed\n%m", sts); errh_SetStatus(PWR__SRVTERM); exit(sts); } sts = gdh_GetClassList(pwr_cClass_Epl_CNServer, &oid); if (ODD(sts)) { system("rt_powerlink_cn &"); exit(0); } // Get Powerlink handler object sts = io_get_plhandler_object(&plhp, &oid); if (EVEN(sts)) { errh_SetStatus(0); errh_Info("rt_powerlink terminated, no EplHandler object found"); exit(sts); } // Create context and call init functions of all agent, // rack and cardobjects sts = io_init(io_mProcess_Powerlink, pwr_cNObjid, &io_ctx, 1, ctime); if (EVEN(sts)) { errh_SetStatus(PWR__SRVTERM); errh_Fatal("rt_powerlink aborted, io_init() failed\n%m", sts); exit(sts); } tmo = (plhp->CycleTime) * 1000; aproc_TimeStamp(plhp->CycleTime, 5.0); errh_SetStatus(PWR__SRUN); aproc_RegisterObject(oid); // Call IoAgentRead() IoAgentWrite() IoCardRead() IoCardWrite() // IoModuleRead() IoModuleWrite() forever for (;;) { get.maxSize = sizeof(mp); get.data = mp; qcom_Get(&sts, &qid, &get, tmo); if (sts == QCOM__TMO || sts == QCOM__QEMPTY) { sts = io_read(io_ctx); sts = io_write(io_ctx); aproc_TimeStamp(plhp->CycleTime, 5.0); } else { ini_mEvent new_event; qcom_sEvent* ep = (qcom_sEvent*)get.data; new_event.m = ep->mask; if (new_event.b.oldPlcStop) { // TODO } else if (new_event.b.swapDone) { // TODO } else if (new_event.b.terminate) { // io_close(io_ctx); exit(0); } } } }
int main(int argc, char * argv[]) { int i; int read_write_error; int input_stat[2] = {0}; int output_stat[2] = {0}; int flags = 0; int count = -1; int skip = 0, seek = 0; int bs = -1, ibs = 4096, obs = 4096; int buffer_size = 0; int count_read, count_write; time_t time_start, time_finish, time_use; const char * input_path = "-"; const char * output_path = "-"; const char * input_device = NULL; const char * output_device = NULL; struct io_base *input_handle, *output_handle; char * buffer_read, * buffer_write, * buffer_alloc; for (i = 1; i < argc; i++) { char * argline = argv[i]; char * optvalue = getoptvalue(argv[i]); ARG_INT(&ibs, 1, "ibs="); ARG_INT(&obs, 2, "obs="); ARG_INT(&bs, (1 | 2), "bs="); ARG_INT(&seek, 4, "seek="); ARG_INT(&skip, 8, "skip="); ARG_INT(&count, 16, "count="); ARG_STRING(&input_path, 32, "if="); ARG_STRING(&output_path, 64, "of="); ARG_STRING(&input_device, 128, "kin="); ARG_STRING(&output_device, 256, "kout="); fprintf(stderr, "unkown operand %s", argline); exit(-1); } if (bs != -1) { ibs = bs; obs = bs; } valid_size("invalid input block size", ibs); valid_size("invalid output block size", obs); input_handle = open_file(input_path, GENERIC_READ); valid_handle("invalid input handle", input_handle); output_handle = open_file(output_path, GENERIC_WRITE); valid_handle("invalid output handle", output_handle); buffer_size = (ibs < obs? obs: ibs) * 2; buffer_alloc = (char *)malloc(buffer_size); valid_buffer("alloc buffer fail", buffer_alloc); if (seek > 0) { off_t posnew = seek * (off_t)(obs); off_t poscur = io_lseek(output_handle, posnew, SEEK_CUR); valid_size("seek output file fail", posnew == poscur); } if (skip > 0) { off_t posnew = skip * (off_t)(ibs); off_t poscur = io_lseek(output_handle, posnew, SEEK_CUR); valid_size("skip input file fail", posnew == poscur); } read_write_error = 0; count_read = count_write = 0; buffer_read = buffer_write = buffer_alloc; time_start = time(NULL); while (read_write_error == 0) { size_t transfer = 0; while (buffer_read < buffer_alloc + obs) { if (!io_read(input_handle, buffer_read, ibs, &transfer)) { read_write_error = 2; break; } if (transfer == 0) { read_write_error = 1; break; } buffer_read += transfer; count_read += transfer; input_stat[transfer == ibs]++; if (input_stat[0] + input_stat[1] == count) { read_write_error = 1; break; } } while (buffer_write + obs <= buffer_read) { if (!io_write(output_handle, buffer_write, obs, &transfer)) { read_write_error = 2; break; } if (transfer == 0) { read_write_error = 2; break; } output_stat[transfer == obs]++; buffer_write += transfer; count_write += transfer; } memmove(buffer_alloc, buffer_write, count_read - count_write); buffer_read = buffer_alloc + (count_read - count_write); buffer_write = buffer_alloc; } while (read_write_error == 1 && count_write < count_read) { size_t transfer = (count_read - count_write); valid_size("internal error", transfer < obs); if (io_write(output_handle, buffer_write, transfer, &transfer)) { output_stat[transfer == obs]++; buffer_write += transfer; count_write += transfer; continue; } if (io_write(output_handle, buffer_write, obs, &transfer)) { output_stat[transfer == obs]++; buffer_write += transfer; count_write += transfer; continue; } read_write_error = 3; break; } time_finish = time(NULL); io_close(output_handle); io_close(input_handle); free(buffer_alloc); time_use = time_finish > time_start? time_finish - time_start: 1; fprintf(stderr, "%d+%d records in\n", input_stat[1], input_stat[0]); fprintf(stderr, "%d+%d records out\n", output_stat[1], output_stat[0]); fprintf(stderr, "%d bytes transferred in %ld secs (%ld bytes/sec)\n", count_read, time_use, count_read / time_use); return 0; }
/** Writes a null-terminated string (eg. a string literal) */ void serial_write_const(const char * string) { io_write(io, (uint8_t *) string, strlen(string)); }
int main (int argc, char **argv) { pwr_tStatus sts = 1; io_tCtx io_ctx; io_tCtx io_ctx_swap; pwr_sClass_IOHandler *ihp; int swap_io; int close_io; int init_io; qcom_sQid qid = qcom_cNQid; int tmo; char mp[2000]; qcom_sGet get; pwr_tTime now; pwr_tTime next; pwr_tTime after; pwr_tDeltaTime cycle; lst_sEntry *csup_lh; int delay_action = 0; pwr_sNode *nodep; pwr_tBoolean old_emergency_break = 0; if ( argc > 1) { if ( strcmp( argv[1], "-m") == 0) { io_methods_print(); exit(0); } if ( strcmp( argv[1], "-h") == 0) { usage(); exit(0); } } ihp = init(&qid, &csup_lh, &nodep); plc_UtlWaitForPlc(); /* Prepare the swap context */ sts = io_init_swap(io_mProcess_IoComm, pwr_cNObjid, &io_ctx_swap, 1, ihp->CycleTimeBus); for (close_io = swap_io = 0, init_io = 1;;) { if (init_io) { double f; sts = io_init(io_mProcess_IoComm, pwr_cNObjid, &io_ctx, 1, ihp->CycleTimeBus); if ( ODD(sts)) errh_SetStatus( PWR__SRUN); #if defined(OS_ELN) ker$clear_event( &sts, io_comm_terminate); io_dioc_init(); io_dioc_start(); #endif init_io = 0; tmo = ihp->CycleTimeBus * 1000.; f = floor(ihp->CycleTimeBus); cycle.tv_sec = f; cycle.tv_nsec = (ihp->CycleTimeBus - f) * 1.0e9; cycle.tv_nsec++; time_GetTimeMonotonic(&next); time_Aadd(NULL, &next, &cycle); } get.maxSize = sizeof(mp); get.data = mp; qcom_Get(&sts,&qid, &get, tmo); if (sts == QCOM__TMO || sts == QCOM__QEMPTY) { if ( nodep->EmergBreakTrue && !old_emergency_break) sts = io_swap(io_ctx_swap, io_eEvent_IoCommEmergencyBreak); sts = io_read(io_ctx); if (EVEN(sts)) { ihp->IOReadWriteFlag = FALSE; errh_Error("IO read, %m", sts); } sts = io_write(io_ctx); if (EVEN(sts)) { ihp->IOReadWriteFlag = FALSE; errh_Error("IO write, %m", sts); } if ( nodep->EmergBreakTrue && !old_emergency_break) sts = io_swap(io_ctx, io_eEvent_EmergencyBreak); old_emergency_break = nodep->EmergBreakTrue; if (swap_io) { sts = io_swap(io_ctx_swap, io_eEvent_IoCommSwap); } io_ScanSupLst( io_ctx->SupCtx); time_GetTime(&now); time_GetTimeMonotonic(&after); next = after; time_Aadd(NULL, &next, &cycle); delay_action = csup_Exec(&sts, csup_lh, (pwr_tDeltaTime *) &next, (pwr_tDeltaTime *) &after, &now); if (delay_action == 2) ihp->IOReadWriteFlag = FALSE; aproc_TimeStamp(ihp->CycleTimeBus, 5); } else { ini_mEvent new_event; qcom_sEvent *ep = (qcom_sEvent*) get.data; new_event.m = ep->mask; if (new_event.b.oldPlcStop && !swap_io) { swap_io = 1; close_io = 1; errh_SetStatus(PWR__SRVRESTART); } else if (new_event.b.swapDone && swap_io) { swap_io = 0; init_io = 1; } else if (new_event.b.terminate) { exit(0); } if (close_io) { io_close(io_ctx); #if defined(OS_ELN) ker$signal( &sts, io_comm_terminate); #endif close_io = 0; } } } }
int deliver_imap_deliver(struct deliver_ctx *dctx, struct actitem *ti) { struct account *a = dctx->account; struct mail *m = dctx->mail; struct deliver_imap_data *data = ti->data; struct io *io; struct fetch_ctx fctx; struct fetch_imap_data fdata; char *cause, *folder, *ptr, *line; size_t len, maillen; u_int total, body; /* Connect to the IMAP server. */ io = connectproxy(&data->server, conf.verify_certs, conf.proxy, IO_CRLF, conf.timeout, &cause); if (io == NULL) { log_warnx("%s: %s", a->name, cause); xfree(cause); return (DELIVER_FAILURE); } if (conf.debug > 3 && !conf.syslog) io->dup_fd = STDOUT_FILENO; /* Work out the folder name. */ folder = replacestr(&data->folder, m->tags, m, &m->rml); if (folder == NULL || *folder == '\0') { log_warnx("%s: empty folder", a->name); goto error; } /* Fake up the fetch context for the fetch code. */ memset(&fdata, 0, sizeof fdata); fdata.user = data->user; fdata.pass = data->pass; fdata.nocrammd5 = data->nocrammd5; fdata.nologin = data->nologin; memcpy(&fdata.server, &data->server, sizeof fdata.server); fdata.io = io; fdata.only = FETCH_ONLY_ALL; a->data = &fdata; fetch_imap_state_init(a, &fctx); fctx.state = imap_state_connected; fctx.llen = IO_LINESIZE; fctx.lbuf = xmalloc(fctx.llen); /* Use the fetch code until the select1 state is reached. */ if (deliver_imap_pollto(imap_state_select1, a, io, &fctx) != 0) goto error; retry: /* Send an append command. */ if (imap_putln(a, "%u APPEND {%zu}", ++fdata.tag, strlen(folder)) != 0) goto error; switch (deliver_imap_waitappend(a, &fctx, io, &line)) { case IMAP_TAG_ERROR: if (line != NULL) imap_invalid(a, line); goto error; case IMAP_TAG_CONTINUE: break; default: if (imap_no(line) && strstr(line, "[TRYCREATE]") != NULL) goto try_create; imap_invalid(a, line); goto error; } /* * Send the mail size, not forgetting lines are CRLF terminated. The * Google IMAP server is written strangely, so send the size as if * every CRLF was a CR if the server has XYZZY. */ count_lines(m, &total, &body); maillen = m->size + total - 1; if (fdata.capa & IMAP_CAPA_XYZZY) { log_debug2("%s: adjusting size: actual %zu", a->name, maillen); maillen = m->size; } if (fdata.capa & IMAP_CAPA_NOSPACE) { if (imap_putln(a, "%s{%zu}", folder, maillen) != 0) goto error; } else { if (imap_putln(a, "%s {%zu}", folder, maillen) != 0) goto error; } switch (deliver_imap_waitappend(a, &fctx, io, &line)) { case IMAP_TAG_ERROR: if (line != NULL) imap_invalid(a, line); goto error; case IMAP_TAG_CONTINUE: break; default: if (imap_no(line) && strstr(line, "[TRYCREATE]") != NULL) goto try_create; imap_invalid(a, line); goto error; } /* Send the mail data. */ line_init(m, &ptr, &len); while (ptr != NULL) { if (len > 1) io_write(io, ptr, len - 1); io_writeline(io, NULL); /* Update if necessary. */ if (io_update(io, conf.timeout, &cause) != 1) { log_warnx("%s: %s", a->name, cause); xfree(cause); goto error; } line_next(m, &ptr, &len); } /* Wait for an okay from the server. */ switch (deliver_imap_waitappend(a, &fctx, io, &line)) { case IMAP_TAG_ERROR: case IMAP_TAG_CONTINUE: if (line != NULL) imap_invalid(a, line); goto error; default: if (imap_okay(line)) break; if (strstr(line, "[TRYCREATE]") != NULL) goto try_create; imap_invalid(a, line); goto error; } xfree(fctx.lbuf); xfree(folder); if (imap_putln(a, "%u LOGOUT", ++fdata.tag) != 0) goto error; if (deliver_imap_waitokay(a, &fctx, io, &line) != 0) goto error; fdata.disconnect(a); return (DELIVER_SUCCESS); try_create: /* XXX function? */ /* Try to create the folder. */ if (imap_putln(a, "%u CREATE {%zu}", ++fdata.tag, strlen(folder)) != 0) goto error; if (deliver_imap_waitcontinue(a, &fctx, io, &line) != 0) goto error; if (imap_putln(a, "%s", folder) != 0) goto error; if (deliver_imap_waitokay(a, &fctx, io, &line) != 0) goto error; goto retry; error: io_writeline(io, "QUIT"); io_flush(io, conf.timeout, NULL); xfree(fctx.lbuf); if (folder != NULL) xfree(folder); fdata.disconnect(a); return (DELIVER_FAILURE); }
// TODO: Ugly but works bool CUpdater::GetFile(const char *url, const char *path) { NETSOCKET Socket = invalid_socket; NETADDR HostAddress, BindAddr; mem_zero(&HostAddress, sizeof(HostAddress)); mem_zero(&BindAddr, sizeof(BindAddr)); char aNetBuff[1024]; //Lookup if(net_host_lookup(UPDATES_HOST, &HostAddress, NETTYPE_IPV4) != 0) { dbg_msg("autoupdate", "Error running host lookup"); return false; } HostAddress.port = 80; //Connect BindAddr.type = NETTYPE_IPV4; Socket = net_tcp_create(BindAddr); if(net_tcp_connect(Socket, &HostAddress) != 0) { net_tcp_close(Socket); dbg_msg("autoupdate","Error connecting to host"); return false; } //Send request str_format(aNetBuff, sizeof(aNetBuff), "GET "UPDATES_BASE_PATH"%s HTTP/1.0\r\nHost: "UPDATES_HOST"\r\n\r\n", url); net_tcp_send(Socket, aNetBuff, str_length(aNetBuff)); //read data IOHANDLE dstFile = 0; std::string NetData; int TotalRecv = 0, TotalBytes = 0, CurrentRecv = 0, enterCtrl = 0; bool isHead = true, isStatusLine = true; while ((CurrentRecv = net_tcp_recv(Socket, aNetBuff, sizeof(aNetBuff))) > 0) { for (int i=0; i<CurrentRecv ; i++) { if (isHead) { if (aNetBuff[i]=='\n') { if (++enterCtrl == 2) // Go To Body Part { dstFile = io_open(path, IOFLAG_WRITE); if (!dstFile) { net_tcp_close(Socket); dbg_msg("autoupdate","Error writing to disk"); return false; } str_copy(m_CurrentDownloadFileName, url, sizeof(m_CurrentDownloadFileName)); isHead = false; NetData.clear(); continue; } std::transform(NetData.begin(), NetData.end(), NetData.begin(), ::tolower); // Check Status if (isStatusLine) { bool isCodeOk = NetData.find("200") != std::string::npos; bool isStatusOk = NetData.find("ok") != std::string::npos; if (!isCodeOk || !isStatusOk) { net_tcp_close(Socket); dbg_msg("autoupdate","Server Host returns error code"); return false; } } isStatusLine = false; // Get File Size std::size_t fpos = std::string::npos; if ((fpos=NetData.find("content-length:")) != std::string::npos) sscanf(NetData.substr(fpos+15).c_str(), "%d", &TotalBytes); NetData.clear(); continue; } else if (aNetBuff[i]!='\r') enterCtrl=0; NetData+=aNetBuff[i]; } else // Body Part { if (TotalBytes <= 0) { io_close(dstFile); net_tcp_close(Socket); dbg_msg("autoupdate","Error receiving file"); return false; } m_CurrentDownloadProgress = (float)TotalRecv/(float)TotalBytes; io_write(dstFile, &aNetBuff[i], 1); TotalRecv++; if (TotalRecv == TotalBytes) break; } } } //Finish io_close(dstFile); net_tcp_close(Socket); return true; }
int main(int argc, char **argv){ reflowctrl_init(); if(argc == 1 ){ io_read(); } else { // write to device int c; c = getopt_long (argc, argv, "p:t:c:s", long_options, &option_index); send->direction = 1; send->pre_heat = 0; send->set_temp = 0; send->reached_temp = 0; send->is_locked = 0; send->is_cooling = 0; send->is_heating = 0; send->check = 0; while (c != -1){ switch (c) { case 'p': send->pre_heat = 1; double_t p = atoi(optarg); send->temperature = p; send->set_temp = 1; printf("Initialize pre heat phase to %.2f°C. \n", send->temperature); break; case 't': send->temperature = 0; // first line bevore declaration. (dummy) double_t t; t = atoi(optarg); if(t > 655){ fprintf(stderr, "Temperature limit is 655°C.\n"); exit(1); } send->temperature = t; send->set_temp = 1; printf("Set temperature to %.2f \n", send->temperature ); break; case 's': send->temperature = 0; // first line bevore declaration. (dummy) send->temperature = t; send->set_temp = 1; send->is_cooling = 1; printf("Stop reflow process and cooling down."); printf("Please open the door!"); break; case 'c': send->command = 0; // first line bevore declaration. (dummy) send->command = (char) optarg[0]; printf("Set command '%c' \n", send->command ); break; } c = getopt_long (argc, argv, "pt:", long_options, &option_index); } send->check = send->direction ^ send->pre_heat ^ send->set_temp ^ send->reached_temp ^ send->is_locked ^ send->is_cooling ^ send->is_heating ^ send->check; io_write(send); } reflowctrl_destroy(); }
void start_terminal() { char c; byte echo = 1, cnt = 0; write_inverse(6, 30, " SELECT BAUD RATE "); write_inverse(7, 30, " 1: 1200 "); write_inverse(8, 30, " 2: 2400 "); write_inverse(9, 30, " 3: 4800 "); write_inverse(10, 30, " 4: 9600 "); write_inverse(11, 30, " 5: 19200 "); write_inverse(12, 30, " 6: 38400 "); write_inverse(13, 30, " 7: 57600 "); write_inverse(14, 30, " 8: 115200 "); do { c = getchar(); } while (!(c >= '1' && c <= '8')); // set baud rate io_write(170, c - '0'); switch (c) { case '1': write_inverse(0, 20, "1200 BAUD"); break; case '2': write_inverse(0, 20, "2400 BAUD"); break; case '3': write_inverse(0, 20, "4800 BAUD"); break; case '4': write_inverse(0, 20, "9600 BAUD"); break; case '5': write_inverse(0, 20, "19200 BAUD"); break; case '6': write_inverse(0, 20, "38400 BAUD"); break; case '7': write_inverse(0, 20, "57600 BAUD"); break; case '8': write_inverse(0, 20, "115200 BAUD"); break; } clrscr(); showcursor(); while (1) { c = getchar(); cnt = 0; if (c == 0) { // special key c = getchar(); switch (c) { case 60: // F2 echo = 1 - echo; if (echo) write_inverse(0, 0, " F2: ECHO ON "); else write_inverse(0, 0, " F2: ECHO OFF"); break; case 66: // F8 clrscr(); break; case 68: // F10 quit_app(); break; } // switch (c) } // if (c == 0) else { io_write(171, c); if (echo) putchar(c); } // if (c == 0) else if (io_read(174)) { hidecursor(); do { c = io_read(173); if (c) putchar(c); } while (c); showcursor(); } } // while (1) } // start_terminal
void cd64_enable() { io_write(CD64_REG_MODE_ENABLE,CD64_ENABLED); }
bool CHttpDownloader::GetToFile(const char *url, const char *dest, unsigned timeOut, unsigned downloadSpeed) { if (!dest || dest[0] == 0) return false; int64 downloadTime = time_get(); unsigned chunkBytes = 0; NETSOCKET sock; NETADDR nadd, bindAddr; mem_zero(&nadd, sizeof(nadd)); mem_zero(&bindAddr, sizeof(bindAddr)); bindAddr.type = NETTYPE_IPV4; NETURL NetUrl = CreateUrl(url); if (net_host_lookup(NetUrl.m_aHost, &nadd, NETTYPE_IPV4) != 0) { dbg_msg("HttpDownloader", "Error can't found '%s'...", NetUrl.m_aHost); return false; } nadd.port = 80; sock = net_tcp_create(bindAddr); if (net_tcp_connect(sock, &nadd) != 0) { dbg_msg("HttpDownloader", "Error can't connect with '%s'...", NetUrl.m_aHost); net_tcp_close(sock); return false; } net_socket_rcv_timeout(sock, timeOut); char aBuff[512] = {0}; str_format(aBuff, sizeof(aBuff), "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", NetUrl.m_aSlug, NetUrl.m_aHost); net_tcp_send(sock, aBuff, str_length(aBuff)); std::string NetData; unsigned TotalRecv = 0; unsigned TotalBytes = 0; int CurrentRecv = 0; unsigned nlCount = 0; char aNetBuff[1024] = {0}; IOHANDLE dstFile = NULL; do { // Limit Speed if (downloadSpeed > 0) { int64 ctime = time_get(); if (ctime - downloadTime <= time_freq()) { if (chunkBytes >= downloadSpeed) { int tdff = (time_freq() - (ctime - downloadTime)) / 1000; thread_sleep(tdff); continue; } } else { chunkBytes = 0; downloadTime = time_get(); } } // CurrentRecv = net_tcp_recv(sock, aNetBuff, sizeof(aNetBuff)); chunkBytes += CurrentRecv; for (int i=0; i<CurrentRecv ; i++) { if (nlCount < 2) { if (aNetBuff[i] == '\r' || aNetBuff[i] == '\n') { ++nlCount; if (NetData.size() > 0) { std::transform(NetData.begin(), NetData.end(), NetData.begin(), ::tolower); if (NetData.find("404 not found") != std::string::npos) { dbg_msg("HttpDownloader", "ERROR 404: '%s' not found...", NetUrl.m_aFile); net_tcp_close(sock); return false; } else if (NetData.find("content-length:") != std::string::npos) { char aFileSize[64]; str_copy(aFileSize, NetData.substr(15).c_str(), sizeof(aFileSize)); str_trim(aFileSize); TotalBytes = atoi(aFileSize); } NetData.clear(); } if (aNetBuff[i] == '\r') ++i; continue; } nlCount = 0; NetData += aNetBuff[i]; } else { if (nlCount == 2) { if (TotalBytes <= 0) { dbg_msg("HttpDownloader", "Error downloading '%s'...", NetUrl.m_aFile); net_tcp_close(sock); return false; } dstFile = io_open(dest, IOFLAG_WRITE); if(!dstFile) { dbg_msg("HttpDownloader", "Error creating '%s'...", dest); net_tcp_close(sock); return false; } ++nlCount; } io_write(dstFile, &aNetBuff[i], 1); TotalRecv++; if (TotalRecv == TotalBytes) break; } } } while (CurrentRecv > 0); net_tcp_close(sock); if (TotalRecv > 0) { io_close(dstFile); return true; } return false; }
void CFetcher::WriteToFile(char *pData, size_t size, size_t nmemb, void *pFile) { io_write((IOHANDLE)pFile, pData, size*nmemb); }
int io_print(struct io *io, const char *s) { return io_write(io, s, strlen(s)); }
/** Writes the given number of characters from the buffer.*/ void serial_write(char * string, uint16_t length) { io_write(io, (uint8_t *)string, length); }
size_t CGetFile::OnData(char *pData, size_t DataSize) { return io_write(m_File, pData, DataSize); }
static error_t main_argp_parser(int key, char *arg, struct argp_state *state) { CAST(srp_gen_options, self, state->input); switch(key) { default: return ARGP_ERR_UNKNOWN; case ARGP_KEY_INIT: state->child_inputs[0] = &self->style; state->child_inputs[1] = NULL; break; case ARGP_KEY_END: if (!self->name) argp_error(state, "No user name given. Use the -l option, or set LOGNAME in the environment."); { struct lsh_fd *fd; if (self->file) { fd = io_write_file(self->backend, self->file->data, O_CREAT | O_EXCL | O_WRONLY, 0600, BLOCK_SIZE, NULL, self->e); if (!fd) argp_failure(state, EXIT_FAILURE, errno, "Could not open '%s'.", self->file->data); } else { fd = io_write(make_lsh_fd(self->backend, STDOUT_FILENO, "stdout", self->e), BLOCK_SIZE, NULL); } self->dest = &fd->write_buffer->super; } while (!self->passwd) { struct lsh_string *pw; struct lsh_string *again; pw = INTERACT_READ_PASSWORD(self->tty, 500, ssh_format("Enter new SRP password: "******"Aborted."); again = INTERACT_READ_PASSWORD(self->tty, 500, ssh_format("Again: "), 1); if (!again) argp_failure(state, EXIT_FAILURE, 0, "Aborted."); if (lsh_string_eq(pw, again)) self->passwd = pw; else lsh_string_free(pw); lsh_string_free(again); } if (self->style < 0) self->style = self->file ? SEXP_CANONICAL : SEXP_TRANSPORT; break; case 'o': self->file = make_string(arg); break; case 'p': self->passwd = ssh_format("%lz", arg); break; } return 0; }
void CMapLayers::OnRender() { if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) return; CUIRect Screen; Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h); vec2 Center = m_pClient->m_pCamera->m_Center; //float center_x = gameclient.camera->center.x; //float center_y = gameclient.camera->center.y; bool PassedGameLayer = false; for(int g = 0; g < m_pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = m_pLayers->GetGroup(g); if(!pGroup) { dbg_msg("MapLayers", "Error:Group was null, Group Number = %d, Total Groups = %d", g, m_pLayers->NumGroups()); dbg_msg("MapLayers", "This is here to prevent a crash but the source of this is unknown, please report this for it to get fixed"); dbg_msg("MapLayers", "we need mapname and crc and the map that caused this if possible, and anymore info you think is relevant"); continue; } if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) { // set clipping float Points[4]; MapScreenToGroup(Center.x, Center.y, m_pLayers->GameGroup(), m_pClient->m_pCamera->m_Zoom); Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]); float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]); float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]); Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()), (int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight())); } MapScreenToGroup(Center.x, Center.y, pGroup, m_pClient->m_pCamera->m_Zoom); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); bool Render = false; bool IsGameLayer = false; bool IsFrontLayer = false; bool IsSwitchLayer = false; bool IsTeleLayer = false; bool IsSpeedupLayer = false; if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) { IsGameLayer = true; PassedGameLayer = 1; } if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer()) IsFrontLayer = true; if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer()) IsSwitchLayer = true; if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer()) IsTeleLayer = true; if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer()) IsSpeedupLayer = true; // skip rendering if detail layers if not wanted if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer) continue; if(m_Type == -1) Render = true; else if(m_Type == 0) { if(PassedGameLayer) return; Render = true; } else { if(PassedGameLayer && !IsGameLayer) Render = true; } if(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0)) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); char aFilename[256]; str_format(aFilename, sizeof(aFilename), "dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height); IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(File) { #if defined(CONF_FAMILY_WINDOWS) static const char Newline[] = "\r\n"; #else static const char Newline[] = "\n"; #endif for(int y = 0; y < pTMap->m_Height; y++) { for(int x = 0; x < pTMap->m_Width; x++) io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index)); io_write(File, Newline, sizeof(Newline)-1); } io_close(File); } } if((Render && !IsGameLayer && (!g_Config.m_ClShowEntities || !g_Config.m_ClDDRaceCheats)) || ((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsGameLayer)) { //layershot_begin(); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; if(pTMap->m_Image == -1) { if(!g_Config.m_ClShowEntities) Graphics()->TextureSet(-1); else Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); } else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image)); CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else if(pLayer->m_Type == LAYERTYPE_QUADS) { CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; if(pQLayer->m_Image == -1) Graphics()->TextureSet(-1); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image)); CQuad *pQuads = (CQuad *)m_pLayers->Map()->GetDataSwapped(pQLayer->m_Data); Graphics()->BlendNone(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this); Graphics()->BlendNormal(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this); } //layershot_end(); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsFrontLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CTile *pFrontTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Front); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsSwitchLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CSwitchTile *pSwitchTiles = (CSwitchTile *)m_pLayers->Map()->GetData(pTMap->m_Switch); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderSwitchOverlay(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsTeleLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CTeleTile *pTeleTiles = (CTeleTile *)m_pLayers->Map()->GetData(pTMap->m_Tele); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderTeleOverlay(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f); } else if((g_Config.m_ClShowEntities && g_Config.m_ClDDRaceCheats) && IsSpeedupLayer) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); CSpeedupTile *pSpeedupTiles = (CSpeedupTile *)m_pLayers->Map()->GetData(pTMap->m_Speedup); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); Graphics()->BlendNormal(); RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); RenderTools()->RenderSpeedupOverlay(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f); } } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); // reset the screen like it was before Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); }
int CDataFileWriter::Finish() { if(!m_File) return 1; int ItemSize = 0; int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize; int DataSize = 0; CDatafileHeader Header; // we should now write this file! if(DEBUG) dbg_msg("datafile", "writing"); // calculate sizes for(int i = 0; i < m_NumItems; i++) { if(DEBUG) dbg_msg("datafile", "item=%d size=%d (%d)", i, m_pItems[i].m_Size, int(m_pItems[i].m_Size+sizeof(CDatafileItem))); ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem); } for(int i = 0; i < m_NumDatas; i++) DataSize += m_pDatas[i].m_CompressedSize; // calculate the complete size TypesSize = m_NumItemTypes*sizeof(CDatafileItemType); HeaderSize = sizeof(CDatafileHeader); OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize; SwapSize = FileSize - DataSize; (void)SwapSize; if(DEBUG) dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize); // construct Header { Header.m_aID[0] = 'D'; Header.m_aID[1] = 'A'; Header.m_aID[2] = 'T'; Header.m_aID[3] = 'A'; Header.m_Version = 4; Header.m_Size = FileSize - 16; Header.m_Swaplen = SwapSize - 16; Header.m_NumItemTypes = m_NumItemTypes; Header.m_NumItems = m_NumItems; Header.m_NumRawData = m_NumDatas; Header.m_ItemSize = ItemSize; Header.m_DataSize = DataSize; // write Header if(DEBUG) dbg_msg("datafile", "HeaderSize=%d", (int)sizeof(Header)); #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); #endif io_write(m_File, &Header, sizeof(Header)); } // write types for(int i = 0, Count = 0; i < 0xffff; i++) { if(m_pItemTypes[i].m_Num) { // write info CDatafileItemType Info; Info.m_Type = i; Info.m_Start = Count; Info.m_Num = m_pItemTypes[i].m_Num; if(DEBUG) dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num); #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int)); #endif io_write(m_File, &Info, sizeof(Info)); Count += m_pItemTypes[i].m_Num; } } // write item offsets for(int i = 0, Offset = 0; i < 0xffff; i++) { if(m_pItemTypes[i].m_Num) { // write all m_pItems in of this type int k = m_pItemTypes[i].m_First; while(k != -1) { if(DEBUG) dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset); int Temp = Offset; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_pItems[k].m_Size + sizeof(CDatafileItem); // next k = m_pItems[k].m_Next; } } } // write data offsets for(int i = 0, Offset = 0; i < m_NumDatas; i++) { if(DEBUG) dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset); int Temp = Offset; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_pDatas[i].m_CompressedSize; } // write data uncompressed sizes for(int i = 0; i < m_NumDatas; i++) { if(DEBUG) dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize); int UncompressedSize = m_pDatas[i].m_UncompressedSize; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int)); #endif io_write(m_File, &UncompressedSize, sizeof(UncompressedSize)); } // write m_pItems for(int i = 0; i < 0xffff; i++) { if(m_pItemTypes[i].m_Num) { // write all m_pItems in of this type int k = m_pItemTypes[i].m_First; while(k != -1) { CDatafileItem Item; Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID; Item.m_Size = m_pItems[k].m_Size; if(DEBUG) dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size); #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int)); swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int)); #endif io_write(m_File, &Item, sizeof(Item)); io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size); // next k = m_pItems[k].m_Next; } } } // write data for(int i = 0; i < m_NumDatas; i++) { if(DEBUG) dbg_msg("datafile", "writing data id=%d size=%d", i, m_pDatas[i].m_CompressedSize); io_write(m_File, m_pDatas[i].m_pCompressedData, m_pDatas[i].m_CompressedSize); } // free data for(int i = 0; i < m_NumItems; i++) mem_free(m_pItems[i].m_pData); for(int i = 0; i < m_NumDatas; ++i) mem_free(m_pDatas[i].m_pCompressedData); io_close(m_File); m_File = 0; if(DEBUG) dbg_msg("datafile", "done"); return 0; }
void CMapLayers::OnRender() { if((Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK && !m_pMenuMap)) return; CLayers *pLayers = 0; if(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK) pLayers = Layers(); else if(m_pMenuMap->IsLoaded()) pLayers = m_pMenuLayers; if(!pLayers) return; CUIRect Screen; Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h); vec2 Center = m_pClient->m_pCamera->m_Center; bool PassedGameLayer = false; for(int g = 0; g < pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = pLayers->GetGroup(g); if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) { // set clipping float Points[4]; RenderTools()->MapScreenToGroup(Center.x, Center.y, pLayers->GameGroup(), m_pClient->m_pCamera->m_Zoom); Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]); float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]); float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]); Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()), (int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight())); } RenderTools()->MapScreenToGroup(Center.x, Center.y, pGroup, m_pClient->m_pCamera->m_Zoom); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l); bool Render = false; bool IsGameLayer = false; if(pLayer == (CMapItemLayer*)pLayers->GameLayer()) { IsGameLayer = true; PassedGameLayer = 1; } // skip rendering if detail layers if not wanted if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer && (Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)) continue; if(m_Type == -1) Render = true; else if(m_Type == 0) { if(PassedGameLayer && (Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)) return; Render = true; } else { if(PassedGameLayer && !IsGameLayer) Render = true; } if(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0)) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; CTile *pTiles = (CTile *)pLayers->Map()->GetData(pTMap->m_Data); CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); char aFilename[256]; str_format(aFilename, sizeof(aFilename), "dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height); IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(File) { for(int y = 0; y < pTMap->m_Height; y++) { for(int x = 0; x < pTMap->m_Width; x++) io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index)); io_write_newline(File); } io_close(File); } } if(Render && !IsGameLayer) { if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; if(pTMap->m_Image == -1) Graphics()->TextureClear(); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image)); CTile *pTiles = (CTile *)pLayers->Map()->GetData(pTMap->m_Data); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else if(pLayer->m_Type == LAYERTYPE_QUADS) { CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; if(pQLayer->m_Image == -1) Graphics()->TextureClear(); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image)); CQuad *pQuads = (CQuad *)pLayers->Map()->GetDataSwapped(pQLayer->m_Data); Graphics()->BlendNone(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this); Graphics()->BlendNormal(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this); } } } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); // reset the screen like it was before Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); }
int write_data(const struct object_descriptor *descr, int offset, int size, const void *buffer) { return io_write(descr, offset, size, buffer); }
void cd64_disable() { io_write(CD64_REG_MODE_ENABLE,CD64_DISABLED); }
static void io_read (SoupSocket *sock, SoupMessage *msg) { SoupMessagePrivate *priv = SOUP_MESSAGE_GET_PRIVATE (msg); SoupMessageIOData *io = priv->io_data; guint status; read_more: switch (io->read_state) { case SOUP_MESSAGE_IO_STATE_NOT_STARTED: return; case SOUP_MESSAGE_IO_STATE_HEADERS: if (!read_metadata (msg, TRUE)) return; /* We need to "rewind" io->read_meta_buf back one line. * That SHOULD be two characters (CR LF), but if the * web server was stupid, it might only be one. */ if (io->read_meta_buf->len < 3 || io->read_meta_buf->data[io->read_meta_buf->len - 2] == '\n') io->read_meta_buf->len--; else io->read_meta_buf->len -= 2; io->read_meta_buf->data[io->read_meta_buf->len] = '\0'; status = io->parse_headers_cb (msg, (char *)io->read_meta_buf->data, io->read_meta_buf->len, &io->read_encoding, io->user_data); g_byte_array_set_size (io->read_meta_buf, 0); if (status != SOUP_STATUS_OK) { /* Either we couldn't parse the headers, or they * indicated something that would mean we wouldn't * be able to parse the body. (Eg, unknown * Transfer-Encoding.). Skip the rest of the * reading, and make sure the connection gets * closed when we're done. */ soup_message_set_status (msg, status); soup_message_headers_append (msg->request_headers, "Connection", "close"); io->read_state = SOUP_MESSAGE_IO_STATE_FINISHING; break; } if (io->read_encoding == SOUP_ENCODING_CONTENT_LENGTH) { SoupMessageHeaders *hdrs = (io->mode == SOUP_MESSAGE_IO_CLIENT) ? msg->response_headers : msg->request_headers; io->read_length = soup_message_headers_get_content_length (hdrs); } if (io->mode == SOUP_MESSAGE_IO_CLIENT && SOUP_STATUS_IS_INFORMATIONAL (msg->status_code)) { if (msg->status_code == SOUP_STATUS_CONTINUE && io->write_state == SOUP_MESSAGE_IO_STATE_BLOCKING) { /* Pause the reader, unpause the writer */ io->read_state = SOUP_MESSAGE_IO_STATE_BLOCKING; io->write_state = io_body_state (io->write_encoding); } else { /* Just stay in HEADERS */ io->read_state = SOUP_MESSAGE_IO_STATE_HEADERS; } } else if (io->mode == SOUP_MESSAGE_IO_SERVER && soup_message_headers_get_expectations (msg->request_headers) & SOUP_EXPECTATION_CONTINUE) { /* The client requested a Continue response. The * got_headers handler may change this to something * else though. */ soup_message_set_status (msg, SOUP_STATUS_CONTINUE); io->write_state = SOUP_MESSAGE_IO_STATE_HEADERS; io->read_state = SOUP_MESSAGE_IO_STATE_BLOCKING; } else { io->read_state = io_body_state (io->read_encoding); /* If the client was waiting for a Continue * but got something else, then it's done * writing. */ if (io->mode == SOUP_MESSAGE_IO_CLIENT && io->write_state == SOUP_MESSAGE_IO_STATE_BLOCKING) io->write_state = SOUP_MESSAGE_IO_STATE_FINISHING; } if (io->mode == SOUP_MESSAGE_IO_CLIENT && SOUP_STATUS_IS_INFORMATIONAL (msg->status_code)) { SOUP_MESSAGE_IO_PREPARE_FOR_CALLBACK; soup_message_got_informational (msg); soup_message_cleanup_response (msg); SOUP_MESSAGE_IO_RETURN_IF_CANCELLED_OR_PAUSED; } else { SOUP_MESSAGE_IO_PREPARE_FOR_CALLBACK; soup_message_got_headers (msg); SOUP_MESSAGE_IO_RETURN_IF_CANCELLED_OR_PAUSED; } break; case SOUP_MESSAGE_IO_STATE_BLOCKING: io_write (sock, msg); /* As in the io_write case, we *must* return here. */ return; case SOUP_MESSAGE_IO_STATE_BODY: if (!read_body_chunk (msg)) return; got_body: io->read_state = SOUP_MESSAGE_IO_STATE_FINISHING; SOUP_MESSAGE_IO_PREPARE_FOR_CALLBACK; soup_message_got_body (msg); SOUP_MESSAGE_IO_RETURN_IF_CANCELLED_OR_PAUSED; break; case SOUP_MESSAGE_IO_STATE_CHUNK_SIZE: if (!read_metadata (msg, FALSE)) return; io->read_length = strtoul ((char *)io->read_meta_buf->data, NULL, 16); g_byte_array_set_size (io->read_meta_buf, 0); if (io->read_length > 0) io->read_state = SOUP_MESSAGE_IO_STATE_CHUNK; else io->read_state = SOUP_MESSAGE_IO_STATE_TRAILERS; break; case SOUP_MESSAGE_IO_STATE_CHUNK: if (!read_body_chunk (msg)) return; io->read_state = SOUP_MESSAGE_IO_STATE_CHUNK_END; break; case SOUP_MESSAGE_IO_STATE_CHUNK_END: if (!read_metadata (msg, FALSE)) return; g_byte_array_set_size (io->read_meta_buf, 0); io->read_state = SOUP_MESSAGE_IO_STATE_CHUNK_SIZE; break; case SOUP_MESSAGE_IO_STATE_TRAILERS: if (!read_metadata (msg, FALSE)) return; if (io->read_meta_buf->len <= SOUP_MESSAGE_IO_EOL_LEN) goto got_body; /* FIXME: process trailers */ g_byte_array_set_size (io->read_meta_buf, 0); break; case SOUP_MESSAGE_IO_STATE_FINISHING: if (io->read_tag) { g_signal_handler_disconnect (io->sock, io->read_tag); io->read_tag = 0; } io->read_state = SOUP_MESSAGE_IO_STATE_DONE; if (io->mode == SOUP_MESSAGE_IO_SERVER) { io->write_state = SOUP_MESSAGE_IO_STATE_HEADERS; io_write (sock, msg); } else soup_message_io_finished (msg); return; case SOUP_MESSAGE_IO_STATE_DONE: default: g_return_if_reached (); } goto read_more; }
void cd64_init() { cd64_enable(); io_write(CD64_REG_MODE,CD64_MODE_0); }
void CDemoVideoRecorder::Init(int Width, int Height, int FPS, int Format, const char *pName) { m_Counter = 0; m_Frame = 0; m_pAudioFrame = 0; m_pVideoFrame = 0; m_pSound = Kernel()->RequestInterface<ISound>(); av_register_all(); avcodec_register_all(); m_FPS = FPS; m_ScreenWidth = Width; m_ScreenHeight = Height; m_Format = Format; if (m_Format == IClient::DEMO_RECORD_FORMAT_OGV) { ogg_stream_init(&m_TheoraOggStreamState, rand()); ogg_stream_init(&m_VorbisOggStreamState, rand()); char aBuf[1024]; if (str_find_rev(pName, "/")) str_format(aBuf, sizeof(aBuf), "%s.ogv", str_find_rev(pName, "/")); else if (str_find_rev(aBuf, "\\")) str_format(aBuf, sizeof(pName), "%s.ogv", str_find_rev(pName, "\\")); else str_format(aBuf, sizeof(aBuf), "%s.ogv", pName); m_OutFile = io_open(aBuf, IOFLAG_WRITE); //thread_sleep(10000); vorbis_info_init(&m_VorbisEncodingInfo); vorbis_encode_init_vbr(&m_VorbisEncodingInfo, 2, g_Config.m_SndRate, 1.0f); //2 ch - samplerate - quality 1 vorbis_analysis_init(&m_VorbisState, &m_VorbisEncodingInfo); vorbis_block_init(&m_VorbisState, &m_VorbisBlock); vorbis_comment_init(&m_VorbisComment); ogg_packet header; ogg_packet header_comm; ogg_packet header_code; vorbis_analysis_headerout(&m_VorbisState, &m_VorbisComment, &header, &header_comm, &header_code); ogg_stream_packetin(&m_VorbisOggStreamState, &header); ogg_stream_packetin(&m_VorbisOggStreamState, &header_comm); ogg_stream_packetin(&m_VorbisOggStreamState, &header_code); th_info_init(&m_TheoraEncodingInfo); //this should not work, as far as i know. but idk how to kill the green bar at the bottom m_TheoraEncodingInfo.frame_width = m_ScreenWidth;//+15&~0xF; m_TheoraEncodingInfo.frame_height = m_ScreenHeight;//+15&~0xF; m_TheoraEncodingInfo.pic_width = m_ScreenWidth; m_TheoraEncodingInfo.pic_height = m_ScreenHeight; m_TheoraEncodingInfo.pic_x = m_TheoraEncodingInfo.frame_width - m_ScreenWidth>>1&~1; m_TheoraEncodingInfo.pic_y = m_TheoraEncodingInfo.frame_height - m_ScreenHeight>>1&~1; m_TheoraEncodingInfo.colorspace = TH_CS_UNSPECIFIED; m_TheoraEncodingInfo.fps_numerator = FPS; //fps m_TheoraEncodingInfo.fps_denominator = 1; m_TheoraEncodingInfo.aspect_numerator = -1; m_TheoraEncodingInfo.aspect_denominator = -1; m_TheoraEncodingInfo.pixel_fmt = TH_PF_444; m_TheoraEncodingInfo.target_bitrate = (int)(64870*(ogg_int64_t)48000>>16); m_TheoraEncodingInfo.quality = 32; m_TheoraEncodingInfo.keyframe_granule_shift = 0; m_pThreoraContext = th_encode_alloc(&m_TheoraEncodingInfo); int arg = TH_RATECTL_CAP_UNDERFLOW; th_encode_ctl(m_pThreoraContext, TH_ENCCTL_SET_RATE_FLAGS, &arg, sizeof(arg)); th_comment CommentHeader; ogg_packet OggPacket; th_comment_init(&CommentHeader); mem_zero(&OggPacket, sizeof(OggPacket)); //Flush //Step 1 th_encode_flushheader(m_pThreoraContext, &CommentHeader, &OggPacket); // first header ogg_stream_packetin(&m_TheoraOggStreamState, &OggPacket); // ogg_page OggPage; ogg_stream_pageout(&m_TheoraOggStreamState, &OggPage); io_write(m_OutFile, OggPage.header, OggPage.header_len); io_write(m_OutFile, OggPage.body, OggPage.body_len); while(1) { ogg_page OggPage; if (ogg_stream_flush(&m_VorbisOggStreamState,&OggPage) == 0) break; io_write(m_OutFile, OggPage.header, OggPage.header_len); io_write(m_OutFile, OggPage.body, OggPage.body_len); } while(th_encode_flushheader(m_pThreoraContext, &CommentHeader, &OggPacket)) { ogg_stream_packetin(&m_TheoraOggStreamState, &OggPacket); } ogg_stream_flush(&m_TheoraOggStreamState, &OggPage); io_write(m_OutFile, OggPage.header, OggPage.header_len); io_write(m_OutFile, OggPage.body, OggPage.body_len); }
/** * Handle system calls. Interrupts are enabled when this function is * called. * * @param user_context The userland context (CPU registers as they * where when system call instruction was called in userland) */ void syscall_handle(context_t *user_context) { /* When a syscall is executed in userland, register a0 contains * the number of the syscall. Registers a1, a2 and a3 contain the * arguments of the syscall. The userland code expects that after * returning from the syscall instruction the return value of the * syscall is found in register v0. Before entering this function * the userland context has been saved to user_context and after * returning from this function the userland context will be * restored from user_context. */ switch (A0) { case SYSCALL_HALT: halt_kernel(); break; case SYSCALL_READ: { int filehandle = (int)A1; if (filehandle == FILEHANDLE_STDIN || filehandle == FILEHANDLE_STDOUT || filehandle == FILEHANDLE_STDERR) { V0 = io_read((int) A1, (void*) A2, (int) A3); } else { V0 = syscall_read((openfile_t)A1, (void *)A2, (int)A3); } } break; case SYSCALL_WRITE: { int filehandle = (int)A1; if (filehandle == FILEHANDLE_STDIN || filehandle == FILEHANDLE_STDOUT || filehandle == FILEHANDLE_STDERR) { V0 = io_write((int) A1, (void*) A2, (int) A3); } else { V0 = syscall_write((openfile_t)A1, (void *)A2, (int)A3); } } break; case SYSCALL_EXEC: V0 = syscall_exec((char*) A1); break; case SYSCALL_EXIT: syscall_exit((int) A1); break; case SYSCALL_JOIN: V0 = syscall_join((process_id_t) A1); break; case SYSCALL_OPEN: V0 = syscall_open((char *) A1); break; case SYSCALL_CLOSE: V0 = syscall_close((openfile_t) A1); break; case SYSCALL_SEEK: V0 = syscall_seek((openfile_t)A1, (int)A2); break; case SYSCALL_CREATE: V0 = syscall_create((const char *)A1, (int)A2); break; case SYSCALL_REMOVE: V0 = syscall_remove((const char *)A1); break; case SYSCALL_TELL: V0 = syscall_tell((openfile_t)A1); break; case SYSCALL_SEM_OPEN: V0 = (uint32_t) usr_sem_open((char*) A1, A2); break; case SYSCALL_SEM_PROCURE: V0 = usr_sem_p((usr_sem_t*) A1); break; case SYSCALL_SEM_VACATE: V0 = usr_sem_v((usr_sem_t*) A1); break; case SYSCALL_SEM_DESTROY: V0 = usr_sem_destroy((usr_sem_t*) A1); break; default: KERNEL_PANIC("Unhandled system call\n"); } /* Move to next instruction after system call */ user_context->pc += 4; }