int main(int argc, char** argv) { char *input_filename = NULL; char *catalog_filename = NULL; char *output_filename = NULL; rs_module_t *modules = NULL; long modules_count = 2; long module_index = 0; #if HAVE_XLSXWRITER modules_count++; #endif modules = calloc(modules_count, sizeof(rs_module_t)); modules[module_index++] = rs_mod_readstat; modules[module_index++] = rs_mod_csv; #if HAVE_XLSXWRITER modules[module_index++] = rs_mod_xlsx; #endif if (argc == 2 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) { print_version(); return 0; } else if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { print_usage(argv[0]); return 0; } else if (argc == 2) { if (!can_read(argv[1])) { print_usage(argv[0]); return 1; } input_filename = argv[1]; } else if (argc == 3) { if (!can_read(argv[1]) || !can_write(modules, modules_count, argv[2])) { print_usage(argv[0]); return 1; } input_filename = argv[1]; output_filename = argv[2]; } else if (argc == 4) { if (!can_read(argv[1]) || !is_catalog(argv[2]) || !can_write(modules, modules_count, argv[3])) { print_usage(argv[0]); return 1; } input_filename = argv[1]; catalog_filename = argv[2]; output_filename = argv[3]; } else { print_usage(argv[0]); return 1; } if (output_filename) return convert_file(input_filename, catalog_filename, output_filename, modules, modules_count); return dump_file(input_filename); }
/** * Send data package though the ssl connection * @param ssl ssl connection * @param buffer array containg the data * @param len size of the data container * @return number of bytes transmitted, -1 in case of an error */ int send_ssl_socket(ssl_connection *ssl, void *buffer, int len) { #ifdef HAVE_OPENSSL int n= 0; ASSERT(ssl); do { n= SSL_write(ssl->handler, buffer, len); } while(n <= 0 && BIO_should_retry(ssl->socket_bio) && can_write(ssl->socket, 5)); if(n <= 0) { return -1; } return n; #else return -1; #endif }
/* can发送测试 */ int can_write_test(uint8 ucBoardType) { struct can_frame stCanFrame; /* aa 00 03 01 00 01 05 55 */ /* CAN ID 设置 */ if((0 < ucBoardType) && (64 >= ucBoardType)) { stCanFrame.can_id = 0x80000000 | (ucBoardType<<16); } else { stCanFrame.can_id = 0x80010000; } stCanFrame.can_dlc = 8; stCanFrame.data[0] = 0xaa; stCanFrame.data[1] = 0x00; stCanFrame.data[2] = 0x03; stCanFrame.data[3] = 0x01; stCanFrame.data[4] = 0x00; stCanFrame.data[5] = 0x01; stCanFrame.data[6] = 0x05; stCanFrame.data[7] = 0x55; return can_write(&stCanFrame); }
// (virtual) bool MemoryStream::set_size( Sint64 size) { if (!is_open()) return false; if (!can_write()) return false; if (size < 0) return false; if (ext_buffer_ != NULL) return false; int_buffer_.resize(static_cast<size_t>(size)); size_ = size; if (size_ > 0) buffer_ = reinterpret_cast<Uint8*>(&int_buffer_[0]); else buffer_ = NULL; return true; }
void itrm_queue_event(struct itrm *itrm, unsigned char *data, int len) { int w = 0; if (!len) return; if (!itrm->out.queue.len && can_write(itrm->out.sock)) { w = safe_write(itrm->out.sock, data, len); if (w <= 0 && HPUX_PIPE) { register_bottom_half(free_itrm, itrm); return; } } if (w < len) { int left = len - w; unsigned char *c = mem_realloc(itrm->out.queue.data, itrm->out.queue.len + left); if (!c) { free_itrm(itrm); return; } itrm->out.queue.data = c; memcpy(itrm->out.queue.data + itrm->out.queue.len, data + w, left); itrm->out.queue.len += left; set_handlers(itrm->out.sock, get_handler(itrm->out.sock, SELECT_HANDLER_READ), (select_handler_T) itrm_queue_write, (select_handler_T) free_itrm, itrm); } }
static enum op_stats operation_status(struct operation *op) { GSList *t = NULL; enum op_stats stats; if (op == NULL) return OP_UNKNOWN; switch (op->cmd) { case CMD_WRITE: return can_write(op); case CMD_READ: return can_read(op); case CMD_LOCK_S: stats = can_s_lock(op); if (stats == OP_OK) { t = g_hash_table_lookup(lock_s_table, op->var); t = g_slist_append(t, &(op->transaction)); g_hash_table_insert(lock_s_table, op->var, t); } return stats; case CMD_LOCK_X: stats = can_x_lock(op); if (stats == OP_OK) x_lock(op); return stats; case CMD_UNLOCK: return unlock_variable(op, 0); case CMD_UNKNOWN: default: break; } return OP_ERROR; }
static enum op_stats can_read(struct operation *op) { GSList *t = NULL; struct operation *tmpop; enum op_stats stats; char *var; int trans; if (op == NULL) return OP_ERROR; stats = can_write(op); if (stats == OP_OK) return OP_OK; else if (stats == OP_WAIT) return OP_WAIT; var = op->var; trans = op->transaction; // Checando se a variável já foi bloqueada de maneira compartilhada // pela transição. t = g_hash_table_lookup(lock_s_table, var); if (t != NULL) { for (int i = 0; i < g_slist_length(t); i++) { tmpop = g_slist_nth_data(t, i); if (tmpop->transaction == trans) return OP_OK; } } return OP_ERROR; }
const char *pzq::visitor_t::visit_full (const char *kbuf, size_t ksiz, const char *vbuf, size_t vsiz, size_t *sp) { size_t msg_size, pos = 0; std::string key (kbuf, ksiz); if (!can_write ()) throw std::runtime_error ("Reached maximum messages in flight limit"); if ((*m_store).is_in_flight (key)) return NOP; pzq::message_t parts; parts.append (key); // Check if it is a replica and if it should be sent memcpy( &msg_size, vbuf, sizeof( uint64_t ) ); if( msg_size > 8 && strncmp( vbuf+sizeof(uint64_t), "REPLICA:", 8 ) == 0 ) { std::string replicaSource = std::string( vbuf+sizeof(uint64_t) + 8, msg_size - 8 ); if( !m_cluster->shouldSendReplica( replicaSource ) ) return NOP; m_cluster->checkReplica( key, replicaSource ); } // Time when the message goes out std::stringstream mt; mt << pzq::microsecond_timestamp (); parts.append (mt.str ()); std::stringstream expiry; expiry << (*m_store).get_ack_timeout (); parts.append (expiry.str ()); parts.append (); while (true) { memcpy (&msg_size, vbuf + pos, sizeof (uint64_t)); pos += sizeof (uint64_t); parts.append (vbuf + pos, msg_size); pos += msg_size; if (pos >= vsiz) break; } if ((*m_socket).send_many (parts, ZMQ_NOBLOCK)) (*m_store).mark_in_flight (key); else throw std::runtime_error ("Reached maximum messages in flight limit"); return NOP; }
/** * Send data package though the ssl connection * @param ssl ssl connection * @param buffer array containg the data * @param len size of the data container * @param timeout Seconds to wait for data to be written * @return number of bytes transmitted, -1 in case of an error */ int send_ssl_socket(ssl_connection *ssl, void *buffer, int len, int timeout) { int n = 0; ASSERT(ssl); do { n = SSL_write(ssl->handler, buffer, len); } while (n <= 0 && BIO_should_retry(ssl->socket_bio) && can_write(ssl->socket, timeout)); return (n > 0) ? n : -1; }
static int create_writefile(lua_State *L, const char* mode) { const char *filename = luaL_checkstring(L, 1); luaL_Stream *p = (luaL_Stream *)lua_newuserdata(L, sizeof(luaL_Stream)); luaL_setmetatable(L, LUA_FILEHANDLE); p->closef = 0; p->f = 0; if (!can_write(filename, p, mode)) { errno = EACCES; return luaL_fileresult(L, 0, filename); } return (p == NULL || p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; }
void socket_engine::run() { fd_set self; FD_ZERO(&self); FD_SET(socket_, &self); while (!closed()) { process(); if (!closed()) { int n = ::select(FD_SETSIZE, can_read() ? &self : NULL, can_write() ? &self : NULL, NULL, NULL); check(n, "select: "); } } }
void connection_engine::try_write() { size_t max = can_write(); if (max == 0) return; try { size_t n = io_write(pn_transport_head(ctx_->transport), max); if (n > max) { throw io_error(msg() << "write invalid size: " << n << " > " << max); } pn_transport_pop(ctx_->transport, n); } catch (const closed_error&) { pn_transport_close_head(ctx_->transport); } catch (const io_error& e) { set_error(ctx_, e.what()); pn_transport_close_head(ctx_->transport); } }
void turn(int fd, int right) { short int value = 2106; if (!right) { value = -value; } // demi tour /*if (right) { packet.b[0] = 116; packet.b[1] = 16; } else { packet.b[0] = 140; packet.b[1] = 239; }*/ can_write(fd, bin, 1026, 2, ((char*)&value)[0], ((char*)&value)[1]); }
// (virtual) bool MemoryStream::write( const void* buffer, int count) { if (!is_open()) return false; if (!can_write()) return false; if (count < 0) return false; if (count == 0) return true; if (buffer == NULL) return false; if (ext_buffer_ == NULL) { Sint64 new_size = position_ + count; if (new_size > size_) { int_buffer_.resize(static_cast<size_t>(new_size)); size_ = new_size; buffer_ = reinterpret_cast<Uint8*>(&int_buffer_[0]); } } else { if ((position_ + count) > ext_size_) return false; } std::uninitialized_copy( static_cast<const Uint8*>(buffer), &static_cast<const Uint8*>(buffer)[count], &buffer_[position_]); position_ += count; return true; }
bool connection_engine::process_nothrow(int flags) { if (closed()) return false; if (flags & WRITE) try_write(); dispatch(); if (flags & READ) try_read(); dispatch(); if (connection_.closed() && !closed()) { dispatch(); while (can_write()) { try_write(); // Flush final data. } // no transport errors. close_transport(ctx_); } if (closed()) { pn_transport_unbind(ctx_->transport); dispatch(); try { io_close(); } catch(const io_error&) {} // Tell the IO to close. } return !closed(); }
/** * Handle errors during read, write, connect and accept * @return TRUE if non fatal, FALSE if non fatal and retry */ static int handle_error(int code, ssl_connection *ssl) { int ssl_error = SSL_get_error(ssl->handler, code); switch (ssl_error) { case SSL_ERROR_NONE: return TRUE; case SSL_ERROR_WANT_READ: if (can_read(ssl->socket, SSL_TIMEOUT)) return TRUE; LogError("SSL read timeout error\n"); break; case SSL_ERROR_WANT_WRITE: if (can_write(ssl->socket, SSL_TIMEOUT)) return TRUE; LogError("SSL write timeout error\n"); break; case SSL_ERROR_SYSCALL: LogError("SSL syscall error: %s\n", STRERROR); break; case SSL_ERROR_SSL: LogError("SSL engine error: %s\n", SSLERROR); break; default: LogError("SSL error\n"); break; } return FALSE; }
int32_t CircBuffer::Write(binary* data, uint32_t length){ if(can_write(length)){ unsigned int bbw = bytes_before_wrap_write(); if (bbw >= length) { memcpy(write_ptr, data, length); move_pointer(&write_ptr, length); bytes_in_buf += length; }else{ if(bbw != 0){ memcpy(write_ptr,data,bbw); length -= bbw; bytes_in_buf += bbw; data += bbw; move_pointer(&write_ptr, bbw); //Reset to beginning } memcpy(write_ptr, data,length); bytes_in_buf += length; move_pointer(&write_ptr, length); } return 0; }else{ return -1; } }
int CAN::write(CANMessage msg) { return can_write(&_can, msg, 0); }
list<int> IOSelect::can_write(const int seconds) { struct timeval timeout = {seconds, 0}; return can_write(&timeout); }
int main(int argc, char* argv[]) { int i = 0; struct timespec timedelay; int fd = -1; char* port = "/dev/can1"; uint8_t extended = 0; int nmax = 0; int opt = 0; int verbose = 0; /* db_clt_typ *pclt; char hostname[MAXHOSTNAMELEN+1]; char *domain = DEFAULT_SERVICE; int xport = COMM_OS_XPORT; */ msg_type messages[6]; // 6 types of messages to be sent int num_msg = sizeof(messages) / sizeof(messages[0]); // initialize the messages memset(messages, 0, sizeof(messages)); messages[0].id = 0; messages[0].frequency = 1; messages[1].id = 1; messages[1].frequency = 40; messages[2].id = 2; messages[2].frequency = 40; messages[3].id = 3; messages[3].frequency = 40; messages[4].id = 4; messages[4].frequency = 500; messages[5].id = 5; messages[5].frequency = 20; for (i = 0; i < num_msg; i++) { messages[i].count = 1; // have them all send only 1 for now messages[i].period = 1.0 / messages[i].frequency; } // parse the command-line args while ((opt = getopt(argc, argv, "e:n:p:v:z")) != -1) { printf ("opt = %d\n", opt); switch (opt) { case 'e': extended = 1; break; case 'n': nmax = atoi(optarg); break; case 'p': port = strdup(optarg); break; case 'v': verbose = 1; break; } } // initialize the timedelay structure timedelay.tv_sec = 0; timedelay.tv_nsec = 10000000; /* 10 millsecs */ // open can port printf("sensor_simulator: trying to open %s\n", port); fflush(stdout); fd = can_open(port, O_WRONLY); if (fd == -1 || fd == 0) { fprintf (stderr, "error opening %s\n", port); exit(EXIT_FAILURE); } printf ("can port opened. fd = %d\n", fd); // open database /* get_local_name(hostname, MAXHOSTNAMELEN); if ((pclt = db_list_init(argv[0], hostname, domain, xport, NULL, 0, NULL, 0)) == NULL) { printf("Database initialization error in %s.\n", argv[0]); exit(EXIT_FAILURE); } */ // keep on sending data until someone decides to press ctrl+C for (;;) { unsigned now_ms; struct timespec timeread; clock_gettime(CLOCK_REALTIME, &timeread); now_ms = timeread.tv_sec * 1000 + timeread.tv_nsec / 1000000; for (i = 0; i < num_msg; ++i) { // see how long it has been since that message was last sent unsigned long diff = now_ms - messages[i].last_sent; int j = 0; // if not longer than the period, move on if (diff < messages[i].period) continue; for (j = 0; j < messages[i].count; j++) { can_write(fd, messages[i].id, 0, &messages[i].data, 8); // snd_g(pclt, fd, 0, (void*)&vaa_msg_funcs[messages[i].id+1]); messages[i].data++; } messages[i].last_sent = now_ms; } // sleep for 10 ms to avoid using all the cpu // nanosleep(&timedelay, NULL); } return 0; }
/* 发送数据到CAN */ int send_data_to_can(int lBoardType, char *pcCmd, int lCmdLen) { struct can_frame stCanFrame; int i = 0; uint8 ucCnt = 0; uint16 unTemp = 0; if(INVALID_POINTER(pcCmd) || (1 > lCmdLen) || (1 > lBoardType)) { DEBUG_MSG("E:input param error!\r\n"); return -1; } /*! 计算数据需要几个报文帧 */ unTemp = lCmdLen / 8; if(0x0000 != (lCmdLen & 0x0007)) { unTemp = unTemp + 1; } /*! 数据不大于8字节,无需分段 */ if(1 == unTemp) { stCanFrame.can_id = 0x80000000 | (15 << 22) | (lBoardType << 16) |FRAME_NONE_SEG; stCanFrame.can_dlc = lCmdLen; for(i = 0; i < lCmdLen; i++) { stCanFrame.data[i] = pcCmd[i]; } if(0 > can_write(&stCanFrame)) { return -1; } } else { /*! 第一个分段报文 */ stCanFrame.can_id = 0x80000000 | (15 << 22) | (lBoardType << 16) | FRAME_FIRST_SEG; stCanFrame.can_dlc = 8; for(i = 0; i<8; i++) { stCanFrame.data[i] = *pcCmd; pcCmd++; } if(0 > can_write(&stCanFrame)) { return -1; } unTemp--; ucCnt = 1; /*! 中间分段报文 */ while(1 != unTemp) { stCanFrame.can_id = 0x80000000 | (15 << 22) | (lBoardType << 16) | FRAME_MIDDLE_SEG | (ucCnt << 8); stCanFrame.can_dlc = 8; for(i = 0; i<8; i++) { stCanFrame.data[i] = *pcCmd; pcCmd++; } if(0 > can_write(&stCanFrame)) { return -1; } unTemp--; ucCnt++; } /*! 最后分段报文 */ if(0x0000 == (lCmdLen & 0x0007)) { unTemp = 8; } else { unTemp = lCmdLen & 0x0007; } ucCnt = 0; stCanFrame.can_id = 0x80000000 | (15 << 22) | (lBoardType << 16) | FRAME_END_SEG | (ucCnt << 8); stCanFrame.can_dlc = unTemp; for(i = 0; i<unTemp; i++) { stCanFrame.data[i] = *pcCmd; pcCmd++; } if(0 > can_write(&stCanFrame)) { return -1; } } return 0; }
/************************************************** * Function name : void can_buffer_send(void) * return : 0 - failure: fail to send the message * : 1 - success * Created by : Luca Lucci * Date created : 11/11/12 * Description : This function sends the data from tx buffer to * CAN buffer and updates the data count and read pointer * variables of transmit buffer. When interrupt is disable, * the can_buffer param should be -1 * Notes : if interrupt is disable, this is a blocking function! * It wait until one buffer frees. **************************************************/ unsigned char can_buffer_send(void) { unsigned char buffer_index; //buffer's index where to send the data unsigned char i; // for loop //to remember when interrupt has to be enabled unsigned char txbnie_flag = 0; // check if tx buffer is empty if( !can_status.buffer_tx_empty ) { #ifndef CAN_INTERRUPT_TX // searching for a free tx buffer do{ buffer_index = can_load_buffer(-1, &can_buffer_tx[can_buffer_tx_rd_ptr]); } while( buffer_index == -1 ); #else // else load a free buffer that updates with interrupt if(can_buffer_tx_free) { //critical code, disable interrupt if(PIE5bits.TXBnIE) { PIE5bits.TXBnIE = 0; txbnie_flag = 1; } else txbnie_flag = 0; //find the buffer with highest priority for(i = 9; i > 0; i--) { if(((can_buffer_tx_free & can_buffer_tx_mask) >> (i - 1)) & 0x01) { buffer_index = i - 1; can_buffer_tx_free &= ~(0x001 << buffer_index); //reset flag for buffer break; } } // re-enable interrupt if(txbnie_flag) PIE5bits.TXBnIE = 1; buffer_index = can_load_buffer(buffer_index, &can_buffer_tx[can_buffer_tx_rd_ptr]); if(buffer_index == -1) // no can buffer availble return 0; #endif if(!can_write(buffer_index)) return 0; else count++; if(can_status.buffer_tx_full) can_status.buffer_tx_full = 0; can_buffer_tx_data_cnt--; if(can_buffer_tx_data_cnt == 0 ) can_status.buffer_tx_empty = 1; can_buffer_tx_rd_ptr++; if(can_buffer_tx_rd_ptr == CAN_BUFFER_SIZE_TX) can_buffer_tx_rd_ptr = 0; } #ifdef CAN_INTERRUPT_TX } #endif return 1; }
int CAN::write(CANMessage msg) { lock(); int ret = can_write(&_can, msg, 0); unlock(); return ret; }
/*PAGE * * exec_command * * Parse and execute FTP command. * * FIXME: This section is somewhat of a hack. We should have a better * way to parse commands. * * Input parameters: * info - corresponding SessionInfo structure * cmd - command to be executed (upper-case) * args - arguments of the command * * Output parameters: * NONE */ static void exec_command(FTPD_SessionInfo_t *info, char* cmd, char* args) { char fname[FTPD_BUFSIZE]; int wrong_command = 0; fname[0] = '\0'; if (!strcmp("PORT", cmd)) { command_port(info, args); } else if (!strcmp("PASV", cmd)) { command_pasv(info); } else if (!strcmp("RETR", cmd)) { strncpy(fname, args, 254); command_retrieve(info, fname); } else if (!strcmp("STOR", cmd)) { strncpy(fname, args, 254); command_store(info, fname); } else if (!strcmp("LIST", cmd)) { strncpy(fname, args, 254); command_list(info, fname, 1); } else if (!strcmp("NLST", cmd)) { strncpy(fname, args, 254); command_list(info, fname, 0); } else if (!strcmp("MDTM", cmd)) { strncpy(fname, args, 254); command_mdtm(info, fname); } else if (!strcmp("SYST", cmd)) { send_reply(info, 215, FTPD_SYSTYPE); } else if (!strcmp("TYPE", cmd)) { if (args[0] == 'I') { info->xfer_mode = TYPE_I; send_reply(info, 200, "Type set to I."); } else if (args[0] == 'A') { info->xfer_mode = TYPE_A; send_reply(info, 200, "Type set to A."); } else { info->xfer_mode = TYPE_I; send_reply(info, 504, "Type not implemented. Set to I."); } } else if (!strcmp("USER", cmd) || !strcmp("PASS", cmd)) { send_reply(info, 230, "User logged in."); } else if (!strcmp("DELE", cmd)) { if(!can_write()) { send_reply(info, 550, "Access denied."); } else if ( strncpy(fname, args, 254) && unlink(fname) == 0) { send_reply(info, 257, "DELE successful."); } else { send_reply(info, 550, "DELE failed."); } } else if (!strcmp("SITE", cmd)) { char* opts; split_command(args, &cmd, &opts, &args); if(!strcmp("CHMOD", cmd)) { int mask; if(!can_write()) { send_reply(info, 550, "Access denied."); } else { char *c; c = strchr(args, ' '); if((c != NULL) && (sscanf(args, "%o", &mask) == 1) && strncpy(fname, c+1, 254) && (chmod(fname, (mode_t)mask) == 0)) send_reply(info, 257, "CHMOD successful."); else send_reply(info, 550, "CHMOD failed."); } } else wrong_command = 1; } else if (!strcmp("RMD", cmd)) { if(!can_write()) { send_reply(info, 550, "Access denied."); } else if ( strncpy(fname, args, 254) && rmdir(fname) == 0) { send_reply(info, 257, "RMD successful."); } else { send_reply(info, 550, "RMD failed."); } } else if (!strcmp("MKD", cmd)) { if(!can_write()) { send_reply(info, 550, "Access denied."); } else if ( strncpy(fname, args, 254) && mkdir(fname, S_IRWXU | S_IRWXG | S_IRWXO) == 0) { send_reply(info, 257, "MKD successful."); } else { send_reply(info, 550, "MKD failed."); } } else if (!strcmp("CWD", cmd)) { strncpy(fname, args, 254); command_cwd(info, fname); } else if (!strcmp("CDUP", cmd)) { command_cwd(info, ".."); } else if (!strcmp("PWD", cmd)) { command_pwd(info); } else wrong_command = 1; if(wrong_command) send_reply(info, 500, "Command not understood."); }
/*PAGE * * command_store * * Performs the "STOR" command (receive data from client). * * Input parameters: * info - corresponding SessionInfo structure * char *filename - Destination filename. * * Output parameters: * NONE */ static void command_store(FTPD_SessionInfo_t *info, char const *filename) { int s; int n; unsigned long size = 0; struct rtems_ftpd_hook *usehook = NULL; char buf[FTPD_DATASIZE]; int res = 1; int bare_lfs = 0; int null = 0; typedef ssize_t (*WriteProc)(int, void const*, size_t); WriteProc wrt = &write; if(!can_write()) { send_reply(info, 550, "Access denied."); return; } send_mode_reply(info); s = data_socket(info); if(0 > s) return; null = !strcmp("/dev/null", filename); if (null) { /* File "/dev/null" just throws data away. * FIXME: this is hack. Using `/dev/null' filesystem entry would be * better. */ wrt = &discard; } if (!null && rtems_ftpd_configuration.hooks != NULL) { /* Search our list of hooks to see if we need to do something special. */ struct rtems_ftpd_hook *hook; int i; i = 0; hook = &rtems_ftpd_configuration.hooks[i++]; while (hook->filename != NULL) { if (!strcmp(hook->filename, filename)) { usehook = hook; break; } hook = &rtems_ftpd_configuration.hooks[i++]; } } if (usehook != NULL) { /* * OSV: FIXME: Small buffer could be used and hook routine * called multiple times instead. Alternatively, the support could be * removed entirely in favor of configuring RTEMS pseudo-device with * given name. */ char *bigBufr; size_t filesize = rtems_ftpd_configuration.max_hook_filesize + 1; /* * Allocate space for our "file". */ bigBufr = (char *)malloc(filesize); if (bigBufr == NULL) { send_reply(info, 451, "Local resource failure: malloc."); close_data_socket(info); return; } /* * Retrieve the file into our buffer space. */ size = 0; while ((n = recv(s, bigBufr + size, filesize - size, 0)) > 0) { size += n; } if (size >= filesize) { send_reply(info, 451, "File too long: buffer size exceeded."); free(bigBufr); close_data_socket(info); return; } /* * Call our hook. */ res = (usehook->hook_function)(bigBufr, size) == 0; free(bigBufr); if(!res) { send_reply(info, 451, "File processing failed."); close_data_socket(info); return; } } else { /* Data transfer to regular file or /dev/null. */ int fd = 0; if(!null) fd = creat(filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (0 > fd) { send_reply(info, 550, "Error creating file."); close_data_socket(info); return; } if(info->xfer_mode == TYPE_I) { while ((n = recv(s, buf, FTPD_DATASIZE, 0)) > 0) { if (wrt(fd, buf, n) != n) { res = 0; break; } } } else if(info->xfer_mode == TYPE_A) { int rest = 0; int pended_cr = 0; while (res && rest == 0 && (n = recv(s, buf, FTPD_DATASIZE, 0)) > 0) { char const* e = buf; char const* b; int i; rest = n; if(pended_cr && *e != '\n') { char const lf = '\r'; pended_cr = 0; if(wrt(fd, &lf, 1) != 1) { res = 0; break; } } do { int count; int sub = 0; b = e; for(i = 0; i < rest; ++i, ++e) { int pcr = pended_cr; pended_cr = 0; if(*e == '\r') { pended_cr = 1; } else if(*e == '\n') { if(pcr) { sub = 2; ++i; ++e; break; } ++bare_lfs; } } if(res == 0) break; count = i - sub - pended_cr; if(count > 0 && wrt(fd, b, count) != count) { res = 0; break; } if(sub == 2 && wrt(fd, e - 1, 1) != 1) res = 0; } while((rest -= i) > 0); } } if (0 > close(fd) || res == 0) { send_reply(info, 452, "Error writing file."); close_data_socket(info); return; } } if (bare_lfs > 0) { snprintf(buf, FTPD_BUFSIZE, "Transfer complete. WARNING! %d bare linefeeds received in ASCII mode.", bare_lfs); send_reply(info, 226, buf); } else send_reply(info, 226, "Transfer complete."); close_data_socket(info); }
int main(int argc, char** argv) { struct timeval start_time, end_time; readstat_error_t error = READSTAT_OK; char *input_filename = NULL; char *catalog_filename = NULL; char *output_filename = NULL; if (argc == 2 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) { print_version(); return 0; } else if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { print_usage(argv[0]); return 0; } if (argc == 3) { if (!can_read(argv[1]) || !can_write(argv[2])) { print_usage(argv[0]); return 1; } input_filename = argv[1]; output_filename = argv[2]; } else if (argc == 4) { if (!can_read(argv[1]) || !is_catalog(argv[2]) || !can_write(argv[3])) { print_usage(argv[0]); return 1; } input_filename = argv[1]; catalog_filename = argv[2]; output_filename = argv[3]; } else { print_usage(argv[0]); return 1; } int input_format = format(input_filename); int output_format = format(output_filename); gettimeofday(&start_time, NULL); int fd = open(output_filename, O_CREAT | O_WRONLY | O_EXCL, 0644); if (fd == -1) { dprintf(STDERR_FILENO, "Error opening %s for writing: %s\n", output_filename, strerror(errno)); return 1; } readstat_parser_t *pass1_parser = readstat_parser_init(); readstat_parser_t *pass2_parser = readstat_parser_init(); readstat_writer_t *writer = readstat_writer_init(); readstat_writer_set_file_label(writer, "Created by ReadStat <https://github.com/WizardMac/ReadStat>"); rs_ctx_t *rs_ctx = ctx_init(); rs_ctx->writer = writer; rs_ctx->out_fd = fd; rs_ctx->out_format = output_format; readstat_set_data_writer(writer, &write_data); // Pass 1 - Collect fweight and value labels readstat_set_error_handler(pass1_parser, &handle_error); readstat_set_info_handler(pass1_parser, &handle_info); readstat_set_value_label_handler(pass1_parser, &handle_value_label); readstat_set_fweight_handler(pass1_parser, &handle_fweight); if (catalog_filename) { error = parse_file(pass1_parser, catalog_filename, RS_FORMAT_SAS_CATALOG, rs_ctx); } else { error = parse_file(pass1_parser, input_filename, input_format, rs_ctx); } if (error != READSTAT_OK) goto cleanup; // Pass 2 - Parse full file readstat_set_error_handler(pass2_parser, &handle_error); readstat_set_info_handler(pass2_parser, &handle_info); readstat_set_variable_handler(pass2_parser, &handle_variable); readstat_set_value_handler(pass2_parser, &handle_value); error = parse_file(pass2_parser, input_filename, input_format, rs_ctx); if (error != READSTAT_OK) goto cleanup; gettimeofday(&end_time, NULL); dprintf(STDERR_FILENO, "Converted %ld variables and %ld rows in %.2lf seconds\n", rs_ctx->var_count, rs_ctx->row_count, (end_time.tv_sec + 1e-6 * end_time.tv_usec) - (start_time.tv_sec + 1e-6 * start_time.tv_usec)); cleanup: readstat_parser_free(pass1_parser); readstat_parser_free(pass2_parser); readstat_writer_free(writer); ctx_free(rs_ctx); close(fd); if (error != READSTAT_OK) { dprintf(STDERR_FILENO, "%s\n", readstat_error_message(error)); unlink(output_filename); return 1; } return 0; }
static switch_status_t switch_console_logger(const switch_log_node_t *node, switch_log_level_t level) { FILE *handle; if (!RUNNING) { return SWITCH_STATUS_SUCCESS; } #if 0 if (failed_write) { if ((handle = switch_core_data_channel(SWITCH_CHANNEL_ID_LOG))) { int aok = can_write(handle, 100); if (aok) { const char *msg = "Failed to write to the console! Logging disabled! RE-enable with the 'console loglevel' command\n"; #ifdef WIN32 switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "%s", msg); #else if (COLORIZE) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "%s%s%s", COLORS[1], msg, SWITCH_SEQ_DEFAULT_COLOR); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "%s", msg); } #endif failed_write = 0; } } } #endif if (level > hard_log_level && (node->slevel == SWITCH_LOG_UNINIT || level > node->slevel)) { return SWITCH_STATUS_SUCCESS; } if ((handle = switch_core_data_channel(SWITCH_CHANNEL_ID_LOG))) { size_t mask = 0; size_t ok = 0; ok = switch_log_check_mask(all_level, level); if (log_hash) { if (!ok) { mask = (size_t) switch_core_hash_find(log_hash, node->file); ok = switch_log_check_mask(mask, level); } if (!ok) { mask = (size_t) switch_core_hash_find(log_hash, node->func); ok = switch_log_check_mask(mask, level); } } if (ok) { #ifndef WIN32 int aok = can_write(handle, 10000); if (!aok) { //hard_log_level = 0; //failed_write++; return SWITCH_STATUS_SUCCESS; } #endif if (COLORIZE) { #ifdef WIN32 DWORD len = (DWORD) strlen(node->data); DWORD outbytes = 0; SetConsoleTextAttribute(hStdout, COLORS[node->level]); if (log_uuid && !zstr(node->userdata)) { WriteFile(hStdout, node->userdata, (DWORD)strlen(node->userdata), &outbytes, NULL); WriteFile(hStdout, " ", 1, &outbytes, NULL); } WriteFile(hStdout, node->data, len, &outbytes, NULL); SetConsoleTextAttribute(hStdout, wOldColorAttrs); #else if (log_uuid && !zstr(node->userdata)) { fprintf(handle, "%s%s %s%s", COLORS[node->level], node->userdata, node->data, SWITCH_SEQ_DEFAULT_COLOR); } else { fprintf(handle, "%s%s%s", COLORS[node->level], node->data, SWITCH_SEQ_DEFAULT_COLOR); } #endif } else if (log_uuid && !zstr(node->userdata)) { fprintf(handle, "%s %s", node->userdata, node->data); } else { fprintf(handle, "%s", node->data); } } } return SWITCH_STATUS_SUCCESS; }
void print_dir() { FILE *fp, *popen(), *my_fopen(); WINDOW *p_win, *newwin(); char *ans, *file, *e_get_str(), buf[100], *expand(); int is_printer, i; void error_win(); unsigned int sleep(); p_win = newwin(5, 54, 0, 26); mvwaddstr(p_win, 2, 3, "Print to: (printer)"); box(p_win, VERT, HORZ); wmove(p_win, 2, 13); wrefresh(p_win); /* * This is a special version of get_str() that looks at the * first character to see if it should erase the default answer * already on the screen. */ if ((ans = e_get_str(p_win, 80)) == NULL) { /* erase because it overlaps dm_win */ werase(p_win); wrefresh(p_win); delwin(p_win); return; } file = expand(ans); is_printer = 0; /* the default (printer) */ if (*file == '\0') { if (!(fp = popen(LPRINT, "w"))) { sprintf(buf, "\"%s\"", LPRINT); error_win(0, "Can't open printer program", buf); werase(p_win); wrefresh(p_win); delwin(p_win); return; } is_printer++; } /* the requested file */ else { /* * Check to see if the file already exists (and if you * have write permission too). Currently only allows * you to bail out or overwrite the file (no append). */ switch(can_write(file)) { case DENIED: sprintf(buf, "\"%s\"", file); error_win(0, "No write permission on file", buf); werase(p_win); wrefresh(p_win); delwin(p_win); return; case OK_BUT_EXISTS: werase(p_win); mvwprintw(p_win, 2, 3, "File \"%s\" already exists!", file); beep(); box(p_win, VERT, HORZ); if (!yes_prompt(p_win, 3, 3, A_BOLD, "Overwrite")) { werase(p_win); wrefresh(p_win); delwin(p_win); return; } /* fall thru */ case WRITE_OK: if (!(fp = my_fopen(file, "w"))) { sprintf(buf, "\"%s\"", file); error_win(0, "Can't open file", buf); werase(p_win); wrefresh(p_win); delwin(p_win); return; } break; } } werase(p_win); mvwaddstr(p_win, 2, 13, "Printing Pcomm directory"); box(p_win, VERT, HORZ); wrefresh(p_win); /* * Only prints up to the end of the physical file, not the entire * structure. I gave some thought about not printing empty entries, * but... */ for (i=1; i<=dir->d_entries; i++) fprintf(fp, "%4d- %-20.20s %18.18s %5d-%c-%d-%d %c %-14.14s\n", i, dir->name[i], dir->number[i], dir->baud[i], dir->parity[i], dir->dbits[i], dir->sbits[i], dir->duplex[i], dir->script[i]); if (is_printer) pclose(fp); else { /* a dramatic delay... */ sleep(1); fclose(fp); } werase(p_win); wrefresh(p_win); delwin(p_win); return; }
int main (int argc, char **argv) { int fd, i; unsigned char axes = 2; unsigned char buttons = 2; int version = 0x000800; char name[NAME_LENGTH] = "Unknown"; uint16_t btnmap[KEY_MAX - BTN_MISC + 1]; uint8_t axmap[ABS_MAX + 1]; if (argc != 4) { puts(""); puts("Usage: jstest <device> <host> <port>"); puts(""); return 1; } if ((fd = open(argv[1], O_RDONLY)) < 0) { perror("jsrobot"); return 1; } ioctl(fd, JSIOCGVERSION, &version); ioctl(fd, JSIOCGAXES, &axes); ioctl(fd, JSIOCGBUTTONS, &buttons); ioctl(fd, JSIOCGNAME(NAME_LENGTH), name); ioctl(fd, JSIOCGAXMAP, axmap); ioctl(fd, JSIOCGBTNMAP, btnmap); printf("Driver version is %d.%d.%d.\n", version >> 16, (version >> 8) & 0xff, version & 0xff); printf("Joystick (%s) has %d axes (", name, axes); for (i = 0; i < axes; i++) printf("%s%s", i > 0 ? ", " : "", axis_names[axmap[i]]); puts(")"); printf("and %d buttons (", buttons); for (i = 0; i < buttons; i++) printf("%s%s", i > 0 ? ", " : "", button_names[btnmap[i] - BTN_MISC]); puts(")."); if (axes < 2) { printf("No enought axes.\n"); exit(0); } int *axis; char *button; struct js_event js; axis = calloc(axes, sizeof(int)); button = calloc(buttons, sizeof(char)); int sock; if ((sock = getsockfd(argv[2], argv[3])) < 0) { fprintf(stderr, "Error: getsockfd(%s,%s)\n", argv[2], argv[3]); exit(1); } pthread_t pth; pthread_create(&pth, NULL, update, &sock); while (1) { if (read(fd, &js, sizeof(struct js_event)) != sizeof(struct js_event)) { perror("\njstest: error reading"); return 1; } switch(js.type & ~JS_EVENT_INIT) { case JS_EVENT_BUTTON: button[js.number] = js.value; break; case JS_EVENT_AXIS: axis[js.number] = js.value; break; } if (button[1] && !b[1]) { b[1] = 1; can_write(sock, bin, 1051, 0); } else if (button[3] && !b[2]) { b[2] = 1; turn(sock, 0); } else if (button[3] && !b[3]) { b[3] = 1; turn(sock, 1); } else { b[1] = 0; b[2] = 0; b[3] = 0; event(axis[0], -axis[1]); } } return -1; }
int main(int argc, char* argv[]) { int i = 0; msg_type messages[4]; unsigned num_msg = sizeof(messages) / sizeof(messages[0]); struct timespec timeread; struct timespec timedelay; int fd = -1; char* port = "/dev/can1"; char line[1024]; char* read = NULL; int linenum = 0; uint8_t extended = 0; int nmax = 0; int opt = 0; int verbose = 0; // parse the command-line args while ((opt = getopt(argc, argv, "e:n:p:v:z")) != -1) { printf ("opt = %d\n", opt); switch (opt) { case 'e': extended = 1; break; case 'n': nmax = atoi(optarg); break; case 'p': port = strdup(optarg); break; case 'v': verbose = 1; break; } } memset(messages, 0, sizeof(messages)); for (i = 0; i < num_msg; ++i) { messages[i].frequency = i * 10 + 10; // 10Hz, 20Hz, 30Hz, etc... messages[i].period = 1000 / messages[i].frequency; } // read 10 lines of messages from stdin read = fgets(line, sizeof(line), stdin); while ((int)read != EOF && read != NULL) { char* token = strtok(line, " \t"); int num_msg_incoming = atoi(token); int id; // check number of messages matches the number we can store if (num_msg_incoming != num_msg) { fprintf(stderr, "number of messages don't match: %d, %d\n", num_msg_incoming, num_msg); continue; } for (i = 0; i < num_msg_incoming; i++) { msg_descriptor_t* p = NULL; uint64_t msg_raw = 0; token = strtok(NULL, " \t"); id = atoi(token); p = &msg_descriptors[id / 100 - 1]; if (messages[i].id != p->identifier) { if (messages[i].id == 0) messages[i].id = p->identifier; else { fprintf(stderr, "identifers don't match."); continue; } } msg_raw = parse_msg_input(p, NULL, NULL); messages[i].data[linenum] = msg_raw; if (verbose) { printf ("msg parsed: "); print_data(msg_raw); putchar('\n'); } } linenum++; read = fgets(line, sizeof(line), stdin); } puts("input data correctly parsed."); // initialize the timedelay structure timedelay.tv_sec = 0; timedelay.tv_nsec = 10000000; /* 10 millsecs */ // open can port fd = can_open(port, O_WRONLY); if (fd == -1) { fprintf (stderr, "error opening %s\n", port); exit(1); } printf ("can port opened. fd = %d\n", fd); // keep on sending data until someone decides to press ctrl+C for (;;) { unsigned now_ms; clock_gettime(CLOCK_REALTIME, &timeread); now_ms = timeread.tv_sec * 1000 + timeread.tv_nsec / 1000000; for (i = 0; i < num_msg; ++i) { // see how long it has been since that message was last sent unsigned long diff = now_ms - messages[i].lastsent; // if longer than period, send again if (diff >= messages[i].period) { int rand_msg = rand() % 10; can_write(fd, messages[i].id, 0, &messages[i].data[rand_msg], // pick random 8); if (verbose) { printf ("msg sent: i=%d, id=%d, msg_index=%d, data= ", i, messages[i].id, rand_msg); print_data(messages[i].data[rand_msg]); putchar('\n'); } messages[i].lastsent = now_ms; } } // sleep for 10 ms to avoid using all the cpu // nanosleep(&timedelay, NULL); } return 0; }