int sysnet_interface_read(VPNInterface *i, void *data, size_t size) { return read(i->fd, data, size); }
void masterconn_findlastlogversion(void) { struct stat st; uint8_t buff[32800]; // 32800 = 32768 + 32 uint64_t size; uint32_t buffpos; uint64_t lastnewline; int fd; lastlogversion = 0; if (stat("metadata_ml.mfs.back",&st)<0 || st.st_size==0 || (st.st_mode & S_IFMT)!=S_IFREG) { return; } fd = open("changelog_ml.0.back",O_RDWR); if (fd<0) { return; } fstat(fd,&st); size = st.st_size; memset(buff,0,32); lastnewline = 0; while (size>0 && size+200000>(uint64_t)(st.st_size)) { if (size>32768) { memcpy(buff+32768,buff,32); size-=32768; lseek(fd,size,SEEK_SET); if (read(fd,buff,32768)!=32768) { lastlogversion = 0; close(fd); return; } buffpos = 32768; } else { memmove(buff+size,buff,32); lseek(fd,0,SEEK_SET); if (read(fd,buff,size)!=(ssize_t)size) { lastlogversion = 0; close(fd); return; } buffpos = size; size = 0; } // size = position in file of first byte in buff // buffpos = position of last byte in buff to search while (buffpos>0) { buffpos--; if (buff[buffpos]=='\n') { if (lastnewline==0) { lastnewline = size + buffpos; } else { if (lastnewline+1 != (uint64_t)(st.st_size)) { // garbage at the end of file - truncate if (ftruncate(fd,lastnewline+1)<0) { lastlogversion = 0; close(fd); return; } } buffpos++; while (buffpos<32800 && buff[buffpos]>='0' && buff[buffpos]<='9') { lastlogversion *= 10; lastlogversion += buff[buffpos]-'0'; buffpos++; } if (buffpos==32800 || buff[buffpos]!=':') { lastlogversion = 0; } close(fd); return; } } } } close(fd); return; }
// Helper: copy one file to another file // Return 1 for success, 0 for error int shellh_cp_file( const char *psrcname, const char *pdestname, int flags ) { int fds = -1, fdd = -1; int res = 0; char *buf = NULL; ssize_t datalen, datawrote; u32 total = 0; p_logf plog = ( flags & SHELL_F_SILENT ) ? shellh_dummy_printf : printf; if( !strcasecmp( psrcname, pdestname ) ) { plog( "Cannot copy '%s' into itself.\n", psrcname ); goto done; } // If operation confirmation is enabled, ask the user first if( flags & SHELL_F_ASK_CONFIRMATION ) { printf( "Copy '%s' to '%s' ? [y/n] ", psrcname, pdestname ); if( shellh_ask_yes_no( NULL ) == 0 ) goto done; } // Open source file if( ( fds = open( psrcname, O_RDONLY, 0 ) ) == -1 ) { plog( "Error: unable to open source file '%s'\n", psrcname ); goto done; } // If the destination exists and we need to ask for confirmation, do it now if( ( flags & SHELL_F_FORCE_DESTINATION ) == 0 ) { if( ( fdd = open( pdestname, O_RDONLY, 0 ) ) != -1 ) { close( fdd ); fdd = -1; printf( "Destination '%s' already exists, are you sure you want to overwrite it ? [y/n] ", pdestname ); if( shellh_ask_yes_no( NULL ) == 0 ) goto done; } } // Allocate buffer if( ( buf = ( char* )malloc( SHELL_COPY_BUFSIZE ) ) == NULL ) { plog( "ERROR: unable to allocate buffer for copy operation.\n" ); goto done; } plog( "Copying '%s' to '%s' ... ", psrcname, pdestname ); if( ( flags & SHELL_F_SIMULATE_ONLY ) == 0 ) { // Open destination file if( ( fdd = open( pdestname, O_WRONLY | O_CREAT | O_TRUNC, 0 ) ) == -1 ) { plog( "ERROR: unable to open '%s' for writing.\n", pdestname ); goto done; } // Do the actual copy while( 1 ) { if( ( datalen = read( fds, buf, SHELL_COPY_BUFSIZE ) ) == -1 ) { plog( "Error reading source file '%s'.\n", psrcname ); goto done; } if( ( datawrote = write( fdd, buf, datalen ) ) == -1 ) { plog( "Error writing destination file '%s'.\n", pdestname ); goto done; } if( datawrote < datalen ) { plog( "Copy error (no space left on target?)\n" ); goto done; } total += datalen; if( datalen < SHELL_COPY_BUFSIZE ) break; } } plog( "done (%u bytes).\n", ( unsigned )total ); res = 1; done: if( fds != -1 ) close( fds ); if( fdd != -1 ) close( fdd ); if( buf ) free( buf ); return res; }
const char * /* Original version by Solomon Peachy */ version_guess_from_hashcode(sci_version_t *result, int *res_version, guint32 *code) { int i; int fd = -1; int left = VERSION_DETECT_HASH_SIZE; guint32 hash_code; guint8 buf[VERSION_DETECT_BUF_SIZE]; if (IS_VALID_FD(fd = sci_open("resource.001", O_RDONLY|O_BINARY))) { hash_code = HASHCODE_MAGIC_RESOURCE_001; } else if (IS_VALID_FD(fd = sci_open("resource.000", O_RDONLY|O_BINARY))) { hash_code = HASHCODE_MAGIC_RESOURCE_000; } else { sciprintf("Warning: Could not find RESOURCE.000 or RESOURCE.001, cannot determine hash code\n"); *code = 0; /* complete and utter failure */ return NULL; } while (left > 0) { int len = read(fd, buf, left < VERSION_DETECT_BUF_SIZE ? left : VERSION_DETECT_BUF_SIZE); if (len == -1) { sciprintf("Warning: read error while computing hash code for resource file\n"); *code = 0; return NULL; } if (len == 0) /* EOF */ break; for (i = 0; i < len; i++) hash_code = (hash_code * 19) + *(buf + i); /* This is the string hashing algorithm used by Objective Caml 3.08; the general idea ** of multiplying the previous hash code with a prime number between 5 and 23 appears ** to be generally considered to be a "good" approach to exhausting the entire 32 bit ** number space in a somewhat equal distribution. For large chunks of data, such as ** SCI resource files, this should both perform well and yield a good distribution, ** or at least that's what standard library designers have been assuming for quite a ** while. */ left -= len; } close(fd); *code = hash_code; for (i = 0 ; sci_games[i].name ; i++) { if (sci_games[i].id == hash_code) { *result = sci_games[i].version; *res_version = sci_games[i].res_version; return sci_games[i].name; } } return NULL; /* Failed to find matching game */ }
void tailbyteoffset(int fd, char *fn, int isregfile, ssize_t len) { ssize_t n, halfbuf; if (isregfile) /* should be seekable, so we'll do so; it's fastest */ { if (offset > 0) offset = (offset - 1) > len ? len : offset - 1; else offset = (len + offset) > 0 ? len + offset : 0; if (lseek(fd, (off_t)offset, SEEK_SET) == (off_t)-1) fatal(SYSERR, fn); copytoeof(fd, fn); } else /* possibly non-seekable */ { if (offset > 0) /* forwards through file */ { offset--; while(1) { if ((n = read(fd, buf, bufsize)) < 0) fatal(SYSERR, fn); if (n == 0) offset = 0; if (offset <= n) break; else offset -= n; } if (write(STDOUT_FILENO, buf + offset, n - offset) != n - offset) fatal(SYSERR, "stdout"); copytoeof(fd, fn); } else /* backwards through file; remember that offset is negative */ { halfbuf = bufsize / 2; if ((n = read(fd, buf, bufsize)) < 0) fatal(SYSERR, fn); if (n < bufsize) /* we've got the whole file */ { offset = (n + offset) < 0 ? 0 : n + offset; len = n - offset; } else /* we haven't got the whole file */ { while(1) /* page through the file, half a buffer at a time */ { memcpy(buf, buf + halfbuf, halfbuf); if ((n = read(fd, buf + halfbuf, halfbuf)) < 0) fatal(SYSERR, fn); else if (n < halfbuf) break; } offset = (halfbuf + n + offset) < 0 ? 0 : halfbuf + n + offset; len = halfbuf + n - offset; } if (write(STDOUT_FILENO, buf + offset, len) != len) fatal(SYSERR, "stdout"); } } }
int adaptor_init(zhandle_t *zh) { pthread_mutexattr_t recursive_mx_attr; struct adaptor_threads *adaptor_threads = calloc(1, sizeof(*adaptor_threads)); if (!adaptor_threads) { LOG_ERROR(("Out of memory")); return -1; } /* We use a pipe for interrupting select() in unix/sol and socketpair in windows. */ #ifdef WIN32 if (create_socket_pair(adaptor_threads->self_pipe) == -1){ LOG_ERROR(("Can't make a socket.")); #else if(pipe(adaptor_threads->self_pipe)==-1) { LOG_ERROR(("Can't make a pipe %d",errno)); #endif free(adaptor_threads); return -1; } set_nonblock(adaptor_threads->self_pipe[1]); set_nonblock(adaptor_threads->self_pipe[0]); pthread_mutex_init(&zh->auth_h.lock,0); zh->adaptor_priv = adaptor_threads; pthread_mutex_init(&zh->to_process.lock,0); pthread_mutex_init(&adaptor_threads->zh_lock,0); // to_send must be recursive mutex pthread_mutexattr_init(&recursive_mx_attr); pthread_mutexattr_settype(&recursive_mx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&zh->to_send.lock,&recursive_mx_attr); pthread_mutexattr_destroy(&recursive_mx_attr); pthread_mutex_init(&zh->sent_requests.lock,0); pthread_cond_init(&zh->sent_requests.cond,0); pthread_mutex_init(&zh->completions_to_process.lock,0); pthread_cond_init(&zh->completions_to_process.cond,0); start_threads(zh); return 0; } void adaptor_finish(zhandle_t *zh) { struct adaptor_threads *adaptor_threads; // make sure zh doesn't get destroyed until after we're done here api_prolog(zh); adaptor_threads = zh->adaptor_priv; if(adaptor_threads==0) { api_epilog(zh,0); return; } if(!pthread_equal(adaptor_threads->io,pthread_self())){ wakeup_io_thread(zh); pthread_join(adaptor_threads->io, 0); }else pthread_detach(adaptor_threads->io); if(!pthread_equal(adaptor_threads->completion,pthread_self())){ pthread_mutex_lock(&zh->completions_to_process.lock); pthread_cond_broadcast(&zh->completions_to_process.cond); pthread_mutex_unlock(&zh->completions_to_process.lock); pthread_join(adaptor_threads->completion, 0); }else pthread_detach(adaptor_threads->completion); api_epilog(zh,0); } void adaptor_destroy(zhandle_t *zh) { struct adaptor_threads *adaptor = zh->adaptor_priv; if(adaptor==0) return; pthread_cond_destroy(&adaptor->cond); pthread_mutex_destroy(&adaptor->lock); pthread_mutex_destroy(&zh->to_process.lock); pthread_mutex_destroy(&zh->to_send.lock); pthread_mutex_destroy(&zh->sent_requests.lock); pthread_cond_destroy(&zh->sent_requests.cond); pthread_mutex_destroy(&zh->completions_to_process.lock); pthread_cond_destroy(&zh->completions_to_process.cond); pthread_mutex_destroy(&adaptor->zh_lock); pthread_mutex_destroy(&zh->auth_h.lock); close(adaptor->self_pipe[0]); close(adaptor->self_pipe[1]); free(adaptor); zh->adaptor_priv=0; } int wakeup_io_thread(zhandle_t *zh) { struct adaptor_threads *adaptor_threads = zh->adaptor_priv; char c=0; #ifndef WIN32 return write(adaptor_threads->self_pipe[1],&c,1)==1? ZOK: ZSYSTEMERROR; #else return send(adaptor_threads->self_pipe[1], &c, 1, 0)==1? ZOK: ZSYSTEMERROR; #endif } int adaptor_send_queue(zhandle_t *zh, int timeout) { if(!zh->close_requested) return wakeup_io_thread(zh); // don't rely on the IO thread to send the messages if the app has // requested to close return flush_send_queue(zh, timeout); } /* These two are declared here because we will run the event loop * and not the client */ #ifdef WIN32 int zookeeper_interest(zhandle_t *zh, SOCKET *fd, int *interest, struct timeval *tv); #else int zookeeper_interest(zhandle_t *zh, int *fd, int *interest, struct timeval *tv); #endif int zookeeper_process(zhandle_t *zh, int events); #ifdef WIN32 unsigned __stdcall do_io( void * v) #else void *do_io(void *v) #endif { zhandle_t *zh = (zhandle_t*)v; #ifndef WIN32 struct pollfd fds[2]; struct adaptor_threads *adaptor_threads = zh->adaptor_priv; api_prolog(zh); notify_thread_ready(zh); LOG_DEBUG(("started IO thread")); fds[0].fd=adaptor_threads->self_pipe[0]; fds[0].events=POLLIN; while(!zh->close_requested) { struct timeval tv; int fd; int interest; int timeout; int maxfd=1; int rc; zookeeper_interest(zh, &fd, &interest, &tv); if (fd != -1) { fds[1].fd=fd; fds[1].events=(interest&ZOOKEEPER_READ)?POLLIN:0; fds[1].events|=(interest&ZOOKEEPER_WRITE)?POLLOUT:0; maxfd=2; } timeout=tv.tv_sec * 1000 + (tv.tv_usec/1000); poll(fds,maxfd,timeout); if (fd != -1) { interest=(fds[1].revents&POLLIN)?ZOOKEEPER_READ:0; interest|=((fds[1].revents&POLLOUT)||(fds[1].revents&POLLHUP))?ZOOKEEPER_WRITE:0; } if(fds[0].revents&POLLIN){ // flush the pipe char b[128]; while(read(adaptor_threads->self_pipe[0],b,sizeof(b))==sizeof(b)){} } #else fd_set rfds, wfds, efds; struct adaptor_threads *adaptor_threads = zh->adaptor_priv; api_prolog(zh); notify_thread_ready(zh); LOG_DEBUG(("started IO thread")); FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&efds); while(!zh->close_requested) { struct timeval tv; SOCKET fd; SOCKET maxfd=adaptor_threads->self_pipe[0]; int interest; int rc; zookeeper_interest(zh, &fd, &interest, &tv); if (fd != -1) { if (interest&ZOOKEEPER_READ) { FD_SET(fd, &rfds); } else { FD_CLR(fd, &rfds); } if (interest&ZOOKEEPER_WRITE) { FD_SET(fd, &wfds); } else { FD_CLR(fd, &wfds); } } FD_SET( adaptor_threads->self_pipe[0] ,&rfds ); rc = select((int)maxfd, &rfds, &wfds, &efds, &tv); if (fd != -1) { interest = (FD_ISSET(fd, &rfds))? ZOOKEEPER_READ:0; interest|= (FD_ISSET(fd, &wfds))? ZOOKEEPER_WRITE:0; } if (FD_ISSET(adaptor_threads->self_pipe[0], &rfds)){ // flush the pipe/socket char b[128]; while(recv(adaptor_threads->self_pipe[0],b,sizeof(b), 0)==sizeof(b)){} } #endif // dispatch zookeeper events rc = zookeeper_process(zh, interest); // check the current state of the zhandle and terminate // if it is_unrecoverable() if(is_unrecoverable(zh)) break; } api_epilog(zh, 0); LOG_DEBUG(("IO thread terminated")); return 0; } #ifdef WIN32 unsigned __stdcall do_completion( void * v) #else void *do_completion(void *v) #endif { zhandle_t *zh = v; api_prolog(zh); notify_thread_ready(zh); LOG_DEBUG(("started completion thread")); while(!zh->close_requested) { pthread_mutex_lock(&zh->completions_to_process.lock); while(!zh->completions_to_process.head && !zh->close_requested) { pthread_cond_wait(&zh->completions_to_process.cond, &zh->completions_to_process.lock); } pthread_mutex_unlock(&zh->completions_to_process.lock); process_completions(zh); } api_epilog(zh, 0); LOG_DEBUG(("completion thread terminated")); return 0; }
char memfile::getc() { char ch = 0; read(&ch, 1); return ch; }
int main (int argc, char **argv) { int fd = -1, err = 0, readbyte = 0, j; struct mtd_info_user mtdinfo; char buf[sizeof(image_header_t)]; int found = 0; cmdname = *argv; while (--argc > 0 && **++argv == '-') { while (*++*argv) { switch (**argv) { case 'c': if (--argc <= 0) usage (); sectorcount = (unsigned int)atoi(*++argv); cflag = 1; goto NXTARG; case 'o': if (--argc <= 0) usage (); sectoroffset = (unsigned int)atoi(*++argv); goto NXTARG; case 's': if (--argc <= 0) usage (); sectorsize = (unsigned int)atoi(*++argv); sflag = 1; goto NXTARG; default: usage (); } } NXTARG: ; } if (argc != 1 || cflag == 0 || sflag == 0) usage(); devicefile = *argv; fd = open(devicefile, O_RDONLY); if (fd < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", cmdname, devicefile, strerror(errno)); exit(EXIT_FAILURE); } err = ioctl(fd, MEMGETINFO, &mtdinfo); if (err < 0) { fprintf(stderr, "%s: Cannot get MTD information: %s\n",cmdname, strerror(errno)); exit(EXIT_FAILURE); } if (mtdinfo.type != MTD_NORFLASH && mtdinfo.type != MTD_NANDFLASH) { fprintf(stderr, "%s: Unsupported flash type %u\n", cmdname, mtdinfo.type); exit(EXIT_FAILURE); } if (sectorsize * sectorcount != mtdinfo.size) { fprintf(stderr, "%s: Partition size (%d) incompatible with " "sector size and count\n", cmdname, mtdinfo.size); exit(EXIT_FAILURE); } if (sectorsize * sectoroffset >= mtdinfo.size) { fprintf(stderr, "%s: Partition size (%d) incompatible with " "sector offset given\n", cmdname, mtdinfo.size); exit(EXIT_FAILURE); } if (sectoroffset > sectorcount - 1) { fprintf(stderr, "%s: Sector offset cannot be grater than " "sector count minus one\n", cmdname); exit(EXIT_FAILURE); } printf("Searching....\n"); for (j = sectoroffset; j < sectorcount; ++j) { if (lseek(fd, j*sectorsize, SEEK_SET) != j*sectorsize) { fprintf(stderr, "%s: lseek failure: %s\n", cmdname, strerror(errno)); exit(EXIT_FAILURE); } err = flash_bad_block(fd, mtdinfo.type, j*sectorsize); if (err < 0) exit(EXIT_FAILURE); if (err) continue; /* Skip and jump to next */ readbyte = read(fd, buf, sizeof(image_header_t)); if (readbyte != sizeof(image_header_t)) { fprintf(stderr, "%s: Can't read from device: %s\n", cmdname, strerror(errno)); exit(EXIT_FAILURE); } if (fdt_check_header(buf)) { /* old-style image */ if (image_verify_header(buf, fd)) { found = 1; image_print_contents((image_header_t *)buf); } } else { /* FIT image */ fit_print_contents(buf); } } close(fd); if(!found) printf("No images found\n"); exit(EXIT_SUCCESS); }
int cmp( int fh[2], char *names[2], long offs[2] ) { int i; const char *fmt; int bytes_read[2]; size_t amt; for(;;) { bytes_read[0] = read( fh[0], &buffer[0][0], BUFFER_SIZE ); if( bytes_read[0] == -1 ) { Die( "error reading %s: %s\n", names[0], strerror( errno ) ); } bytes_read[1] = read( fh[1], &buffer[1][0], BUFFER_SIZE ); if( bytes_read[1] == -1 ) { Die( "error reading %s: %s\n", names[1], strerror( errno ) ); } amt = bytes_read[0] < bytes_read[1] ? bytes_read[0] : bytes_read[1]; if( memcmp( &buffer[0][0], &buffer[1][0], amt ) ) { for( i = 0; i < amt; ++i ) { if( buffer[0][i] != buffer[1][i] ) { if( !flagSayNothing ) { if( offs[0] == offs[1] ) { if( flagSayItInHex ) { fmt = "offset %08lx: %s=%02x, %s=%02x\n"; } else { fmt = "offset %lu: %s=%u, %s=%u\n"; } printf( fmt, offs[0]+i, names[0], buffer[0][i], names[1], buffer[1][i] ); } else { if( flagSayItInHex ) { fmt = "offset %08lx %s=%02x, offset %08lx %s=%02x\n"; } else { fmt = "offset %lu %s=%u, offset %lu %s=%u\n"; } printf( fmt, offs[0]+i, names[0], buffer[0][i], offs[1]+i, names[1], buffer[1][i] ); } } if( !flagKeepGoing ) return( 1 ); } } } offs[0] += bytes_read[0]; offs[1] += bytes_read[1]; if( bytes_read[0] != bytes_read[1] ) { if( !flagSayNothing ) { if( flagSayItInHex ) { fmt = "%s ends prematurely at offset %08lx\n"; } else { fmt = "%s ends prematurely at offset %u\n"; } if( bytes_read[0] < bytes_read[1] ) { printf( fmt, names[0], offs[0] ); } else { printf( fmt, names[1], offs[1] ); } } return( 1 ); } if( bytes_read[0] == 0 ) break; } return( 0 ); }
// Notify OS X that a ramdisk has been setup. XNU with attach this to /dev/md0 void md0Ramdisk() { RAMDiskParam ramdiskPtr; char filename[512]; const char* override_filename = 0; int fh = -1; int len; if(getValueForKey(kMD0Image, &override_filename, &len, &bootInfo->chameleonConfig)) { // Use user specified md0 file strncpy(filename, override_filename, sizeof(filename) ); fh = open(filename, 0); if(fh < 0) { snprintf(filename, sizeof(filename), "rd(0,0)/Extra/%s", override_filename); fh = open(filename, 0); if(fh < 0) { snprintf(filename, sizeof(filename), "/Extra/%s", override_filename); fh = open(filename, 0); } } } if(fh < 0) { strcpy(filename, "rd(0,0)/Extra/Postboot.img"); fh = open(filename, 0); if(fh < 0) { strcpy(filename, "/Extra/Postboot.img"); // Check /Extra if not in rd(0,0) fh = open(filename, 0); } } if (fh >= 0) { verbose("Enabling ramdisk %s\n", filename); ramdiskPtr.size = file_size(fh); ramdiskPtr.base = AllocateKernelMemory(ramdiskPtr.size); if(ramdiskPtr.size && ramdiskPtr.base) { // Read new ramdisk image contents in kernel memory. if (read(fh, (char*) ramdiskPtr.base, ramdiskPtr.size) == ramdiskPtr.size) { AllocateMemoryRange("RAMDisk", ramdiskPtr.base, ramdiskPtr.size, kBootDriverTypeInvalid); Node* node = DT__FindNode("/chosen/memory-map", false); if(node != NULL) { DT__AddProperty(node, "RAMDisk", sizeof(RAMDiskParam), (void*)&ramdiskPtr); } else { verbose("Unable to notify Mac OS X of the ramdisk %s.\n", filename); } } else { verbose("Unable to read md0 image %s.\n", filename); } } else { verbose("md0 image %s is empty.\n", filename); } close(fh); } }
static int munge_line_in_editor(int count, int key) { int line_number = 0, column_number = 0, ret, tmpfile_fd, bytes_read; size_t tmpfilesize; char *p, *tmpfilename, *text_to_edit; char *editor_command1, *editor_command2, *editor_command3, *editor_command4, *line_number_as_string, *column_number_as_string; char *input, *rewritten_input, *rewritten_input2, **possible_editor_commands; if (!multiline_separator) return 0; tmpfile_fd = open_unique_tempfile(multi_line_tmpfile_ext, &tmpfilename); text_to_edit = search_and_replace(multiline_separator, "\n", rl_line_buffer, rl_point, &line_number, &column_number); write_patiently(tmpfile_fd, text_to_edit, strlen(text_to_edit), "to temporary file"); if (close(tmpfile_fd) != 0) /* improbable */ myerror("couldn't close temporary file %s", tmpfilename); /* find out which editor command we have to use */ possible_editor_commands = list4(getenv("RLWRAP_EDITOR"), getenv("EDITOR"), getenv("VISUAL"), "vi +%L"); editor_command1 = first_of(possible_editor_commands); line_number_as_string = as_string(line_number); column_number_as_string = as_string(column_number); editor_command2 = search_and_replace("%L", line_number_as_string, editor_command1, 0, NULL, NULL); editor_command3 = search_and_replace("%C", column_number_as_string, editor_command2, 0, NULL, NULL); editor_command4 = add3strings(editor_command3, " ", tmpfilename); /* call editor, temporarily restoring terminal settings */ if (terminal_settings_saved && (tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_terminal_settings) < 0)) /* reset terminal */ myerror("tcsetattr error on stdin"); DPRINTF1(DEBUG_READLINE, "calling %s", editor_command4); if ((ret = system(editor_command4))) { if (WIFSIGNALED(ret)) { fprintf(stderr, "\n"); errno = 0; myerror("editor killed by signal"); } else { myerror("failed to invoke editor with '%s'", editor_command4); } } completely_mirror_slaves_terminal_settings(); ignore_queued_input = TRUE; /* read back edited input, replacing real newline with substitute */ tmpfile_fd = open(tmpfilename, O_RDONLY); if (tmpfile_fd < 0) myerror("could not read temp file %s", tmpfilename); tmpfilesize = filesize(tmpfilename); input = mymalloc(tmpfilesize + 1); bytes_read = read(tmpfile_fd, input, tmpfilesize); if (bytes_read < 0) myerror("unreadable temp file %s", tmpfilename); input[bytes_read] = '\0'; rewritten_input = search_and_replace("\t", " ", input, 0, NULL, NULL); /* rlwrap cannot handle tabs in input lines */ rewritten_input2 = search_and_replace("\n", multiline_separator, rewritten_input, 0, NULL, NULL); for(p = rewritten_input2; *p ;p++) if(*p >= 0 && *p < ' ') /* @@@FIXME: works for UTF8, but not UTF16 or UTF32 (Mention this in manpage?)*/ *p = ' '; /* replace all control characters (like \r) by spaces */ rl_delete_text(0, strlen(rl_line_buffer)); rl_point = 0; clear_line(); cr(); my_putstr(saved_rl_state.cooked_prompt); rl_insert_text(rewritten_input2); rl_point = 0; /* leave cursor on predictable place */ rl_done = 1; /* accept line immediately */ /* wash those dishes */ if (unlink(tmpfilename)) myerror("could not delete temporary file %s", tmpfilename); free(editor_command2); free(editor_command3); free(editor_command4); free(line_number_as_string); free(column_number_as_string); free(tmpfilename); free(text_to_edit); free(input); free(rewritten_input); free(rewritten_input2); return_key = (char)'\n'; return 0; }
int mountRAMDisk(const char * param) { int fh = 0, ramDiskSize; int error = 0; // Get file handle for ramdisk file. fh = open(param, 0); if (fh != -1) { printf("\nreading ramdisk image: %s", param); ramDiskSize = file_size(fh); if (ramDiskSize > 0) { // Unmount previously mounted image if exists. umountRAMDisk(); // Read new ramdisk image contents into PREBOOT_DATA area. if (read(fh, (char *)PREBOOT_DATA, ramDiskSize) != ramDiskSize) error = -1; } else error = -1; close(fh); } else error = -1; if (error == 0) { // Save filename in gRAMDiskFile to display information. strlcpy(gRAMDiskFile, param, sizeof(gRAMDiskFile)); // Set gMI as well for the multiboot ramdisk driver hook. gMI = gRAMDiskMI = malloc(sizeof(multiboot_info)); struct multiboot_module * ramdisk_module = malloc(sizeof(multiboot_module)); // Fill in multiboot info and module structures. if (gRAMDiskMI != NULL && ramdisk_module != NULL) { gRAMDiskMI->mi_mods_count = 1; gRAMDiskMI->mi_mods_addr = (uint32_t)ramdisk_module; ramdisk_module->mm_mod_start = PREBOOT_DATA; ramdisk_module->mm_mod_end = PREBOOT_DATA + ramDiskSize; // Set ramdisk driver hooks. p_get_ramdisk_info = &multiboot_get_ramdisk_info; p_ramdiskReadBytes = &multibootRamdiskReadBytes; int partCount; // unused // Save bvr of the mounted image. gRAMDiskVolume = diskScanBootVolumes(0x100, &partCount); if(gRAMDiskVolume == NULL) { umountRAMDisk(); printf("\nRamdisk contains no partitions."); } else { char dirSpec[128]; // Reading ramdisk configuration. strlcpy(dirSpec, RAMDISKCONFIG_FILENAME, sizeof(dirSpec)); if (loadConfigFile(dirSpec, &bootInfo->ramdiskConfig) == 0) { getBoolForKey("BTAlias", &gRAMDiskBTAliased, &bootInfo->ramdiskConfig); } else { printf("\nno ramdisk config...\n"); } printf("\nmounting: done"); } } } return error; }
void udev_read_event(int fd) { struct pdev_array_entry *pae; prop_dictionary_t dict, evdict, devdict; prop_number_t pn; prop_string_t ps; prop_object_t po; prop_array_t pa; char *xml; int n, idx, evtype; size_t sz; sz = 4096 * 1024; xml = malloc(sz); /* 4 MB */ again: if ((n = read(fd, xml, sz)) <= 0) { if (errno == ENOMEM) { sz <<= 2; if ((xml = realloc(xml, sz)) == NULL) { syslog(LOG_ERR, "could not realloc xml memory"); return; } goto again; } free(xml); return; } dict = prop_dictionary_internalize(xml); free(xml); if (dict == NULL) { syslog(LOG_ERR, "internalization of xml failed"); return; } pn = prop_dictionary_get(dict, "evtype"); if (pn == NULL) { syslog(LOG_ERR, "read_event: no key evtype"); goto out; } evtype = prop_number_integer_value(pn); evdict = prop_dictionary_get(dict, "evdict"); if (evdict == NULL) { syslog(LOG_ERR, "read_event: no key evdict"); goto out; } switch (evtype) { case UDEV_EVENT_ATTACH: monitor_queue_event(dict); pae = pdev_array_entry_get_last(); pa = prop_array_copy(pae->pdev_array); pdev_array_entry_unref(pae); if (pa == NULL) goto out; prop_array_add(pa, evdict); pdev_array_entry_insert(pa); break; case UDEV_EVENT_DETACH: monitor_queue_event(dict); if ((devdict = find_dev_dict(-1, evdict, &idx)) == NULL) goto out; pae = pdev_array_entry_get_last(); pa = prop_array_copy(pae->pdev_array); pdev_array_entry_unref(pae); if (pa == NULL) goto out; prop_array_remove(pa, idx); pdev_array_entry_insert(pa); break; case UDEV_EV_KEY_UPDATE: if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL) goto out; if ((ps = prop_dictionary_get(evdict, "key")) == NULL) goto out; if ((po = prop_dictionary_get(evdict, "value")) == NULL) goto out; /* prop_object_retain(po); */ /* not necessary afaik */ prop_dictionary_set(devdict, prop_string_cstring_nocopy(ps), po); break; case UDEV_EV_KEY_REMOVE: if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL) goto out; if ((ps = prop_dictionary_get(evdict, "key")) == NULL) goto out; prop_dictionary_remove(devdict, prop_string_cstring_nocopy(ps)); break; default: syslog(LOG_ERR, "read_event: unknown evtype %d", evtype); } out: prop_object_release(dict); return; }
int main(int argc, char **argv) { const char *progname = argv[0]; struct ccn *ccn = NULL; struct ccn_charbuf *name = NULL; struct ccn_charbuf *pname = NULL; struct ccn_charbuf *temp = NULL; struct ccn_charbuf *extopt = NULL; long expire = -1; int versioned = 0; size_t blocksize = 8*1024; int status = 0; int res; ssize_t read_res; unsigned char *buf = NULL; enum ccn_content_type content_type = CCN_CONTENT_DATA; struct ccn_closure in_interest = {.p=&incoming_interest}; const char *postver = NULL; const char *key_uri = NULL; int force = 0; int verbose = 0; int timeout = -1; int setfinal = 0; int prefixcomps = -1; int fd; struct ccn_signing_params sp = CCN_SIGNING_PARAMS_INIT; while ((res = getopt(argc, argv, "e:fhk:lvV:p:t:w:x:")) != -1) { switch (res) { case 'e': if (extopt == NULL) extopt = ccn_charbuf_create(); fd = open(optarg, O_RDONLY); if (fd < 0) { perror(optarg); exit(1); } for (;;) { read_res = read(fd, ccn_charbuf_reserve(extopt, 64), 64); if (read_res <= 0) break; extopt->length += read_res; } if (read_res < 0) perror(optarg); close(fd); break; case 'f': force = 1; break; case 'l': setfinal = 1; // set FinalBlockID to last comp of name break; case 'k': key_uri = optarg; break; case 'p': prefixcomps = atoi(optarg); if (prefixcomps < 0) usage(progname); break; case 'x': expire = atol(optarg); if (expire <= 0) usage(progname); break; case 'v': verbose = 1; break; case 'V': versioned = 1; postver = optarg; if (0 == memcmp(postver, "%00", 3)) setfinal = 1; break; case 'w': timeout = atol(optarg); if (timeout <= 0) usage(progname); timeout *= 1000; break; case 't': if (0 == strcasecmp(optarg, "DATA")) { content_type = CCN_CONTENT_DATA; break; } if (0 == strcasecmp(optarg, "ENCR")) { content_type = CCN_CONTENT_ENCR; break; } if (0 == strcasecmp(optarg, "GONE")) { content_type = CCN_CONTENT_GONE; break; } if (0 == strcasecmp(optarg, "KEY")) { content_type = CCN_CONTENT_KEY; break; } if (0 == strcasecmp(optarg, "LINK")) { content_type = CCN_CONTENT_LINK; break; } if (0 == strcasecmp(optarg, "NACK")) { content_type = CCN_CONTENT_NACK; break; } content_type = atoi(optarg); if (content_type > 0 && content_type <= 0xffffff) break; fprintf(stderr, "Unknown content type %s\n", optarg); /* FALLTHRU */ default: case 'h': usage(progname); break; } } argc -= optind; argv += optind; if (argv[0] == NULL) usage(progname); name = ccn_charbuf_create(); res = ccn_name_from_uri(name, argv[0]); if (res < 0) { fprintf(stderr, "%s: bad ccn URI: %s\n", progname, argv[0]); exit(1); } if (argv[1] != NULL) fprintf(stderr, "%s warning: extra arguments ignored\n", progname); /* Preserve the original prefix, in case we add versioning, * but trim it down if requested for the interest filter registration */ pname = ccn_charbuf_create(); ccn_charbuf_append(pname, name->buf, name->length); if (prefixcomps >= 0) { res = ccn_name_chop(pname, NULL, prefixcomps); if (res < 0) { fprintf(stderr, "%s: unable to trim name to %d component%s.\n", progname, prefixcomps, prefixcomps == 1 ? "" : "s"); exit(1); } } /* Connect to ccnd */ ccn = ccn_create(); if (ccn_connect(ccn, NULL) == -1) { perror("Could not connect to ccnd"); exit(1); } /* Read the actual user data from standard input */ buf = calloc(1, blocksize); read_res = read_full(0, buf, blocksize); if (read_res < 0) { perror("read"); read_res = 0; status = 1; } /* Tack on the version component if requested */ if (versioned) { res = ccn_create_version(ccn, name, CCN_V_REPLACE | CCN_V_NOW | CCN_V_HIGH, 0, 0); if (res < 0) { fprintf(stderr, "%s: ccn_create_version() failed\n", progname); exit(1); } if (postver != NULL) { res = ccn_name_from_uri(name, postver); if (res < 0) { fprintf(stderr, "-V %s: invalid name suffix\n", postver); exit(0); } } } temp = ccn_charbuf_create(); /* Ask for a FinalBlockID if appropriate. */ if (setfinal) sp.sp_flags |= CCN_SP_FINAL_BLOCK; if (res < 0) { fprintf(stderr, "Failed to create signed_info (res == %d)\n", res); exit(1); } /* Set content type */ sp.type = content_type; /* Set freshness */ if (expire >= 0) { if (sp.template_ccnb == NULL) { sp.template_ccnb = ccn_charbuf_create(); ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_SignedInfo, CCN_DTAG); } else if (sp.template_ccnb->length > 0) { sp.template_ccnb->length--; } ccnb_tagged_putf(sp.template_ccnb, CCN_DTAG_FreshnessSeconds, "%ld", expire); sp.sp_flags |= CCN_SP_TEMPL_FRESHNESS; ccn_charbuf_append_closer(sp.template_ccnb); } /* Set key locator, if supplied */ if (key_uri != NULL) { struct ccn_charbuf *c = ccn_charbuf_create(); res = ccn_name_from_uri(c, key_uri); if (res < 0) { fprintf(stderr, "%s is not a valid ccnx URI\n", key_uri); exit(1); } if (sp.template_ccnb == NULL) { sp.template_ccnb = ccn_charbuf_create(); ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_SignedInfo, CCN_DTAG); } else if (sp.template_ccnb->length > 0) { sp.template_ccnb->length--; } ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_KeyLocator, CCN_DTAG); ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_KeyName, CCN_DTAG); ccn_charbuf_append(sp.template_ccnb, c->buf, c->length); ccn_charbuf_append_closer(sp.template_ccnb); ccn_charbuf_append_closer(sp.template_ccnb); sp.sp_flags |= CCN_SP_TEMPL_KEY_LOCATOR; ccn_charbuf_append_closer(sp.template_ccnb); ccn_charbuf_destroy(&c); } if (extopt != NULL && extopt->length > 0) { if (sp.template_ccnb == NULL) { sp.template_ccnb = ccn_charbuf_create(); ccn_charbuf_append_tt(sp.template_ccnb, CCN_DTAG_SignedInfo, CCN_DTAG); } else if (sp.template_ccnb->length > 0) { sp.template_ccnb->length--; } ccnb_append_tagged_blob(sp.template_ccnb, CCN_DTAG_ExtOpt, extopt->buf, extopt->length); sp.sp_flags |= CCN_SP_TEMPL_EXT_OPT; ccn_charbuf_append_closer(sp.template_ccnb); } /* Create the signed content object, ready to go */ temp->length = 0; res = ccn_sign_content(ccn, temp, name, &sp, buf, read_res); if (res != 0) { fprintf(stderr, "Failed to encode ContentObject (res == %d)\n", res); exit(1); } if (read_res == blocksize) { read_res = read_full(0, buf, 1); if (read_res == 1) { fprintf(stderr, "%s: warning - truncated data\n", argv[0]); status = 1; } } free(buf); buf = NULL; if (force) { /* At user request, send without waiting to see an interest */ res = ccn_put(ccn, temp->buf, temp->length); if (res < 0) { fprintf(stderr, "ccn_put failed (res == %d)\n", res); exit(1); } } else { in_interest.data = temp; /* Set up a handler for interests */ res = ccn_set_interest_filter(ccn, pname, &in_interest); if (res < 0) { fprintf(stderr, "Failed to register interest (res == %d)\n", res); exit(1); } res = ccn_run(ccn, timeout); if (in_interest.intdata == 0) { if (verbose) fprintf(stderr, "Nobody's interested\n"); exit(1); } } if (verbose) { struct ccn_charbuf *uri = ccn_charbuf_create(); uri->length = 0; ccn_uri_append(uri, name->buf, name->length, 1); printf("wrote %s\n", ccn_charbuf_as_string(uri)); ccn_charbuf_destroy(&uri); } ccn_destroy(&ccn); ccn_charbuf_destroy(&name); ccn_charbuf_destroy(&pname); ccn_charbuf_destroy(&temp); ccn_charbuf_destroy(&sp.template_ccnb); ccn_charbuf_destroy(&extopt); exit(status); }
void updateStats(void *) { char pLogBuffer[1024]; static int log_len; static struct timeval last_time; static long last_rx=0; static long last_tx=0; static long connect_time=0; char *ptr; int fd; char buf[1024]; long rx = -1; long tx = -1; float spi = 0.0; float spo = 0.0; static bool modleds = false; int len = -1; fd = open("/proc/net/dev", O_RDONLY); if(fd > 0) { len = read(fd, buf, 1023); close(fd); if(len>0) { buf[len] = '\0'; ptr = strstr( buf, "ppp0" ); } } if(fd==-1 || len < 0 || ptr == NULL) { if (modleds) { dock->remove_from_tray(mModemLeds); modleds = false; } last_rx=0; last_tx=0; connect_time=0; } else { long dt; int ct; struct timeval tv; gettimeofday(&tv, NULL); dt = (tv.tv_sec - last_time.tv_sec) * 1000; dt += (tv.tv_usec - last_time.tv_usec) / 1000; if (dt > 0) { sscanf(ptr, "%*[^:]:%ld %*d %*d %*d %*d %*d %*d %*d %ld", &rx, &tx); spi = (rx - last_rx) / dt; spi = spi / 1024.0 * 1000.0; spo = (tx - last_tx) / dt; spo = spo / 1024.0 * 1000.0; if ( connect_time == 0 ) connect_time = tv.tv_sec; ct = (int)(tv.tv_sec - connect_time); snprintf(pLogBuffer, 1024, _("Received: %ld kB (%.1f kB/s)\n" "Sent: %ld kB (%.1f kB/s)\n" "Duration: %d min %d sec"), rx / 1024, spi, tx / 1024, spo, ct / 60, ct % 60 ); last_rx = rx; last_tx = tx; last_time.tv_sec = tv.tv_sec; last_time.tv_usec = tv.tv_usec; log_len = 0; if ((int)(spi) > 0) { mLedIn->color( (Fl_Color)2 ); mLedIn->redraw(); } else { mLedIn->color( (Fl_Color)968701184 ); mLedIn->redraw(); } if ( (int)(spo) > 0 ) { mLedOut->color( (Fl_Color)2 ); mLedOut->redraw(); } else { mLedOut->color( (Fl_Color)968701184 ); mLedOut->redraw(); } mModemLeds->tooltip(pLogBuffer); } if (!modleds) { dock->add_to_tray(mModemLeds); modleds = true; } } updateSetup(); Fl::repeat_timeout(1.0f, updateStats); }
static int ast_read_callback(void *data) { u_int16_t size; u_int32_t delay = -1; int looper = 1; int retval = 0; int res; struct ast_filestream *s = data; /* Send a frame from the file to the appropriate channel */ while(looper) { if (read(s->fd, &size, 2) != 2) { /* Out of data, or the file is no longer valid. In any case go ahead and stop the stream */ s->owner->streamid = -1; return 0; } /* Looks like we have a frame to read from here */ size = ntohs(size); if (size > G723_MAX_SIZE - sizeof(struct ast_frame)) { ast_log(LOG_WARNING, "Size %d is invalid\n", size); /* The file is apparently no longer any good, as we shouldn't ever get frames even close to this size. */ s->owner->streamid = -1; return 0; } /* Read the data into the buffer */ s->fr->offset = AST_FRIENDLY_OFFSET; s->fr->datalen = size; s->fr->data = s->buf + sizeof(struct ast_frame) + AST_FRIENDLY_OFFSET; if ((res = read(s->fd, s->fr->data , size)) != size) { ast_log(LOG_WARNING, "Short read (%d of %d bytes) (%s)!\n", res, size, strerror(errno)); s->owner->streamid = -1; return 0; } /* Read the delay for the next packet, and schedule again if necessary */ if (read(s->fd, &delay, 4) == 4) delay = ntohl(delay); else delay = -1; #if 0 /* Average out frames <= 50 ms */ if (delay < 50) s->fr->timelen = 30; else s->fr->timelen = delay; #else s->fr->samples = 240; #endif /* Unless there is no delay, we're going to exit out as soon as we have processed the current frame. */ if (delay > VOFR_FUDGE) { looper = 0; /* If there is a delay, lets schedule the next event */ if (delay != s->lasttimeout) { /* We'll install the next timeout now. */ s->owner->streamid = ast_sched_add(s->owner->sched, delay - VOFR_FUDGE, ast_read_callback, s); s->lasttimeout = delay; } else /* Just come back again at the same time */ retval = -1; } /* Lastly, process the frame */ if (ast_write(s->owner, s->fr)) { ast_log(LOG_WARNING, "Failed to write frame\n"); s->owner->streamid = -1; return 0; } } return retval; }
static ssize_t fetchFile_read(void *cookie, void *buf, size_t len) { return read(*(int *)cookie, buf, len); }
int main(int argc,char *argv[]){ char name[1024]; char keyfile[1024]; klee_make_symbolic(name, sizeof(name), "name"); klee_make_symbolic(keyfile, sizeof(keyfile), "keyfile"); int fd,ret=1,err,i; struct stat statbuf; fd=open(keyfile,O_RDONLY); if(fd==-1) { fprintf(stderr,"Cannot open key file %s: %s\n",keyfile,strerror(errno)); return 1; } err=fstat(fd,&statbuf); if(err==-1) { fprintf(stderr,"Unable to stat key file %s: %s\n", keyfile,strerror(errno)); goto fail; } if(statbuf.st_size>65536) { fprintf(stderr,"Key %s too large for CERT encoding\n",keyfile); goto fail; } if(statbuf.st_size>16384) fprintf(stderr,"Warning: key file %s is larger than the default" " GnuPG max-cert-size\n",keyfile); printf("%s\tTYPE37\t\\# %u 0003 0000 00 ", name,(unsigned int)statbuf.st_size+5); err=1; while(err!=0) { unsigned char buffer[1024]; err=read(fd,buffer,1024); if(err==-1) { fprintf(stderr,"Unable to read key file %s: %s\n", keyfile,strerror(errno)); goto fail; } for(i=0;i<err;i++) printf("%02X",buffer[i]); } printf("\n"); ret=0; fail: close(fd); return ret; }
int main (int argc, char *argv[]) { // Test URL extraction function. testGetRequest(); printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving the Mandelbrot since 2011\n"); int serverSocket = makeServerSocket (DEFAULT_PORT); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection (serverSocket); // Wait for a request to be sent from a web browser, open a new // Connection for this conversation // Read the first line of the request sent by the browser int bytesRead; bytesRead = read (connectionSocket, request, (sizeof request)-1); assert (bytesRead >= 0); // Were we able to read any data from the connection? //determine if there is an X in the request if(isXFound(request)){ // Read x,y,zoom from URL. getRequest(request); // Print entire request to the console printf (" *** Received http request ***\n %s\n", request); // Send the browser a simple html page using http printf (" *** Sending http response ***\n"); serveHTML(connectionSocket); } else { // Print entire request to the console printf (" *** Received http request ***\n %s\n", request); // Send the browser a simple html page using http printf (" *** Sending http response ***\n"); serveInteractiveJS(connectionSocket); } // Close the connection after sending the page- keep aust beautiful close(connectionSocket); numberServed++; } // close the server connection after we are done- keep aust beautiful printf ("** shutting down the server **\n"); close (serverSocket); return EXIT_SUCCESS; }
static void * clientThread (void *arg) { client_t *c = (client_t *) arg; fd_set rfds, wfds; int ret; c->querybuf = sdsMakeRoomFor (sdsempty (), DEFAULT_QUERY_BUF_SIZE); c->replybuf = sdsMakeRoomFor (sdsempty (), DEFAULT_QUERY_BUF_SIZE); c->argc = 0; c->argv = NULL; c->argvlen = NULL; c->reqtype = 0; c->multibulklen = 0; c->bulklen = -1; c->rqst = arc_create_request (); c->flags = 0; c->total_append_command = 0; FD_ZERO (&rfds); FD_ZERO (&wfds); while (1) { struct timeval timeout; FD_CLR (c->fd, &rfds); FD_CLR (c->fd, &wfds); if (!(c->flags & REDIS_CLOSE_AFTER_REPLY)) FD_SET (c->fd, &rfds); if (sdslen (c->replybuf) > 0) FD_SET (c->fd, &wfds); timeout.tv_sec = 1; timeout.tv_usec = 0; ret = select (c->fd + 1, &rfds, &wfds, NULL, &timeout); if (ret == -1) { perror ("select"); freeClient (c); } if (server.shutdown_signal) { c->flags |= REDIS_CLOSE_AFTER_REPLY; } /* readable */ if (FD_ISSET (c->fd, &rfds)) { int pos = sdslen (c->querybuf); int avail = sdsavail (c->querybuf); ssize_t nread; if (avail == 0) { c->querybuf = sdsMakeRoomFor (c->querybuf, sdslen (c->querybuf)); avail = sdsavail (c->querybuf); } nread = read (c->fd, c->querybuf + pos, avail); if (nread > 0) { sdsIncrLen (c->querybuf, nread); processInputBuffer (c); if (c->total_append_command) { int arc_errno, arc_be_errno, be_errno; arc_ref_t *arc_ref; arc_ref = acquire_arc_ref (); ret = arc_do_request (arc_ref->arc, c->rqst, server.query_timeout_millis, &be_errno); if (ret == -1) { arc_errno = errno; arc_be_errno = be_errno; } else { ret = processReply (c, &be_errno); if (ret == -1) { arc_errno = errno; arc_be_errno = be_errno; } } arc_free_request (c->rqst); release_arc_ref (arc_ref); c->rqst = arc_create_request (); if (ret == -1) { if (arc_errno == ARC_ERR_TIMEOUT || (arc_errno == ARC_ERR_BACKEND && arc_be_errno == ARC_ERR_TIMEOUT)) { addReplyStr (c, "-ERR Redis Timeout\r\n"); } else { addReplyStr (c, "-ERR Internal Error\r\n"); } c->flags |= REDIS_CLOSE_AFTER_REPLY; } } } else { if (nread == -1 && errno == EAGAIN) { /* Skip */ } else { freeClient (c); } } } /* writable */ if (FD_ISSET (c->fd, &wfds)) { int pos = 0; int avail = sdslen (c->replybuf); ssize_t nwritten; nwritten = write (c->fd, c->replybuf + pos, avail); if (nwritten > 0) { avail -= nwritten; pos += nwritten; sdsrange (c->replybuf, pos, -1); } else { if (nwritten == -1 && errno == EAGAIN) { /* Skip */ } else { freeClient (c); } } } if (sdslen (c->replybuf) == 0 && (c->flags & REDIS_CLOSE_AFTER_REPLY)) { freeClient (c); } } return NULL; }
int rcmd( char **ahost, int rport, const char *locuser, const char *remuser, const char *cmd, int *fd2p ) { struct hostent *hp; struct sockaddr_in sin, from; fd_set reads; #ifndef __rtems__ long oldmask; #endif pid_t pid; int s, lport, timo; char c; pid = getpid(); hp = gethostbyname(*ahost); if (hp == NULL) { herror(*ahost); return (-1); } *ahost = hp->h_name; #ifndef __rtems__ oldmask = sigblock(sigmask(SIGURG)); #endif for (timo = 1, lport = IPPORT_RESERVED - 1;;) { s = rresvport(&lport); if (s < 0) { if (errno == EAGAIN) (void)fprintf(stderr, "rcmd: socket: All ports in use\n"); else (void)fprintf(stderr, "rcmd: socket: %s\n", strerror(errno)); #ifndef __rtems__ sigsetmask(oldmask); #endif return (-1); } fcntl(s, F_SETOWN, pid); bzero(&sin, sizeof sin); sin.sin_len = sizeof(struct sockaddr_in); sin.sin_family = hp->h_addrtype; sin.sin_port = rport; bcopy(hp->h_addr_list[0], &sin.sin_addr, MIN(hp->h_length, sizeof sin.sin_addr)); if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0) break; (void)close(s); if (errno == EADDRINUSE) { lport--; continue; } if (errno == ECONNREFUSED && timo <= 16) { (void)sleep(timo); timo *= 2; continue; } if (hp->h_addr_list[1] != NULL) { int oerrno = errno; (void)fprintf(stderr, "connect to address %s: ", inet_ntoa(sin.sin_addr)); errno = oerrno; perror(0); hp->h_addr_list++; bcopy(hp->h_addr_list[0], &sin.sin_addr, MIN(hp->h_length, sizeof sin.sin_addr)); (void)fprintf(stderr, "Trying %s...\n", inet_ntoa(sin.sin_addr)); continue; } (void)fprintf(stderr, "%s: %s\n", hp->h_name, strerror(errno)); #ifndef __rtems__ sigsetmask(oldmask); #endif return (-1); } lport--; if (fd2p == 0) { write(s, "", 1); lport = 0; } else { char num[8]; int s2 = rresvport(&lport), s3; socklen_t len = sizeof(from); int nfds; if (s2 < 0) goto bad; listen(s2, 1); (void)snprintf(num, sizeof(num), "%d", lport); if (write(s, num, strlen(num)+1) != strlen(num)+1) { (void)fprintf(stderr, "rcmd: write (setting up stderr): %s\n", strerror(errno)); (void)close(s2); goto bad; } nfds = max(s, s2)+1; if(nfds > FD_SETSIZE) { fprintf(stderr, "rcmd: too many files\n"); (void)close(s2); goto bad; } again: FD_ZERO(&reads); FD_SET(s, &reads); FD_SET(s2, &reads); errno = 0; if (select(nfds, &reads, 0, 0, 0) < 1 || !FD_ISSET(s2, &reads)){ if (errno != 0) (void)fprintf(stderr, "rcmd: select (setting up stderr): %s\n", strerror(errno)); else (void)fprintf(stderr, "select: protocol failure in circuit setup\n"); (void)close(s2); goto bad; } s3 = accept(s2, (struct sockaddr *)&from, &len); /* * XXX careful for ftp bounce attacks. If discovered, shut them * down and check for the real auxiliary channel to connect. */ if (from.sin_family == AF_INET && from.sin_port == htons(20)) { close(s3); goto again; } (void)close(s2); if (s3 < 0) { (void)fprintf(stderr, "rcmd: accept: %s\n", strerror(errno)); lport = 0; goto bad; } *fd2p = s3; from.sin_port = ntohs((u_short)from.sin_port); if (from.sin_family != AF_INET || from.sin_port >= IPPORT_RESERVED || from.sin_port < IPPORT_RESERVED / 2) { (void)fprintf(stderr, "socket: protocol failure in circuit setup.\n"); goto bad2; } } (void)write(s, locuser, strlen(locuser)+1); (void)write(s, remuser, strlen(remuser)+1); (void)write(s, cmd, strlen(cmd)+1); if (read(s, &c, 1) != 1) { (void)fprintf(stderr, "rcmd: %s: %s\n", *ahost, strerror(errno)); goto bad2; } if (c != 0) { while (read(s, &c, 1) == 1) { (void)write(STDERR_FILENO, &c, 1); if (c == '\n') break; } goto bad2; } #ifndef __rtems__ sigsetmask(oldmask); #endif return (s); bad2: if (lport) (void)close(*fd2p); bad: (void)close(s); #ifndef __rtems__ sigsetmask(oldmask); #endif return (-1); }
/*=== Main thread */ void *tnet_transport_mainthread(void *param) { tnet_transport_t *transport = param; transport_context_t *context = transport->context; int ret; tsk_size_t i; tsk_bool_t is_stream; tnet_fd_t fd; struct sockaddr_storage remote_addr = {0}; transport_socket_xt* active_socket; /* check whether the transport is already prepared */ if(!transport->prepared){ TSK_DEBUG_ERROR("Transport must be prepared before strating."); goto bail; } is_stream = TNET_SOCKET_TYPE_IS_STREAM(transport->master->type); TSK_DEBUG_INFO("Starting [%s] server with IP {%s} on port {%d} using fd {%d} with type {%d}...", transport->description, transport->master->ip, transport->master->port, transport->master->fd, transport->master->type); while(TSK_RUNNABLE(transport)->running || TSK_RUNNABLE(transport)->started){ if((ret = tnet_poll(context->ufds, context->count, -1)) < 0){ TNET_PRINT_LAST_ERROR("poll have failed."); goto bail; } if(!TSK_RUNNABLE(transport)->running && !TSK_RUNNABLE(transport)->started){ TSK_DEBUG_INFO("Stopping [%s] server with IP {%s} on port {%d} with type {%d}...", transport->description, transport->master->ip, transport->master->port, transport->master->type); goto bail; } /* lock context */ tsk_safeobj_lock(context); /* == == */ for(i=0; i<context->count; i++) { if(!context->ufds[i].revents){ continue; } // TSK_DEBUG_INFO("REVENTS(i=%d) = %d", i, context->ufds[i].revents); if(context->ufds[i].fd == context->pipeR){ TSK_DEBUG_INFO("PipeR event = %d", context->ufds[i].revents); if(context->ufds[i].revents & TNET_POLLIN){ static char __buffer[1024]; if(read(context->pipeR, __buffer, sizeof(__buffer)) < 0){ TNET_PRINT_LAST_ERROR("Failed to read from the Pipe"); } } else if(context->ufds[i].revents & TNET_POLLHUP){ TNET_PRINT_LAST_ERROR("Pipe Error"); goto bail; } context->ufds[i].revents = 0; continue; } /* Get active event and socket */ active_socket = context->sockets[i]; /*================== TNET_POLLHUP ==================*/ if(context->ufds[i].revents & (TNET_POLLHUP)){ fd = active_socket->fd; TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- TNET_POLLHUP(%d)", transport->description, fd); #if defined(ANDROID) /* FIXME */ #else tnet_transport_remove_socket(transport, &active_socket->fd); TSK_RUNNABLE_ENQUEUE(transport, event_closed, transport->callback_data, fd); continue; #endif } /*================== TNET_POLLERR ==================*/ if(context->ufds[i].revents & (TNET_POLLERR)){ fd = active_socket->fd; TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- TNET_POLLERR(%d)", transport->description, fd); tnet_transport_remove_socket(transport, &active_socket->fd); TSK_RUNNABLE_ENQUEUE(transport, event_error, transport->callback_data, fd); continue; } /*================== TNET_POLLNVAL ==================*/ if(context->ufds[i].revents & (TNET_POLLNVAL)){ fd = active_socket->fd; TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- TNET_POLLNVAL(%d)", transport->description, fd); tnet_transport_remove_socket(transport, &active_socket->fd); TSK_RUNNABLE_ENQUEUE(transport, event_error, transport->callback_data, fd); continue; } /*================== POLLIN ==================*/ if(context->ufds[i].revents & TNET_POLLIN) { tsk_size_t len = 0; void* buffer = tsk_null; tnet_transport_event_t* e; // TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- TNET_POLLIN(%d)", transport->description, active_socket->fd); /* check whether the socket is paused or not */ if(active_socket->paused){ TSK_DEBUG_INFO("Socket is paused"); goto TNET_POLLIN_DONE; } /* Retrieve the amount of pending data. * IMPORTANT: If you are using Symbian please update your SDK to the latest build (August 2009) to have 'FIONREAD'. * This apply whatever you are using the 3rd or 5th edition. * Download link: http://wiki.forum.nokia.com/index.php/Open_C/C%2B%2B_Release_History */ if((tnet_ioctlt(active_socket->fd, FIONREAD, &len) < 0 || !len) && is_stream){ /* It's probably an incoming connection --> try to accept() it */ int listening = 0, remove_socket = 0; socklen_t socklen = sizeof(listening); TSK_DEBUG_INFO("ioctlt(%d), len=%u returned zero or failed", active_socket->fd, len); // check if socket is listening if(getsockopt(active_socket->fd, SOL_SOCKET, SO_ACCEPTCONN, &listening, &socklen) != 0){ #if defined(BSD) /* old FreeBSD versions (and OSX up to Lion) do not support SO_ACCEPTCONN */ listening = 1; #else TNET_PRINT_LAST_ERROR("getsockopt(SO_ACCEPTCONN, %d) failed\n", active_socket->fd); /* not socket accepted -> no socket to remove */ goto TNET_POLLIN_DONE; #endif } if (listening){ if((fd = accept(active_socket->fd, tsk_null, 0)) != TNET_INVALID_SOCKET){ TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- FD_ACCEPT(fd=%d)", transport->description, fd); addSocket(fd, transport->master->type, transport, tsk_true, tsk_false); TSK_RUNNABLE_ENQUEUE(transport, event_accepted, transport->callback_data, fd); if(active_socket->tlshandle){ transport_socket_xt* tls_socket; if((tls_socket = getSocket(context, fd))){ if(tnet_tls_socket_accept(tls_socket->tlshandle) != 0){ TSK_RUNNABLE_ENQUEUE(transport, event_closed, transport->callback_data, fd); tnet_transport_remove_socket(transport, &fd); TNET_PRINT_LAST_ERROR("SSL_accept() failed"); continue; } } } } else{ TNET_PRINT_LAST_ERROR("accept(%d) failed", active_socket->fd); remove_socket = 1; } } else{ TSK_DEBUG_INFO("Closing socket with fd = %d because ioctlt() returned zero or failed", active_socket->fd); remove_socket = 1; } if(remove_socket){ fd = active_socket->fd; tnet_transport_remove_socket(transport, &active_socket->fd); TSK_RUNNABLE_ENQUEUE(transport, event_closed, transport->callback_data, fd); continue; } goto TNET_POLLIN_DONE; } if(len <= 0){ context->ufds[i].revents &= ~TNET_POLLIN; goto TNET_POLLIN_DONE; } if(!(buffer = tsk_calloc(len, sizeof(uint8_t)))){ TSK_DEBUG_ERROR("TSK_CALLOC FAILED"); goto TNET_POLLIN_DONE; } // Receive the waiting data if(active_socket->tlshandle){ int isEncrypted; tsk_size_t tlslen = len; if((ret = tnet_tls_socket_recv(active_socket->tlshandle, &buffer, &tlslen, &isEncrypted)) == 0){ if(isEncrypted){ TSK_FREE(buffer); goto TNET_POLLIN_DONE; } if(ret == 0){ len = ret = tlslen; } } } else { if(is_stream){ ret = tnet_sockfd_recv(active_socket->fd, buffer, len, 0); } else { ret = tnet_sockfd_recvfrom(active_socket->fd, buffer, len, 0, (struct sockaddr*)&remote_addr); } } if(ret < 0){ TSK_FREE(buffer); removeSocket(i, context); TNET_PRINT_LAST_ERROR("recv/recvfrom have failed."); goto TNET_POLLIN_DONE; } if((len != (tsk_size_t)ret) && len){ len = (tsk_size_t)ret; // buffer = tsk_realloc(buffer, len); } e = tnet_transport_event_create(event_data, transport->callback_data, active_socket->fd); e->data = buffer; e->size = len; e->remote_addr = remote_addr; TSK_RUNNABLE_ENQUEUE_OBJECT_SAFE(TSK_RUNNABLE(transport), e); TNET_POLLIN_DONE: context->ufds[i].revents &= ~TNET_POLLIN; } /*================== TNET_POLLOUT ==================*/ if(context->ufds[i].revents & TNET_POLLOUT){ TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- TNET_POLLOUT", transport->description); if(!active_socket->connected){ active_socket->connected = tsk_true; TSK_RUNNABLE_ENQUEUE(transport, event_connected, transport->callback_data, active_socket->fd); } context->ufds[i].events &= ~TNET_POLLOUT; } /*================== TNET_POLLPRI ==================*/ if(context->ufds[i].revents & TNET_POLLPRI){ TSK_DEBUG_INFO("NETWORK EVENT FOR SERVER [%s] -- TNET_POLLPRI", transport->description); } context->ufds[i].revents = 0; }/* for */ done: /* unlock context */ tsk_safeobj_unlock(context); } /* while */ bail: TSK_DEBUG_INFO("Stopped [%s] server with IP {%s} on port {%d}", transport->description, transport->master->ip, transport->master->port); return 0; }
// reset the oneshot inotify watch, so it will trip on the next create. // consume pending events, if there are any, and re-watch the directory. // if the pid has changed since last time, watch the new directory. // return 0 on success // return negative on error (errno) static int udev_monitor_fs_watch_reset( struct udev_monitor* monitor ) { int rc = 0; bool inotify_triggerred = false; // was inotify triggerred? char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event)))); // see inotify(7) struct pollfd pfd[1]; pfd[0].fd = monitor->inotify_fd; pfd[0].events = POLLIN; // reset the watch by consuming all its events (should be at most one) while( 1 ) { // do we have data? rc = poll( pfd, 1, 0 ); if( rc <= 0 ) { // out of data, or error if( rc < 0 ) { rc = -errno; if( rc == -EINTR ) { // shouldn't really happen since the timeout for poll is zero, // but you never know... continue; } log_error("poll(%d) rc = %d\n", monitor->inotify_fd, rc ); rc = 0; } break; } // at least one event remaining // consume it rc = read( monitor->inotify_fd, buf, 4096 ); if( rc == 0 ) { break; } if( rc < 0 ) { rc = -errno; if( rc == -EINTR ) { continue; } else if( rc == -EAGAIN || rc == -EWOULDBLOCK ) { rc = 0; break; } } // got one event inotify_triggerred = true; } // has the PID changed? // need to regenerate events path if( getpid() != monitor->pid ) { log_trace("Switch PID from %d to %d", monitor->pid, getpid()); udev_monitor_fs_events_path( "", monitor->events_dir, monitor->slot ); rc = mkdir( monitor->events_dir, 0700 ); if( rc != 0 ) { rc = -errno; if( rc != -EEXIST ) { log_error("mkdir('%s') rc = %d\n", monitor->events_dir, rc ); return rc; } else { rc = 0; } } monitor->events_wd = inotify_add_watch( monitor->inotify_fd, monitor->events_dir, UDEV_FS_WATCH_DIR_FLAGS ); if( monitor->events_wd < 0 ) { rc = -errno; log_error("inotify_add_watch('%s') rc = %d\n", monitor->events_dir, rc ); return rc; } monitor->pid = getpid(); // TODO: what about events that the child was supposed to receive? // the parent forks, receives one or more events, and the child wakes up, and will miss them // if we only do the above. // we need to (try to) consume them here } rc = inotify_add_watch( monitor->inotify_fd, monitor->events_dir, UDEV_FS_WATCH_DIR_FLAGS ); if( rc < 0 ) { rc = -errno; log_error("inotify_add_watch(%d) rc = %d", monitor->inotify_fd, rc ); } return rc; }
static int se_try_read(lua_State *L, int fd, int size, sds *pcache) { char sbuf[4 << 10]; char *cache = *pcache; char *buf; int bufsize; int nread; if (cache) { bufsize = sdsavail(cache); buf = cache + sdslen(cache); printf("continue try read: %d / %d\n", bufsize, size); } else { // first try bufsize = size > 0 ? size : size < 0 ? -size : sizeof(sbuf); if (bufsize <= sizeof(sbuf)) { buf = sbuf; } else { cache = sdsnewlen(NULL, bufsize); oom_check(cache); sdsclear(cache); *pcache = cache; buf = cache; } printf("try read: %d / %d\n", bufsize, size); } nread = read(fd, buf, bufsize); if (nread > 0) { if (size <= 0 || nread == bufsize) { // done if (cache) { lua_pushlstring(L, cache, sdslen(cache) + nread); sdsfree(cache); *pcache = NULL; } else { lua_pushlstring(L, buf, nread); } printf("read done: %d / %d / %d\n", nread, bufsize, size); return 1; } // partial read if (!cache) { cache = sdsnewlen(NULL, bufsize); oom_check(cache); sdsclear(cache); *pcache = cache; memcpy(cache, buf, nread); } sdsIncrLen(cache, nread); printf("partial read: %d / %d / %d\n", nread, bufsize, size); return -1; } if (nread == 0) return se_read_error(L, pcache, "EOF"); if (errno == EAGAIN || errno == EWOULDBLOCK) return -1; se_assert(L, errno != EBADF, "read(%d) error", fd); return se_read_error(L, pcache, strerror(errno)); }
void taillineoffset(int fd, char *fn, int isregfile, ssize_t len) { ssize_t n, i, halfbuf; if (offset > 0) /* forwards through file */ { offset--; while(1) { if ((n = read(fd, buf, bufsize)) < 0) fatal(SYSERR, fn); if (n == 0) { offset = 0; break; } for (i = 0; i < n && offset > 0; i++) if (buf[i] == '\n') offset--; if (offset == 0) { offset = i; break; } } if (write(STDOUT_FILENO, buf + offset, n - offset) != n - offset) fatal(SYSERR, "stdout"); copytoeof(fd, fn); } else /* backwards through file; remember that offset is negative */ { if (isregfile && len > 0) /* should be seekable, so we'll do so */ { n = (len - bufsize) < 0 ? 0 : len - bufsize; if (lseek(fd, (off_t)n, SEEK_SET) == (off_t)-1) fatal(SYSERR, fn); if ((n = read(fd, buf, bufsize)) < 0) fatal(SYSERR, fn); if (buf[n-1] == '\n') offset--; for (i = n - 1; i >= 0 && offset < 0; i--) if (buf[i] == '\n') offset++; if (offset == 0) offset = i + 2; else offset = 0; len = n - offset; if (write(STDOUT_FILENO, buf + offset, len) != len) fatal(SYSERR, "stdout"); } else { halfbuf = bufsize / 2; if ((n = read(fd, buf, bufsize)) < 0) fatal(SYSERR, fn); if (n < bufsize) /* we've got the whole file */ { if (n == 0) offset = 0; else { if (buf[n-1] == '\n') offset--; for (i = n - 1; i >= 0 && offset < 0; i--) if (buf[i] == '\n') offset++; if (offset == 0) offset = i + 2; else offset = 0; } len = n - offset; } else /* we haven't got the whole file */ { while(1) /* page through the file, half a buffer at a time */ { memcpy(buf, buf + halfbuf, halfbuf); if ((n = read(fd, buf + halfbuf, halfbuf)) < 0) fatal(SYSERR, fn); else if (n < halfbuf) break; } if (buf[halfbuf+n-1] == '\n') offset--; for (i = halfbuf + n - 1; i >= 0 && offset < 0; i--) if (buf[i] == '\n') offset++; if (offset == 0) offset = i + 2; else offset = 0; len = halfbuf + n - offset; } if (write(STDOUT_FILENO, buf + offset, len) != len) fatal(SYSERR, "stdout"); } } }
int do_screenshot(char *pdest) { int rc = 0 ; int i ; int fd ; int fd_ss ; off_t offset ; int xres = SCREENW ; int yres = SCREENH ; int bpp = BPP ; int imgsize = IMGSIZE ; int bperrow = IMGSIZE / SCREENH ; struct fb_fix_screeninfo finfo; struct fb_var_screeninfo vinfo; const struct bmpfile_magic magichdr = { { 'B', 'M'} } ; struct bmpfile_header file_h ; BITMAPINFOHEADER dib_h ; const struct rgba_color colortab[NCOLORS] = { { 0xff, 0xff, 0xff, 0 }, { 0xee, 0xee, 0xee, 0 }, { 0xdd, 0xdd, 0xdd, 0 }, { 0xcc, 0xcc, 0xcc, 0 }, { 0xbb, 0xbb, 0xbb, 0 }, { 0xaa, 0xaa, 0xaa, 0 }, { 0x99, 0x99, 0x99, 0 }, { 0x88, 0x88, 0x88, 0 }, { 0x77, 0x77, 0x77, 0 }, { 0x66, 0x66, 0x66, 0 }, { 0x55, 0x55, 0x55, 0 }, { 0x44, 0x44, 0x44, 0 }, { 0x33, 0x33, 0x33, 0 }, { 0x22, 0x22, 0x22, 0 }, { 0x11, 0x11, 0x11, 0 }, { 0x00, 0x00, 0x00, 0 }, } ; memset(&file_h, 0, sizeof(file_h)) ; file_h.bmp_offset = sizeof(magichdr) + sizeof(file_h) + sizeof(dib_h) + sizeof(colortab) ; file_h.filesz = file_h.bmp_offset + IMGSIZE ; memset(&dib_h, 0, sizeof(dib_h)) ; if ((fd = open(FRAMEBUFFER, O_RDONLY)) != -1) { if ((fd_ss = open(pdest, O_WRONLY| O_CREAT)) != -1) { memset(&vinfo, 0, sizeof(vinfo)); memset(&finfo, 0, sizeof(finfo)); ////ioctl(fd, FBIOGET_FSCREENINFO, &finfo) ; if ((ioctl(fd, FBIOGET_VSCREENINFO, &vinfo)) != -1) { xres = vinfo.xres ; yres = vinfo.yres ; bpp = vinfo.bits_per_pixel ; imgsize = ((xres/(8/bpp)) * yres) ; bperrow = imgsize / yres ; if (xres > SCREENW) { dib_h.hres = KDXDPM ; dib_h.vres = KDXDPM ; } } dib_h.header_sz = sizeof(BITMAPINFOHEADER) ; dib_h.width = xres ; dib_h.height = yres ; dib_h.nplanes = 1 ; dib_h.bitspp = bpp ; dib_h.compress_type = BI_RGB ; dib_h.bmp_bytesz = imgsize ; // KDX has different screen resolution than the default K3 ... dib_h.hres = ((xres > SCREENW) ? KDXDPM : K3DPM) ; dib_h.vres = dib_h.hres ; dib_h.ncolors = NCOLORS ; dib_h.nimpcolors = 0 ; { unsigned char rowbuf[bperrow] ; write(fd_ss, &magichdr, sizeof(magichdr)) ; write(fd_ss, &file_h, sizeof(file_h)) ; write(fd_ss, &dib_h, sizeof(dib_h)) ; write(fd_ss, &colortab, sizeof(colortab)) ; for (i = 0 ; i < yres ; i++) { offset = imgsize - (bperrow) * (i -1) ; lseek(fd, offset, SEEK_SET) ; read(fd, &rowbuf, bperrow) ; write(fd_ss, &rowbuf, bperrow) ; } } close(fd_ss) ; } else { //fprintf(stderr, "Can't open %s\n",pdest) ; close(fd) ; rc = 1 ; } } else { //fprintf(stderr, "Can't open %s\n",FRAMEBUFFER) ; rc = 1 ; } return rc ; }
void masterconn_read(masterconn *eptr,double now) { int32_t i; uint32_t type,leng; const uint8_t *ptr; uint32_t rbleng,rbpos; uint8_t err,hup; static uint8_t *readbuff = NULL; static uint32_t readbuffsize = 0; if (eptr == NULL) { if (readbuff != NULL) { free(readbuff); } readbuff = NULL; readbuffsize = 0; return; } if (readbuffsize==0) { readbuffsize = 65536; readbuff = malloc(readbuffsize); passert(readbuff); } rbleng = 0; err = 0; hup = 0; for (;;) { i = read(eptr->sock,readbuff+rbleng,readbuffsize-rbleng); if (i==0) { hup = 1; break; } else if (i<0) { if (ERRNO_ERROR) { err = 1; } break; } else { stats_bytesin+=i; rbleng += i; if (rbleng==readbuffsize) { readbuffsize*=2; readbuff = realloc(readbuff,readbuffsize); passert(readbuff); } else { break; } } } if (rbleng>0) { eptr->lastread = now; } rbpos = 0; while (rbpos<rbleng) { if ((rbleng-rbpos)>=eptr->input_bytesleft) { memcpy(eptr->input_startptr,readbuff+rbpos,eptr->input_bytesleft); i = eptr->input_bytesleft; } else { memcpy(eptr->input_startptr,readbuff+rbpos,rbleng-rbpos); i = rbleng-rbpos; } rbpos += i; eptr->input_startptr+=i; eptr->input_bytesleft-=i; if (eptr->input_bytesleft>0) { break; } if (eptr->input_packet == NULL) { ptr = eptr->input_hdr; type = get32bit(&ptr); leng = get32bit(&ptr); if (leng>MaxPacketSize) { syslog(LOG_WARNING,"Master packet too long (%"PRIu32"/%u)",leng,MaxPacketSize); eptr->input_end = 1; return; } eptr->input_packet = malloc(offsetof(in_packetstruct,data)+leng); passert(eptr->input_packet); eptr->input_packet->next = NULL; eptr->input_packet->type = type; eptr->input_packet->leng = leng; eptr->input_startptr = eptr->input_packet->data; eptr->input_bytesleft = leng; } if (eptr->input_bytesleft>0) { continue; } if (eptr->input_packet != NULL) { *(eptr->inputtail) = eptr->input_packet; eptr->inputtail = &(eptr->input_packet->next); eptr->input_packet = NULL; eptr->input_bytesleft = 8; eptr->input_startptr = eptr->input_hdr; } } if (hup) { syslog(LOG_NOTICE,"connection was reset by Master"); eptr->input_end = 1; } else if (err) { mfs_errlog_silent(LOG_NOTICE,"read from Master error"); eptr->input_end = 1; } }
/* * Given a cache file, return the contents as a list of importable pools. * poolname or guid (but not both) are provided by the caller when trying * to import a specific pool. */ nvlist_t * zpool_find_import_cached(libzfs_handle_t *hdl, const char *cachefile, char *poolname, uint64_t guid) { char *buf; int fd; struct stat64 statbuf; nvlist_t *raw, *src, *dst; nvlist_t *pools; nvpair_t *elem; char *name; uint64_t this_guid; boolean_t active; verify(poolname == NULL || guid == 0); if ((fd = open(cachefile, O_RDONLY)) < 0) { zfs_error_aux(hdl, "%s", strerror(errno)); (void) zfs_error(hdl, EZFS_BADCACHE, dgettext(TEXT_DOMAIN, "failed to open cache file")); return (NULL); } if (fstat64(fd, &statbuf) != 0) { zfs_error_aux(hdl, "%s", strerror(errno)); (void) close(fd); (void) zfs_error(hdl, EZFS_BADCACHE, dgettext(TEXT_DOMAIN, "failed to get size of cache file")); return (NULL); } if ((buf = zfs_alloc(hdl, statbuf.st_size)) == NULL) { (void) close(fd); return (NULL); } if (read(fd, buf, statbuf.st_size) != statbuf.st_size) { (void) close(fd); free(buf); (void) zfs_error(hdl, EZFS_BADCACHE, dgettext(TEXT_DOMAIN, "failed to read cache file contents")); return (NULL); } (void) close(fd); if (nvlist_unpack(buf, statbuf.st_size, &raw, 0) != 0) { free(buf); (void) zfs_error(hdl, EZFS_BADCACHE, dgettext(TEXT_DOMAIN, "invalid or corrupt cache file contents")); return (NULL); } free(buf); /* * Go through and get the current state of the pools and refresh their * state. */ if (nvlist_alloc(&pools, 0, 0) != 0) { (void) no_memory(hdl); nvlist_free(raw); return (NULL); } elem = NULL; while ((elem = nvlist_next_nvpair(raw, elem)) != NULL) { verify(nvpair_value_nvlist(elem, &src) == 0); verify(nvlist_lookup_string(src, ZPOOL_CONFIG_POOL_NAME, &name) == 0); if (poolname != NULL && strcmp(poolname, name) != 0) continue; verify(nvlist_lookup_uint64(src, ZPOOL_CONFIG_POOL_GUID, &this_guid) == 0); if (guid != 0) { verify(nvlist_lookup_uint64(src, ZPOOL_CONFIG_POOL_GUID, &this_guid) == 0); if (guid != this_guid) continue; } if (pool_active(hdl, name, this_guid, &active) != 0) { nvlist_free(raw); nvlist_free(pools); return (NULL); } if (active) continue; if ((dst = refresh_config(hdl, src)) == NULL) { nvlist_free(raw); nvlist_free(pools); return (NULL); } if (nvlist_add_nvlist(pools, nvpair_name(elem), dst) != 0) { (void) no_memory(hdl); nvlist_free(dst); nvlist_free(raw); nvlist_free(pools); return (NULL); } nvlist_free(dst); } nvlist_free(raw); return (pools); }
// How to handle static variables with multiple sensors? objects? add to gpspacket? int read_gps(struct gps *gpsData_ptr) { cyg_io_handle_t port_handle; cyg_serial_buf_info_t buff_info; unsigned int len = sizeof (buff_info); // get serial port handle cyg_io_lookup( gpsData_ptr->portName, &port_handle ); cyg_io_get_config (port_handle, CYG_IO_GET_CONFIG_SERIAL_BUFFER_INFO,\ &buff_info, &len); unsigned int bytesInBuffer = buff_info.rx_count; unsigned int bytesReadThisCall = 0; unsigned short msgPayloadSize = 0, bytesToRead = 0, bytesRead = 0; unsigned long CRC_computed, CRC_read; int j, status =0; // Initialization of persistent local buffer if (gpsData_ptr->localBuffer == NULL) { gpsData_ptr->localBuffer = (unsigned char*) malloc (1024 * sizeof (unsigned char)); } // First check if there are any bytes in the serial buffer, return if none if( bytesInBuffer == 0 ) return -1; // Get localBuffer stored in gps packet. This is to keep the following code readable localBuffer = gpsData_ptr->localBuffer; bytesInLocalBuffer= gpsData_ptr->bytesInLocalBuffer; readState = gpsData_ptr->readState; while (bytesReadThisCall < bytesInBuffer){ switch (readState){ case 0: //Look for packet header bytes // Read in up to 3 bytes to the first open location in the local buffer //fprintf(stderr,"bytesInLocalBuffer is %d\n",bytesInLocalBuffer); bytesRead = read(gpsData_ptr->port,&localBuffer[bytesInLocalBuffer],3-bytesInLocalBuffer); //fprintf(stderr,"The first three bytes are %0X %0X %0X\n",localBuffer[0],localBuffer[1],localBuffer[2]); //fprintf(stderr,"bytesRead is %d\n",bytesRead); //fprintf(stderr,"Read %d bytes, The first three bytes are %0X %0X %0X\n", bytesRead,localBuffer[0],localBuffer[1],localBuffer[2]); bytesReadThisCall += bytesRead; // keep track of bytes read during this call if (localBuffer[0] == 0xAA){ // Check for first header byte bytesInLocalBuffer = 1; //fprintf(stderr, "case 0, 0xAA header type \n"); if (localBuffer[1] == 0x44){ // Check for second header byte bytesInLocalBuffer = 2; if (localBuffer[2] == 0x12){ // Check for third header byte bytesInLocalBuffer = 3; readState++; } } } else { gpsData_ptr->err_type = noPacketHeader; } break; // end case 0 case 1: // Look for block ID and data length // Read 28 Header Bytes bytesToRead = 28 - bytesInLocalBuffer; // Read in bytes to the last location in the local buffer bytesRead = read(gpsData_ptr->port,&localBuffer[bytesInLocalBuffer],bytesToRead); bytesInLocalBuffer += bytesRead; // keep track of bytes in local buffer bytesReadThisCall += bytesRead; // keep track of bytes read during this call if (bytesRead == bytesToRead){ readState++; //fprintf (stderr,"<GPS>: Got msgID: %d and Data Length: %d\n", localBuffer[5]*256 + localBuffer[4], localBuffer[9]*256 + localBuffer[8]); //printf ("<GPS>: localBuffer[0] = %02X localBuffer[1] = %02X localBuffer[2] = %02X localBuffer[3] = %02X localBuffer[4] = %02X localBuffer[5] = %02X \n", localBuffer[0], localBuffer[1], localBuffer[2], localBuffer[3], localBuffer[4], localBuffer[5]); } else{ gpsData_ptr->err_type = incompletePacket; } break; // end case 1 case 2: //Read payload // Find message payload size msgPayloadSize = localBuffer[9]*256 + localBuffer[8]; // data is in little endian format // Error checking on payload size. If size is bigger than expected, dump packet if(msgPayloadSize > GPS_MAX_MSG_SIZE){ gpsData_ptr->err_type = incompletePacket; reset_localBuffer(); } // Find how many bytes need to be read for the total message (Sync (3) + Remaining Header (25) + Payload - bytes already read ) bytesToRead = msgPayloadSize + 28 - bytesInLocalBuffer; //printf("bytesInLocalBuffer is %d bytesToRead is %d \n",bytesInLocalBuffer,bytesToRead); // Read in the remainder of the message to the local buffer, starting at the first empty location bytesRead = read (gpsData_ptr->port, &localBuffer[bytesInLocalBuffer], bytesToRead); bytesInLocalBuffer += bytesRead; // keep track of bytes in local buffer bytesReadThisCall += bytesRead; // keep track of bytes read during this call if (bytesRead == bytesToRead){ //printf ("<GPS>: Got complete message! Tried for %d, got %d\n",bytesToRead,bytesRead); readState++; } else { gpsData_ptr->err_type = incompletePacket; } break; // end case 2 case 3: // read CRC bytes (4 bytes) bytesToRead = 4; bytesRead = read (gpsData_ptr->port, &localBuffer[bytesInLocalBuffer], bytesToRead); bytesInLocalBuffer += bytesRead; bytesReadThisCall += bytesRead; if(bytesRead == bytesToRead) { // CRC verification CRC_computed = CalculateBlockCRC32(bytesInLocalBuffer-4,localBuffer); endian_swap(localBuffer,140,4); CRC_read = *(uint32_t *) (localBuffer+140); if (CRC_computed == CRC_read) { gpsData_ptr->err_type = data_valid; parse_gps(gpsData_ptr); //fprintf (stderr,"<GPS t = %9.3lf>: Success!\n",gpsData_ptr->GPS_TOW); } else{ send_status("GPS CRC ERR"); //fprintf (stderr,"<GPS>: Checksum mismatch!\n"); /* ============= DEBUG CHECKSUM ERROR ================ fprintf (stderr,"<GPS %d>: Checksum mismatch! Buffer: %02X%02X%02X%02X Read: %08lX Computed: %08lX\n",localBuffer[5]*256 + localBuffer[4],localBuffer[140],localBuffer[141],localBuffer[142],localBuffer[143],CRC_read,CRC_computed); fprintf (stderr,"Hex: \n"); for (j = 0; j < bytesInLocalBuffer; j++) { fprintf(stderr,"%02X ",localBuffer[j]); if(j%8==7) fprintf(stderr,"\n"); } */ gpsData_ptr->err_type = checksum_err; } reset_localBuffer(); } else{ //printf ("\n<GPS>: Didn't get complete message. Tried for %d, got %d",bytesToRead,bytesRead); gpsData_ptr->err_type= incompletePacket; status = 0; } break; // end case 3 default: reset_localBuffer(); printf ("\n<GPS>: Why are you here?"); status = 0; break; // end default } // end switch (readState) } // end while (bytesReadThisCall < bytesInBuffer) // Store local buffer in gps packet gpsData_ptr->localBuffer = localBuffer; gpsData_ptr->bytesInLocalBuffer = bytesInLocalBuffer; gpsData_ptr->readState = readState; return status; }
int main(int argc, char* argv[] ) { FILE* fp; /* Remove all existing log files */ remove(FIFO_PIPE); int pid; //Initialize first process to ID 1 int msgId, namedPipe; if (access(FIFO_PIPE, F_OK) == -1) { printf("Creating named pipe...\n"); namedPipe = mkfifo(FIFO_PIPE, 0777); if (namedPipe != 0) { /* the fifo name */ /* check if fifo already /* if not then, create the fifo*/ printf("Could not create fifo %s\n", FIFO_PIPE); exit(EXIT_FAILURE); } printf("Named pipe created successfully: %s\n",FIFO_PIPE); } pid = (int)fork(); if(pid == 0) { /* Child 1 section */ printf("Opening FIFO named pipe..\n"); /* Open the named pipe for read only on child process 2 */ namedPipe = open(FIFO_PIPE, O_RDONLY); printf("Opening success..\n"); //fclose(fp); fp = fopen("TESTLOG.txt", "a+"); /* Open a log file */ printf("Parent Process 1: reading from Child 3..\n"); while(read(namedPipe, tmpBuffer, sizeof(tmpBuffer))) { /* Read all the buffers from pipe */ sscanf(tmpBuffer, "%d%[^\n]",&msgId, buffer); /* Break the message into the ID and message */ printf("MSG: %d, %s\n", msgId, buffer); if(msgId == 1) { /* Message is belongs to the child */ strcat(buffer, KEEP_MSG); /* Append message will "keep" word*/ } else { /* Message is NOT belongs to the child */ //write(pipeFd[1], tmpBuffer, sizeof(tmpBuffer)); /* Forward the message to next child */ strcat(buffer, FWD_MSG); /* Append message will "forward" word*/ } fprintf(fp, "%d%s\n",msgId,buffer); /* Write the messages into the log file */ } printf("Close file PP LOG\n"); fclose(fp); return 0; } else { /* Parent or root section */ printf("PARENT: Opening FIFO named pipe..\n"); /* Open the named pipe for read only on child process 2 */ namedPipe = open(FIFO_PIPE, O_WRONLY); printf("PARENT: Opened FIFO successfully.\n"); /* Write to Childs from Message File*/ fp = fopen(C2_TXT, "r"); /* Open Message File */ while(fgets(tmpBuffer, (sizeof(tmpBuffer) + 2), fp)) { /* Read all the messages from the file */ printf("%s\n", tmpBuffer ); write(namedPipe, tmpBuffer, sizeof(tmpBuffer)); } //c2Status = 1; /* File is logged */ printf("PARENT: Close file\n"); fclose(fp); } return EXIT_SUCCESS; }