int exec_err(t_cpe *cpe) { int i; i = 0; if (!PRM) exit_msg(0, "", cpe); if (PRM[0] && (PRM[1] || no_digit(PRM[0]))) { ft_putendl("exit: Expression Syntax."); return (11); } else { while (PRM[0][i]) { if (!ft_isdigit(PRM[0][i])) { ft_putendl("exit: Badly formed number."); return (11); } i++; } exit_msg(ft_atoi(PRM[0]), "", cpe); } return (10); }
// // The function to open bind a socket given a port // int getSocket(const char *port) { struct addrinfo hint, *aip, *rp; int lfd, rval, optval; // initialize variables memset((void*) &hint, 0, sizeof(hint)); // provide hints to point getaddrinfo in the right direction hint.ai_family = AF_UNSPEC; // either IPv4 or IPv6 hint.ai_socktype = SOCK_STREAM; // use TCP hint.ai_flags = AI_PASSIVE; // suitable for bind printf("port = %s\n", port); getaddrinfo(NULL, port, &hint, &aip); for (rp = aip; rp != NULL; rp = rp->ai_next) { lfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (lfd == -1) continue; optval = 1; rval = setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); exit_msg(rval < 0, "setsockopt() error"); if (bind(lfd, rp->ai_addr, rp->ai_addrlen) != -1) break; // bind was successful close(lfd); } freeaddrinfo(aip); exit_msg(rp == NULL, "could not bind"); rval = listen(lfd, tcpQue); exit_msg(rval < 0, "listen() error"); if (lfd >= fd_max) fd_max = lfd + 1; return lfd; }
static void set_fork_info (TestResult * tr, int status, int signal_expected, unsigned char allowed_exit_value) { int was_sig = WIFSIGNALED (status); int was_exit = WIFEXITED (status); int exit_status = WEXITSTATUS (status); int signal_received = WTERMSIG (status); if (was_sig) { if (signal_expected == signal_received) { if (alarm_received) { /* Got alarm instead of signal */ tr->rtype = CK_ERROR; tr->msg = signal_error_msg (signal_received, signal_expected); } else { tr->rtype = CK_PASS; tr->msg = pass_msg (); } } else if (signal_expected != 0) { /* signal received, but not the expected one */ tr->rtype = CK_ERROR; tr->msg = signal_error_msg (signal_received, signal_expected); } else { /* signal received and none expected */ tr->rtype = CK_ERROR; tr->msg = signal_msg (signal_received); } } else if (signal_expected == 0) { if (was_exit && exit_status == allowed_exit_value) { tr->rtype = CK_PASS; tr->msg = pass_msg (); } else if (was_exit && exit_status != allowed_exit_value) { if (tr->msg == NULL) { /* early exit */ tr->rtype = CK_ERROR; tr->msg = exit_msg (exit_status); } else { tr->rtype = CK_FAILURE; } } } else { /* a signal was expected and none raised */ if (was_exit) { tr->msg = exit_msg (exit_status); if (exit_status == allowed_exit_value) tr->rtype = CK_FAILURE; /* normal exit status */ else tr->rtype = CK_FAILURE; /* early exit */ } } }
int WAV_OUT::write_current_output(double ooo) { if(this->num_ch!=1) exit_msg(-581,"attempt to write to a stereo file with mono-write method"); if(fw==NULL) exit_msg(-583,"not ready for WAV write"); // convert data double ttt; double max_uuu = (65536.0 / 2.0) - 1.0; double min_uuu = -(65536.0 / 2.0); double max_ccc = 256.0; double min_ccc = 0.0; int wstat; short int sidata; unsigned char ucdata; if(bits_per_sample == 16) { ttt = ooo; if(ttt>max_uuu) ttt = max_uuu; if(ttt<min_uuu) ttt = min_uuu; sidata = (short int) (ttt + 0.5); wstat = fwrite((void *)(&sidata),sizeof(short int),(size_t)1,fw); if(wstat!=1) exit_msg(-376,"cant write WAV_OUT"); } else if(bits_per_sample == 8) { ttt = ooo; if(ttt>max_ccc) ttt = max_ccc; if(ttt<min_ccc) ttt = min_ccc; ucdata = (unsigned char) (ttt + 0.5); wstat = fwrite((void *)(&ucdata),sizeof(unsigned char),(size_t)1,fw); if(wstat!=1) exit_msg(-376,"cant write WAV_OUT"); } else exit_msg(-376,"bunk bits_per_sample"); // another sample saved g_num_osamp += 1; // be polite return 1; /* int WAV_OUT::write(double ooo) */}
// // The function to wait for a client connection // void wait_connect( ) { //struct addrinfo * rp; struct timeval tv; int lfd, rval; do { FD_ZERO(&r_fds); /* reset fds from s_fds */ for (lfd = 3; lfd < fd_max; lfd++) { if (FD_ISSET(lfd, &s_fds)) { FD_SET(lfd, &r_fds); } } tv.tv_sec = 15; tv.tv_usec = 0; rval = select(fd_max, &r_fds, NULL, NULL, &tv); exit_msg(rval < 0, "select() error"); waitpid(-1, NULL, WNOHANG); if (rval == 0) continue; /* need to figure out what to accept */ for (lfd = 3; lfd < fd_max; lfd++) { if (FD_ISSET(lfd, &r_fds)) { accept_connection(lfd); } } } while ( 1 ); printf("%5d: Server exiting.\n", getpid()); }
//接口 void rpcudp::close() { #ifdef _LOG_RPCUDP_RUNNING mylog.log(log_debug, "rpcudp deconstruct"); #endif complete_result exit_msg( io_complete_port::complete_port_exit, 0, nullptr); _recvport.close(); _process_port.close(); #ifdef _WINDOWS if (_udpsock != SOCKET_ERROR) closesocket(_udpsock); kernel_handle handles[2] = { _recv_thread_handle, _process_thread }; WaitForMultipleObjects(2, handles, TRUE, INFINITE); CloseHandle(_recv_thread_handle); CloseHandle(_process_thread); for (auto iter = _clients.begin(); iter != _clients.end(); ++iter) { delete iter->second; } _ack_timer.stop(); _timer.stop(); #else #endif }
static unsigned char * message_load(size_t *message_len, const char *message_file, int hashed) { FILE *fp; unsigned char *message; off_t message_len_; if (hashed != 0) { return message_load_hashed(message_len, message_file); } if ((fp = fopen(message_file, "rb")) == NULL || fseeko(fp, 0, SEEK_END) != 0 || (message_len_ = ftello(fp)) == (off_t) -1) { exit_err(message_file); } if (hashed == 0 && message_len_ > (off_t) 1L << 30) { exit_msg("Data has to be smaller than 1 Gb. Or use the -H option."); } if ((uintmax_t) message_len_ > (uintmax_t) SIZE_MAX || message_len_ < (off_t) 0) { abort(); } message = xmalloc((*message_len = (size_t) message_len_)); rewind(fp); if (fread(message, *message_len, (size_t) 1U, fp) != 1U) { exit_err(message_file); } xfclose(fp); return message; }
int main(int argc, char *argv[]) { Irc freenode; struct pollfd pfd[4]; int i, ready, murm_listenfd = -1; initialize(argc, argv); for (i = 0; i < SIZE(pfd); i++) { pfd[i].fd = -1; pfd[i].events = POLLIN; } if (add_murmur_callbacks(cfg.murmur_port)) pfd[MURM_LISTEN].fd = murm_listenfd = sock_listen(LOCALHOST, CB_LISTEN_PORT_S); else fprintf(stderr, "Could not connect to Murmur\n"); if ((pfd[MPD].fd = mpdfd = mpd_connect(cfg.mpd_port)) < 0) fprintf(stderr, "Could not connect to MPD\n"); // Connect to server and set IRC details if (!(freenode = irc_connect(cfg.server, cfg.port))) exit_msg("Irc connection failed"); pfd[IRC].fd = get_socket(freenode); set_nick(freenode, cfg.nick); set_user(freenode, cfg.user); for (i = 0; i < cfg.channels_set; i++) join_channel(freenode, cfg.channels[i]); while ((ready = poll(pfd, SIZE(pfd), TIMEOUT)) > 0) { // Keep reading & parsing lines as long the connection is active and act on any registered actions found if (pfd[IRC].revents & POLLIN) while (parse_irc_line(freenode) > 0); if (pfd[MURM_LISTEN].revents & POLLIN) if ((pfd[MURM_ACCEPT].fd = accept_murmur_connection(murm_listenfd)) > 0) pfd[MURM_LISTEN].fd = -1; // Stop listening for connections if (pfd[MURM_ACCEPT].revents & POLLIN) { if (!listen_murmur_callbacks(freenode, pfd[MURM_ACCEPT].fd)) { pfd[MURM_ACCEPT].fd = -1; pfd[MURM_LISTEN].fd = murm_listenfd; // Start listening again for Murmur connections } } if (pfd[MPD].revents & POLLIN) if (!print_song(freenode, default_channel(freenode))) pfd[MPD].fd = mpdfd = mpd_connect(cfg.mpd_port); } // If we reach here, it means we got disconnected from server. Exit with error (1) if (ready == -1) perror("poll"); else fprintf(stderr, "%d minutes passed without getting a message, exiting...\n", TIMEOUT / 1000 / 60); quit_server(freenode, cfg.quit_msg); cleanup(); return 1; }
static PubkeyStruct * pubkey_load_string(const char *pubkey_s) { PubkeyStruct *pubkey_struct; size_t pubkey_struct_len; pubkey_struct = xmalloc(sizeof *pubkey_struct); if (b64_to_bin((unsigned char *) (void *) pubkey_struct, pubkey_s, sizeof *pubkey_struct, strlen(pubkey_s), &pubkey_struct_len) == NULL || pubkey_struct_len != sizeof *pubkey_struct) { exit_msg("base64 conversion failed"); } if (memcmp(pubkey_struct->sig_alg, SIGALG, sizeof pubkey_struct->sig_alg) != 0) { exit_msg("Unsupported signature algorithm"); } return pubkey_struct; }
void command_strobe(void) { show_delta_time(); output("command %02X: %s (%s)\n", regnum, command_strobes[regnum-0x30].name, command_strobes[regnum-0x30].descr); if (regnum == 0x30) { // chip reset: mark in the packet stream if (packet.length != 0) exit_msg("reset with packet length not zero", packet.length); // not interesting, because it happens too often: packet_decode(); } if (receive_enable_packet && regnum == 0x34) { // enable RX: create pseudo-packet entry in the log fprintf(pktfile, "%3ld.%06d sec ", packet.delta_time_usec/1000000, (packet.delta_time_usec%1000000)); fprintf(pktfile, "rcv enable on chan %02X sync %02X %02X\n", current_config_regs[0x0A], current_config_regs[0x04], current_config_regs[0x05]); packet.delta_time_usec = 0; } }
int WAV_OUT::write_current_output(double left,double right) { if(this->num_ch!=2) exit_msg(-587,"attempt to write to a mono file with stereo-write method"); int wstat; this->num_ch = 1; write_current_output(left); wstat = write_current_output(right); this->num_ch = 2; return wstat; }
// // Main // int main(int argc, char *argv[]) { int lfd, i, opt, len; FD_ZERO(&s_fds); fd_max = 0; while(-1 != (opt = getopt_long(argc, argv, "hp:r:", long_opts, &i)) ) { switch (opt) { case 'h': usage(argv[0]); break; case 'p': // open ports if ((atoi(optarg) > 65535) || (atoi (optarg) < 1)) { fprintf(stderr, "bad port number: (1-65535)\n"); exit(0); } lfd = getSocket(optarg); // getSocket handles errors internally printf(" - lfd = %d fd_max = %d\n", lfd, fd_max); FD_SET(lfd, &s_fds); break; case 'r': // set root exit_msg(access(optarg, F_OK) , "Root directory not found"); server_root = optarg; break; default: fprintf(stderr, "Invalid option.\n"); usage(argv[0]); break; } } // while for long_opts if (fd_max == 0) { lfd = getSocket(DEFAULT_PORT); FD_SET(lfd, &s_fds); } // for consistency ensure server root ends with '/' len = strlen(server_root); if (server_root[len-1] != '/') strncat(server_root, "/", len); printf("Starting web server at %s \n", server_root); wait_connect( ); return 0; }
// // The fuction to accept a client connection // void accept_connection(int lfd) { int cfd, pid; //accept cfd = accept(lfd, NULL, NULL); exit_msg(cfd < 0, "accept() error"); printf("%5d: Accepted connection.\n", getpid()); if ((pid = fork()) == 0) { /* in child */ close(lfd); printf("%5d: Handling connection.\n", getpid()); handle_connection(cfd); printf("%5d: Done.\n", getpid()); exit(0); } /* in parent */ close(cfd); }
// // The function to handle a client connection // void handle_connection(int fd) { http_req req; FILE *rx, *tx; exit_msg((fd < 0) || (fd > FD_SETSIZE), "bad fd"); // for streams with sockets, need one for read and one for write rx = fdopen(fd, "r"); tx = fdopen(dup(fd), "w"); init_req(&req); http_get_request(rx, &req); http_process_request(&req); http_response(tx, &req); shutdown(fileno(rx), SHUT_RDWR); fclose(rx); fclose(tx); free_req(&req); return; }
int sock_connect(const char *address, const char *port) { int sock, ret_value; struct addrinfo addr_filter, *addr_holder, *addr_iterator; // Create filter for getaddrinfo() memset(&addr_filter, 0, sizeof(addr_filter)); addr_filter.ai_family = AF_UNSPEC; // IPv4 or IPv6 addr_filter.ai_socktype = SOCK_STREAM; // Stream socket addr_filter.ai_protocol = IPPROTO_TCP; // TCP protocol // Don't try to resolve service -> port, since we already provide it in numeric form addr_filter.ai_flags |= AI_NUMERICSERV; // Return addresses according to the filter criteria ret_value = getaddrinfo(address, port, &addr_filter, &addr_holder); if (ret_value != 0) exit_msg("getaddrinfo: %s", gai_strerror(ret_value)); sock = -1; for (addr_iterator = addr_holder; addr_iterator != NULL; addr_iterator = addr_holder->ai_next) { // Create TCP socket sock = socket(addr_iterator->ai_family, addr_iterator->ai_socktype, addr_iterator->ai_protocol); if (sock < 0) continue; // Failed, try next address ret_value = connect(sock, addr_iterator->ai_addr, addr_iterator->ai_addrlen); if (ret_value == 0) break; // Success close(sock); // Cleanup and try next address sock = -1; } freeaddrinfo(addr_holder); return sock; }
// // Reads in all the headers sent by the client // and uses them to populate req // int http_get_request(FILE *stream, http_req *req) { int len, rval, lineno, fd; char *ptr, *val, buf[MAX_REQUEST_LEN]; fd_set fds; struct timeval tv; // initialize fd = fileno(stream); tv.tv_sec = CLIENT_TIMEOUT; tv.tv_usec = 0; lineno = 0; // Just get the first line of the request. The // first line contains the essential URI request, // and contains enough information to distinguish between // full and simple requests. // // Simple-Request = "GET" SP Request-URI CRLF // Full-Request = Method SP Request-URI SP HTTP-Version CRLF // *(General-Header | Request-Header | Entity-Header) // CRLF // [Entity-Body] FD_ZERO(&fds); FD_SET(fd, &fds); rval = select(fd + 1, &fds, NULL, NULL, &tv); exit_msg(rval < 0, "select() error"); if (rval == 0) return -1; fgets(buf, sizeof(buf), stream); ptr = buf; lineno++; // "GET" SP Request-URI CRLF // Method SP Request-URI SP HTTP-Version CRLF if (lineno == 1) { if (strncmp(ptr, "GET ", 4) == 0) { req->method = GET; ptr += 4; } else if (strncmp(ptr, "HEAD ", 5) == 0) { req->method = HEAD; ptr += 5; } else { req->method = UNSUPPORTED; req->status = NOT_IMPLEMENTED; return -1; } // skip SP while (*ptr && isspace(*ptr)) ptr++; // Request-URI val = strchr(ptr, ' '); if (!val) len = strlen(ptr); else len = val - ptr; if (len < 1) { req->status = BAD_REQUEST; return -1; } req->resource = malloc(len+1); if (req->resource == NULL) { req->status = INTERNAL_ERROR; return -1; } memset(req->resource, '\0', len+1); strncpy(req->resource, ptr, len); // HTTP-Version present? if (strstr(ptr, "HTTP/")) req->type = FULL; else req->type = SIMPLE; } else { // we are going to ignore the value of subsequent headers // but this is where we would process them } return 0; }
int main(int argc,char *argv[]) { int argno; fprintf(stderr, "SPI decoder, V%s\n", VERSION); argno = HandleOptions(argc,argv); if (fileread) { if ((datfile = fopen(DATFILENAME,"r")) == NULL) // opne to read from .dat file fatal_err(DATFILENAME " open for read failed"); fprintf(stderr, "Reading from " DATFILENAME "\n"); } else { char dev_name[80]; sprintf(dev_name, "\\\\.\\COM%d", comport); fprintf(stderr, "Opening serial port on %s...", dev_name); handle_serial = CreateFile(dev_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (handle_serial!=INVALID_HANDLE_VALUE) { dcbSerialParams.BaudRate = 115200; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; dcbSerialParams.DCBlength = sizeof(DCB); if(SetCommState(handle_serial, &dcbSerialParams) == 0) fatal_err("Error setting serial port parameters"); timeouts.ReadIntervalTimeout = 100; // msec timeouts.ReadTotalTimeoutConstant = 200; // msec timeouts.ReadTotalTimeoutMultiplier = 0; // msec timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; if(SetCommTimeouts(handle_serial, &timeouts) == 0) fatal_err("Error setting serial port timeouts"); fprintf(stderr,"OK\n"); } else fatal_err("Failed"); if ((datfile = fopen(DATFILENAME,"a")) == NULL) // open to append to .dat file fatal_err(DATFILENAME " open for append failed"); } if ((outfile = fopen(OUTFILENAME,"a")) == NULL) fatal_err(OUTFILENAME " open failed"); if ((pktfile = fopen(PKTFILENAME,"a")) == NULL) fatal_err(PKTFILENAME " open failed"); fprintf(pktfile, "\n"); // atexit(cleanup); fprintf(stderr, "Starting.\n"); while(!kbhit()) { more_data: if (fileread) { // read from .dat file if (!fgets(line, MAX_LINE, datfile)) { output("***end of file"); fprintf(stderr, "***end of file"); cleanup(); exit(0); } ++linecnt; bytes_read = strlen(line); output("got %d bytes from the file\n", bytes_read); } else { // read from serial port // printf("reading serial port com%d...\n", comport); ReadFile(handle_serial, line, MAX_LINE, &bytes_read, NULL); line[bytes_read]='\0'; if (bytes_read != 0) { output("got %d bytes from serial port\n", bytes_read); fprintf(stderr, "got %d bytes from the serial port\n", bytes_read); fprintf(datfile, "%s\n", line); } } if (strcmp(line, "SPI Sniffer\n") == 0) { fprintf(stderr, "\"SPI Sniffer\" header line read\n"); continue; } // output("decode %n bytes: %s\n", bytes_read, line); lineptr = line; while (*lineptr != '\0') { skip_to_next_data(); // process input up to next master/slave data pair if (*lineptr == '\0')break; next_command: if (!read_data_pair()) goto more_data; isread = master_data & 0x80; // "read register" flag bit isburst = master_data & 0x40; // "burst" flag bit regnum = master_data & 0x3f; // register number 0 to 63 if (isread) { // config register read if (regnum >= 0x30 && regnum <= 0x3d && !isburst) { // no, is really command strobe command_strobe(); } else { if(isburst){ if (regnum == 0x3f) { // read RX FIFO: receive packet if (!chip_selected) exit_msg("burst RX FIFO write without chip selected", regnum); show_config_reg("read", true); packet.xmit = false; while (1) { // show all burst read data from FIFO if (!skip_timestamp()) goto next_command; if (*lineptr == ']') break; // ends with chip unselect if (!read_data_pair()) goto next_command; output(" %02X", slave_data); if (packet.length < MAX_PKT) { packet.data[packet.length++] = slave_data; } } output("\n"); packet_decode(); } else { // burst read of other than FIFO: consecutive config registers if (!skip_to_next_data()) goto next_command; while (1) { if (!skip_timestamp()) goto next_command; if (*lineptr == ']') break; // ends with chip unselect if (!read_data_pair()) goto next_command; regval = slave_data; show_config_reg("read", false); if (++regnum >= 0x40) exit_msg("burst read of too many config registers", regnum); } } } else { // regular single-register read if (!read_data_pair()) goto next_command; regval = slave_data; show_config_reg("read", false); } } } else { // register write if (regnum >= 0x30 && regnum <= 0x3d && !isburst) { // no, is really command strobe command_strobe(); } else if (regnum == 0x3e) { // write power table if (isburst) { if (!chip_selected) exit_msg("burst power table write without chip selected", regnum); show_config_reg("write", true); while (1) { // show all burst write data to power table if (!skip_timestamp()) goto next_command; if (*lineptr == ']') break; // ends with chip unselect if (!read_data_pair()) goto next_command; output(" %02X", master_data); } output("\n"); } else { // non-burst write to power table if (!read_data_pair()) goto next_command; regval = master_data; show_config_reg("write", false); } } else if (regnum == 0x3f) { // write TX FIFO: transmit packet if (!isburst) exit_msg("implement non-burst TX FIFO write", regnum); if (!chip_selected) exit_msg("burst TX FIFO write without chip selected", regnum); show_config_reg("write", true); packet.xmit = true; while (1) { // show all burst write data to FIFO if (!skip_timestamp()) goto next_command; if (*lineptr == ']') break; // ends with chip unselect if (!read_data_pair()) goto next_command; output(" %02X", master_data); if (packet.length < MAX_PKT) { packet.data[packet.length++] = master_data; } } output("\n"); packet_decode(); } else { // writing config register(s) if (isburst) { // burst config register write int bytes_bursted, bytes_changed, start_reg, end_reg; bytes_bursted = 0; bytes_changed = 0; start_reg = regnum; // output("burst config write\n"); if (!chip_selected) output("burst write without chip selected at reg %02X", regnum); while (1) { // read all the burst write data if (!skip_timestamp()) goto next_command; if (*lineptr == ']') break; // ends with chip unselect if (regnum > 0x2e) exit_msg("too much burst data", regnum); if (!read_data_pair()) goto next_command; new_config_regs[regnum++] = master_data; ++bytes_bursted; } end_reg = regnum-1; for (regnum=start_reg; regnum<end_reg; ++regnum) { // show only those that changed if ((new_config_regs[regnum] != current_config_regs[regnum])) { regval = new_config_regs[regnum]; show_config_reg(" wrote", false); current_config_regs[regnum] = new_config_regs[regnum]; ++bytes_changed; } } show_delta_time(); output(" burst wrote %d registers, and %d changed\n", bytes_bursted, bytes_changed); } else { // single register write if (!read_data_pair()) goto next_command; regval = master_data; show_config_reg("write", false); current_config_regs[regnum] = regval; } } } } } return 0; }
int WAV_OUT::create_wave_file(const char *fname) { unsigned int wstat; int i; char obuff[80]; WAV_HDR *wav; CHUNK_HDR *chk; int wbuff_len; // allocate wav header wav = new WAV_HDR; chk = new CHUNK_HDR; if(wav==NULL) exit_msg(-376,"cant new headers"); if(chk==NULL) exit_msg(-376,"cant new headers"); // setup size - just assume 1 second length for now! wbuff_len = ((int) fs_hz) * bits_per_sample / 8; // setup wav header sprintf(obuff,"RIFF"); for(i=0;i<4;i++) wav->rID[i] = obuff[i]; sprintf(obuff,"WAVE"); for(i=0;i<4;i++) wav->wID[i] = obuff[i]; sprintf(obuff,"fmt "); for(i=0;i<4;i++) wav->fId[i] = obuff[i]; wav->nBitsPerSample = bits_per_sample; wav->nSamplesPerSec = (int) fs_hz; wav->nAvgBytesPerSec = (int) fs_hz; wav->nAvgBytesPerSec *= bits_per_sample / 8; wav->nAvgBytesPerSec *= num_ch; wav->nChannels = num_ch; wav->pcm_header_len = 16; wav->wFormatTag = 1; wav->rLen = sizeof(WAV_HDR) + sizeof(CHUNK_HDR) + wbuff_len; wav->nBlockAlign = num_ch * bits_per_sample / 8; // setup chunk header sprintf(obuff,"data"); for(i=0;i<4;i++) chk->dId[i] = obuff[i]; chk->dLen = wbuff_len; // save (file) offsets for later size updates // header_offset_rlen = ((int) &(wav->rLen)); // header_offset_rlen -= ((int) wav); header_offset_rlen = 4; // header_offset_dlen = ((int) &(chk->dLen)) - ((int) chk); // header_offset_dlen += sizeof(WAV_HDR); header_offset_dlen = sizeof(WAV_HDR) + 4; /* open wav file */ fw = fopen(fname,"wb"); if(fw==NULL) exit_msg(-371,"cant open wav file for create"); /* write riff/wav header */ wstat = fwrite((void *)wav,sizeof(WAV_HDR),(size_t)1,fw); if(wstat!=1) exit_msg(-376,"cant write wav"); /* write chunk header */ wstat = fwrite((void *)chk,sizeof(CHUNK_HDR),(size_t)1,fw); if(wstat!=1) exit_msg(-377,"cant write chk"); // reset output stream index g_num_osamp = 0; // copy file name fname_copy = new char [strlen(fname)+1]; if(fname_copy==NULL) exit_msg(-378,"cant create string buffer for fname"); fname_copy[0] = 0; strcpy(fname_copy, fname); // be polite if(wav!=NULL) delete wav; if(chk!=NULL) delete chk; return 1; /* int WAV_OUT::create_wave_file(char *fname) */}
int WAV_OUT::save_wave_file(const char *fname) { unsigned int wstat; int wbuff_len; int rlen_data; int dlen_data; if(fw==NULL) return 0; if(g_num_osamp<=0) exit_msg(-980,"warning, no new data written to output"); // find correct lengths wbuff_len = g_num_osamp * bits_per_sample / 8; rlen_data = sizeof(WAV_HDR) + sizeof(CHUNK_HDR) + wbuff_len; dlen_data = wbuff_len; // close and re-open file fclose(fw); fw = fopen(fname,"rb+"); if(fw==NULL) exit_msg(-372,"cant open wav file to finalize via read/write"); // seek file positions and overwrite length data wstat = fseek(fw,header_offset_rlen,SEEK_SET); if(wstat!=0) exit_msg(-377,"cant fseek test file"); wstat = fwrite((void *)&rlen_data,sizeof(int),1,fw); if(wstat!=1) exit_msg(-371,"cant re-write header (1)"); wstat = fseek(fw,header_offset_dlen,SEEK_SET); if(wstat!=0) exit_msg(-377,"cant fseek test file"); wstat = fwrite((void *)&dlen_data,sizeof(int),1,fw); if(wstat!=1) exit_msg(-371,"cant re-write header (2)"); // close file, final fclose(fw); /* printf("\nCreated WAV File: %s\n",fname); printf(" Fs = %1.0lf Hz,",fs_hz); if(num_ch==2) printf(" # Samples (Saved as Stereo Pairs) = %d,",g_num_osamp/num_ch); else printf(" # Samples (Mono) = %d,",g_num_osamp/num_ch); printf(" Bits Per Sample = %d\n",bits_per_sample); */ // reset output stream index g_num_osamp = 0; fw = NULL; return 1; /* int WAV_OUT::save_wave_file(char *fname) */}
static int generate(const char *pk_file, const char *sk_file, const char *comment) { char *pwd = xsodium_malloc(PASSWORDMAXBYTES); char *pwd2 = xsodium_malloc(PASSWORDMAXBYTES); SeckeyStruct *seckey_struct = xsodium_malloc(sizeof(SeckeyStruct)); PubkeyStruct *pubkey_struct = xsodium_malloc(sizeof(PubkeyStruct)); unsigned char *stream ; FILE *fp; randombytes_buf(seckey_struct->keynum_sk.keynum, sizeof seckey_struct->keynum_sk.keynum); crypto_sign_keypair(pubkey_struct->keynum_pk.pk, seckey_struct->keynum_sk.sk); memcpy(seckey_struct->sig_alg, SIGALG, sizeof seckey_struct->sig_alg); memcpy(seckey_struct->kdf_alg, KDFALG, sizeof seckey_struct->kdf_alg); memcpy(seckey_struct->chk_alg, CHKALG, sizeof seckey_struct->chk_alg); randombytes_buf(seckey_struct->kdf_salt, sizeof seckey_struct->kdf_salt); le64_store(seckey_struct->kdf_opslimit_le, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE); le64_store(seckey_struct->kdf_memlimit_le, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE); seckey_chk(seckey_struct->keynum_sk.chk, seckey_struct); memcpy(pubkey_struct->keynum_pk.keynum, seckey_struct->keynum_sk.keynum, sizeof pubkey_struct->keynum_pk.keynum); memcpy(pubkey_struct->sig_alg, SIGALG, sizeof pubkey_struct->sig_alg); puts("Please enter a password to protect the secret key.\n"); if (get_password(pwd, PASSWORDMAXBYTES, "Password: "******"Password (one more time): ") != 0) { exit_msg("get_password()"); } if (strcmp(pwd, pwd2) != 0) { exit_msg("Passwords don't match"); } printf("Deriving a key from the password in order to encrypt the secret key... "); fflush(stdout); stream = xsodium_malloc(sizeof seckey_struct->keynum_sk); if (crypto_pwhash_scryptsalsa208sha256 (stream, sizeof seckey_struct->keynum_sk, pwd, strlen(pwd), seckey_struct->kdf_salt, le64_load(seckey_struct->kdf_opslimit_le), le64_load(seckey_struct->kdf_memlimit_le)) != 0) { abort(); } sodium_free(pwd); sodium_free(pwd2); xor_buf((unsigned char *) (void *) &seckey_struct->keynum_sk, stream, sizeof seckey_struct->keynum_sk); sodium_free(stream); puts("done\n"); if ((fp = fopen_create_useronly(sk_file)) == NULL) { exit_err(sk_file); } xfprintf(fp, "%s%s\n", COMMENT_PREFIX, comment); xfput_b64(fp, (unsigned char *) (void *) seckey_struct, sizeof *seckey_struct); xfclose(fp); sodium_free(seckey_struct); if ((fp = fopen(pk_file, "w")) == NULL) { exit_err(pk_file); } xfprintf(fp, COMMENT_PREFIX "minisign public key %" PRIX64 "\n", le64_load(pubkey_struct->keynum_pk.keynum)); xfput_b64(fp, (unsigned char *) (void *) pubkey_struct, sizeof *pubkey_struct); xfclose(fp); printf("The secret key was saved as %s - Keep it secret!\n", sk_file); printf("The public key was saved as %s - That one can be public.\n\n", pk_file); puts("Files signed using this key pair can be verified with the following command:\n"); printf("minisign -Vm <file> -P "); xfput_b64(stdout, (unsigned char *) (void *) pubkey_struct, sizeof *pubkey_struct); puts(""); sodium_free(pubkey_struct); return 0; }
static int sign(const char *sk_file, const char *message_file, const char *sig_file, const char *comment, const char *trusted_comment, int hashed) { unsigned char global_sig[crypto_sign_BYTES]; SigStruct sig_struct; FILE *fp; SeckeyStruct *seckey_struct; unsigned char *message; unsigned char *sig_and_trusted_comment; size_t comment_len; size_t trusted_comment_len; size_t message_len; seckey_struct = seckey_load(sk_file); message = message_load(&message_len, message_file, hashed); if (hashed != 0) { memcpy(sig_struct.sig_alg, SIGALG_HASHED, sizeof sig_struct.sig_alg); } else { memcpy(sig_struct.sig_alg, SIGALG, sizeof sig_struct.sig_alg); } memcpy(sig_struct.keynum, seckey_struct->keynum_sk.keynum, sizeof sig_struct.keynum); crypto_sign_detached(sig_struct.sig, NULL, message, message_len, seckey_struct->keynum_sk.sk); free(message); if ((fp = fopen(sig_file, "w")) == NULL) { exit_err(sig_file); } comment_len = strlen(comment); assert(strrchr(comment, '\r') == NULL && strrchr(comment, '\n') == NULL); assert(COMMENTMAXBYTES > sizeof COMMENT_PREFIX); if (comment_len >= COMMENTMAXBYTES - sizeof COMMENT_PREFIX) { fprintf(stderr, "Warning: comment too long. " "This breaks compatibility with signify.\n"); } xfprintf(fp, "%s%s\n", COMMENT_PREFIX, comment); xfput_b64(fp, (unsigned char *) (void *) &sig_struct, sizeof sig_struct); xfprintf(fp, "%s%s\n", TRUSTED_COMMENT_PREFIX, trusted_comment); trusted_comment_len = strlen(trusted_comment); assert(strrchr(trusted_comment, '\r') == NULL && strrchr(trusted_comment, '\n') == NULL); if (trusted_comment_len >= TRUSTEDCOMMENTMAXBYTES - sizeof TRUSTED_COMMENT_PREFIX) { exit_msg("Trusted comment too long"); } sig_and_trusted_comment = xmalloc((sizeof sig_struct.sig) + trusted_comment_len); memcpy(sig_and_trusted_comment, sig_struct.sig, sizeof sig_struct.sig); memcpy(sig_and_trusted_comment + sizeof sig_struct.sig, trusted_comment, trusted_comment_len); crypto_sign_detached(global_sig, NULL, sig_and_trusted_comment, (sizeof sig_struct.sig) + trusted_comment_len, seckey_struct->keynum_sk.sk); sodium_free(seckey_struct); xfput_b64(fp, (unsigned char *) (void *) &global_sig, sizeof global_sig); free(sig_and_trusted_comment); xfclose(fp); return 0; }
static SeckeyStruct * seckey_load(const char *sk_file) { char sk_comment[COMMENTMAXBYTES]; unsigned char chk[crypto_generichash_BYTES]; SeckeyStruct *seckey_struct; FILE *fp; char *pwd = xsodium_malloc(PASSWORDMAXBYTES); char *seckey_s; unsigned char *stream; size_t seckey_s_size; size_t seckey_struct_len; if ((fp = fopen(sk_file, "r")) == NULL) { exit_err(sk_file); } if (fgets(sk_comment, (int) sizeof sk_comment, fp) == NULL) { exit_err(sk_file); } sodium_memzero(sk_comment, sizeof sk_comment); seckey_s_size = B64_MAX_LEN_FROM_BIN_LEN(sizeof *seckey_struct) + 2U; seckey_s = xsodium_malloc(seckey_s_size); seckey_struct = xsodium_malloc(sizeof *seckey_struct); if (fgets(seckey_s, (int) seckey_s_size, fp) == NULL) { exit_err(sk_file); } trim(seckey_s); xfclose(fp); if (b64_to_bin((unsigned char *) (void *) seckey_struct, seckey_s, sizeof *seckey_struct, strlen(seckey_s), &seckey_struct_len) == NULL || seckey_struct_len != sizeof *seckey_struct) { exit_msg("base64 conversion failed"); } sodium_free(seckey_s); if (memcmp(seckey_struct->sig_alg, SIGALG, sizeof seckey_struct->sig_alg) != 0) { exit_msg("Unsupported signature algorithm"); } if (memcmp(seckey_struct->kdf_alg, KDFALG, sizeof seckey_struct->kdf_alg) != 0) { exit_msg("Unsupported key derivation function"); } if (memcmp(seckey_struct->chk_alg, CHKALG, sizeof seckey_struct->chk_alg) != 0) { exit_msg("Unsupported checksum function"); } if (get_password(pwd, PASSWORDMAXBYTES, "Password: "******"get_password()"); } printf("Deriving a key from the password and decrypting the secret key... "); fflush(stdout); stream = xsodium_malloc(sizeof seckey_struct->keynum_sk); if (crypto_pwhash_scryptsalsa208sha256 (stream, sizeof seckey_struct->keynum_sk, pwd, strlen(pwd), seckey_struct->kdf_salt, le64_load(seckey_struct->kdf_opslimit_le), le64_load(seckey_struct->kdf_memlimit_le)) != 0) { abort(); } sodium_free(pwd); xor_buf((unsigned char *) (void *) &seckey_struct->keynum_sk, stream, sizeof seckey_struct->keynum_sk); sodium_free(stream); puts("done\n"); seckey_chk(chk, seckey_struct); if (memcmp(chk, seckey_struct->keynum_sk.chk, sizeof chk) != 0) { exit_msg("Wrong password for that key"); } sodium_memzero(chk, sizeof chk); return seckey_struct; }
int main(int argc, char **argv) { // _MM_ROUND_NEAREST // _MM_ROUND_DOWN // _MM_ROUND_UP // _MM_ROUND_TOWARD_ZERO // _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); if (argc != 5) { printf("Invalid arguments\n"); printf("\tprogram height width ix iy\n"); exit(EXIT_FAILURE); } struct timeval t, t2; int height = atoi(argv[1]), width = atoi(argv[2]); float ix = atof(argv[3]), //zoom en x iy = atof(argv[4]); //zoom en y int delay = 2; short *mirror = NULL; //donde dira el padre que empieza el espejo global short *scale = NULL; //donde dira el padre que hay que guardar las cosas //Las dos siguientes las modifica MPI int nprocs, myid; MPI_Init(&argc, &argv);//inicializamos mpi MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); int aux_rows[nprocs];//Las filas con las que trabajara cada proceso int size_send_child[nprocs];//El numero de elementos a enviar a cada hijo int aux_split[nprocs];//Es para saber donde empezar a contar (este es para enviar a los hijos) int size_send_dad[nprocs]; //para saber el tamano que se le va a enviar al padre int aux_begin[nprocs]; //Es el para saber donde empezar a contar (este es para enviar al padre) //Con esto indicamos que todos saben lo que tienen todos fill_aux_rows(aux_rows, nprocs, height, delay); fill_size_send_child(size_send_child, nprocs, aux_rows, width, delay); fill_aux_split(aux_split, nprocs, size_send_child[0], width, delay); fill_size_send_dady(size_send_dad, nprocs, aux_rows, width, ix, iy, delay); fill_aux_begin(aux_begin, nprocs, size_send_dad[0]); if (myid == 0) {//Parent process short *originalImage = malloc(sizeof(short) * height * width); //Imagen original mirror = malloc(sizeof(short) * (height+delay*2) * (width+delay*2)); //Imagen en espejo if (originalImage == NULL || mirror == NULL) { exit_msg("main: cannot allocate memory", myid); } getImage(originalImage, height, width); getMirror(originalImage, mirror, height, width, delay); free(originalImage); gettimeofday(&t, NULL);//Empezamos a contar el tiempo } short *work = malloc(sizeof(short) * (aux_rows[myid]) * (width+2*delay) ); //con la que trabajara cada proceso if (work == NULL) exit_msg("main: cannot allocate memory (for work)", myid); //Enviamos a los procesos la informacion if (0 != MPI_Scatterv(mirror, size_send_child, aux_split, MPI_SHORT, work, size_send_child[myid], MPI_SHORT, 0, MPI_COMM_WORLD)) exit_msg("main: MPI_Scatterv", myid); short *result = malloc(sizeof(short) * ((int) ((aux_rows[myid]-2*delay)*iy)) * (int) (width*ix)); if (result == NULL) exit_msg("main: cannot allocate memory (for result)", myid); getScale(work, result, aux_rows[myid]-2*delay, width, delay, ix, iy); free(work); if (myid == 0) { free(mirror); scale = malloc(sizeof(short) * ((int) (height*iy)) * ((int) (width*ix))); // donde se guardara el resultado final } //Los procesos envian la informacion al padre if (0 != MPI_Gatherv(result, size_send_dad[myid], MPI_SHORT, scale, size_send_dad, aux_begin, MPI_SHORT, 0, MPI_COMM_WORLD)) exit_msg("main: MPI_Gatherv", myid); if (myid == 0) { gettimeofday(&t2, NULL); struct timeval diff; diff_time(&diff, &t2, &t); print_image(scale, height*iy, width*ix); printf("Tiempo = %ld:%ld(seg:mseg)\n\n", diff.tv_sec, diff.tv_usec/1000 ); } MPI_Finalize(); //Clean UP for MPI exit(EXIT_SUCCESS); }
static SigStruct * sig_load(const char *sig_file, unsigned char global_sig[crypto_sign_BYTES], int *hashed, char trusted_comment[TRUSTEDCOMMENTMAXBYTES], size_t trusted_comment_maxlen) { char comment[COMMENTMAXBYTES]; SigStruct *sig_struct; FILE *fp; char *global_sig_s; char *sig_s; size_t global_sig_len; size_t global_sig_s_size; size_t sig_s_size; size_t sig_struct_len; if ((fp = fopen(sig_file, "r")) == NULL) { exit_err(sig_file); } if (fgets(comment, (int) sizeof comment, fp) == NULL) { exit_err(sig_file); } if (strncmp(comment, COMMENT_PREFIX, (sizeof COMMENT_PREFIX) - 1U) != 0) { exit_msg("Untrusted signature comment should start with " "\"" COMMENT_PREFIX "\""); } sig_s_size = B64_MAX_LEN_FROM_BIN_LEN(sizeof *sig_struct) + 2U; sig_s = xmalloc(sig_s_size); if (fgets(sig_s, (int) sig_s_size, fp) == NULL) { exit_err(sig_file); } trim(sig_s); if (fgets(trusted_comment, (int) trusted_comment_maxlen, fp) == NULL) { exit_err(sig_file); } if (strncmp(trusted_comment, TRUSTED_COMMENT_PREFIX, (sizeof TRUSTED_COMMENT_PREFIX) - 1U) != 0) { exit_msg("Trusted signature comment should start with " "\"" TRUSTED_COMMENT_PREFIX "\""); } memmove(trusted_comment, trusted_comment + sizeof TRUSTED_COMMENT_PREFIX - 1U, strlen(trusted_comment + sizeof TRUSTED_COMMENT_PREFIX - 1U) + 1U); trim(trusted_comment); global_sig_s_size = B64_MAX_LEN_FROM_BIN_LEN(crypto_sign_BYTES) + 2U; global_sig_s = xmalloc(global_sig_s_size); if (fgets(global_sig_s, (int) global_sig_s_size, fp) == NULL) { exit_err(sig_file); } trim(global_sig_s); xfclose(fp); sig_struct = xmalloc(sizeof *sig_struct); if (b64_to_bin((unsigned char *) (void *) sig_struct, sig_s, sizeof *sig_struct, strlen(sig_s), &sig_struct_len) == NULL || sig_struct_len != sizeof *sig_struct) { exit_msg("base64 conversion failed"); } free(sig_s); if (memcmp(sig_struct->sig_alg, SIGALG, sizeof sig_struct->sig_alg) == 0) { *hashed = 0; } else if (memcmp(sig_struct->sig_alg, SIGALG_HASHED, sizeof sig_struct->sig_alg) == 0) { *hashed = 1; } else { exit_msg("Unsupported signature algorithm"); } if (b64_to_bin(global_sig, global_sig_s, crypto_sign_BYTES, strlen(global_sig_s), &global_sig_len) == NULL || global_sig_len != crypto_sign_BYTES) { exit_msg("base64 conversion failed"); } free(global_sig_s); return sig_struct; }
int main(int argc, char *argv[]) { char *hostname; int port, sock; fd_set fds; if(argc < 3) exit_msg("minitalk client\nusage: /path/client hostname port"); hostname = argv[1]; port = atoi(argv[2]); if(port < 5000 || port > 65535) exit_msg("port must be between 5000 and 65535 inclusive"); if((sock = request_tcp_connection(hostname, port)) < 0) exit_msg("connection timed out"); printf("connected\n"); int st; char buf[MAXMSG]; while(1) { FD_ZERO(&fds); FD_SET(sock, &fds); FD_SET(0, &fds); st = select(sock+1, &fds, NULL, NULL, NULL); if (st < 0) { printf("error waiting for input.\n"); perror("select"); break; } if (FD_ISSET(0,&fds)) {//input on stdin memset(buf,0,sizeof(buf)); st = read(0, buf, sizeof(buf)); if(st < 0) { printf("error reading stdin.\n"); perror("read"); continue; } st = write(sock, buf, sizeof(buf)); if (st < 0) { printf("error writing to conenction/ \n"); perror("write"); break; } } if (FD_ISSET(sock, &fds)) { memset(buf,0,sizeof(buf)); st = read(sock, buf, sizeof(buf)); if (st < 0) { printf("error reading from connection.\n"); perror("read"); break; } if(buf[0] == '\0') { printf("connection terminated by server\n"); break; } printf(">%s\n", buf); } } close(sock); return 0; }