Beispiel #1
0
/**
 * Handle errors during read, write, connect and accept
 * @return TRUE if non fatal, FALSE if non fatal and retry
 */
static int handle_error(int code, ssl_connection *ssl) {
        int ssl_error = SSL_get_error(ssl->handler, code);

        switch (ssl_error) {

                case SSL_ERROR_NONE:
                        return TRUE;

                case SSL_ERROR_WANT_READ:
                        if (can_read(ssl->socket, SSL_TIMEOUT))
                                return TRUE;
                        LogError("SSL read timeout error\n");
                        break;

                case SSL_ERROR_WANT_WRITE:
                        if (can_write(ssl->socket, SSL_TIMEOUT))
                                return TRUE;
                        LogError("SSL write timeout error\n");
                        break;

                case SSL_ERROR_SYSCALL:
                        LogError("SSL syscall error: %s\n", STRERROR);
                        break;

                case SSL_ERROR_SSL:
                        LogError("SSL engine error: %s\n", SSLERROR);
                        break;

                default:
                        LogError("SSL error\n");
                        break;

        }

        return FALSE;
}
Beispiel #2
0
int main(int argc, char** argv) {
    struct timeval start_time, end_time;
    readstat_error_t error = READSTAT_OK;
    char *input_filename = NULL;
    char *catalog_filename = NULL;
    char *output_filename = NULL;

    if (argc == 2 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) {
        print_version();
        return 0;
    } else if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
        print_usage(argv[0]);
        return 0;
    } if (argc == 3) {
        if (!can_read(argv[1]) || !can_write(argv[2])) {
            print_usage(argv[0]);
            return 1;
        }
        input_filename = argv[1];
        output_filename = argv[2];
    } else if (argc == 4) {
        if (!can_read(argv[1]) || !is_catalog(argv[2]) || !can_write(argv[3])) {
            print_usage(argv[0]);
            return 1;
        }
        input_filename = argv[1];
        catalog_filename = argv[2];
        output_filename = argv[3];
    } else {
        print_usage(argv[0]);
        return 1;
    }

    int input_format = format(input_filename);
    int output_format = format(output_filename);

    gettimeofday(&start_time, NULL);

    int fd = open(output_filename, O_CREAT | O_WRONLY | O_EXCL, 0644);
    if (fd == -1) {
        dprintf(STDERR_FILENO, "Error opening %s for writing: %s\n", output_filename, strerror(errno));
        return 1;
    }

    readstat_parser_t *pass1_parser = readstat_parser_init();
    readstat_parser_t *pass2_parser = readstat_parser_init();
    readstat_writer_t *writer = readstat_writer_init();
    readstat_writer_set_file_label(writer, "Created by ReadStat <https://github.com/WizardMac/ReadStat>");

    rs_ctx_t *rs_ctx = ctx_init();

    rs_ctx->writer = writer;
    rs_ctx->out_fd = fd;
    rs_ctx->out_format = output_format;

    readstat_set_data_writer(writer, &write_data);

    // Pass 1 - Collect fweight and value labels
    readstat_set_error_handler(pass1_parser, &handle_error);
    readstat_set_info_handler(pass1_parser, &handle_info);
    readstat_set_value_label_handler(pass1_parser, &handle_value_label);
    readstat_set_fweight_handler(pass1_parser, &handle_fweight);

    if (catalog_filename) {
        error = parse_file(pass1_parser, catalog_filename, RS_FORMAT_SAS_CATALOG, rs_ctx);
    } else {
        error = parse_file(pass1_parser, input_filename, input_format, rs_ctx);
    }
    if (error != READSTAT_OK)
        goto cleanup;

    // Pass 2 - Parse full file
    readstat_set_error_handler(pass2_parser, &handle_error);
    readstat_set_info_handler(pass2_parser, &handle_info);
    readstat_set_variable_handler(pass2_parser, &handle_variable);
    readstat_set_value_handler(pass2_parser, &handle_value);

    error = parse_file(pass2_parser, input_filename, input_format, rs_ctx);
    if (error != READSTAT_OK)
        goto cleanup;

    gettimeofday(&end_time, NULL);

    dprintf(STDERR_FILENO, "Converted %ld variables and %ld rows in %.2lf seconds\n",
            rs_ctx->var_count, rs_ctx->row_count, 
            (end_time.tv_sec + 1e-6 * end_time.tv_usec) -
            (start_time.tv_sec + 1e-6 * start_time.tv_usec));

cleanup:
    readstat_parser_free(pass1_parser);
    readstat_parser_free(pass2_parser);
    readstat_writer_free(writer);
    ctx_free(rs_ctx);

    close(fd);

    if (error != READSTAT_OK) {
        dprintf(STDERR_FILENO, "%s\n", readstat_error_message(error));
        unlink(output_filename);
        return 1;
    }

    return 0;
}
Beispiel #3
0
int CAN::read(CANMessage &msg, int handle) {
    lock();
    int ret = can_read(&_can, &msg, handle);
    unlock();
    return ret;
}
Beispiel #4
0
int main(int argc, char **argv)
{
	int size;
	int fd;
	unsigned long id;  
	unsigned char data[8];
        char *port = "/dev/can1";	// use "1" to "4" for steinhoff
        int opt;
	int status;
	int read_err = 0;
	int verbose = 0;
	int msg_count = 0;

        while ((opt = getopt(argc, argv, "p:v")) != -1) {
                switch (opt) {
                  case 'p':
                        port = strdup(optarg);
                        break;
                  case 'v':
                        verbose = 1; 
                        break;

                  default:
                        printf("Usage: %s -p <port>\n", argv[0]);
                        exit(1);
                }
        }

	printf("can_rx: trying to open %s\n", port); 
	fflush(stdout);

	fd = can_open(port, O_RDONLY);

	if (fd == -1)
		exit(EXIT_FAILURE);	// error message printed by can_open 

	printf("program %s, device name %s, fd: %d\n", argv[0], port, fd);
	fflush(stdout);

        if(setjmp(exit_env) != 0) {
		printf("%d messages, %d read errors\n", msg_count, read_err);
		if (fd != -1)
			status = can_close(&fd);
		if (status != -1)			
			exit(EXIT_SUCCESS);
		else
			exit(EXIT_FAILURE);	// can_close prints error info
        } else
		sig_ign(sig_list, sig_hand);

	for(;;) {
		int i;
		id = 0;		
		size = can_read(fd,&id,(char *)NULL,data,8);
		if (size < 0) 
			read_err++;	
		else {
			msg_count++;
			if (verbose) {
				printf(" %5lu ", id);		
				printf(" %u ", size);		
				for (i = 0; i < size; i++)
					printf("%03hhu ",data[i]);
				printf("\n");
				fflush(stdout);
			}
		}
	}
}
Beispiel #5
0
int CAN::read(CANMessage &msg) {
    return can_read(&_can, &msg);
}
Beispiel #6
0
AReader::Error ReaderJpeg::read( imageCache &cache, const uint8_t* data, unsigned length, QString format ) const{
	if( !can_read( data, length, format ) )
		return ERROR_TYPE_UNKNOWN;
	
	try{
		cache.set_info( 1 );
		JpegDecompress jpeg( data, length );
		jpeg.cinfo.client_data = &cache;
		
		//Save application data, we are interested in ICC profiles and EXIF metadata
		jpeg.saveMarker( ICC_META_TEST );
		jpeg.saveMarker( EXIF_META_TEST );
		/* READ EVERYTHING!
		jpeg_save_markers( &jpeg.cinfo, JPEG_COM, 0xFFFF );
		for( unsigned i=0; i<16; i++ )
			jpeg_save_markers( &jpeg.cinfo, JPEG_APP0+i, 0xFFFF );
		//*/
		
		//Read header and set-up image
		jpeg.readHeader();
		jpeg_start_decompress( &jpeg.cinfo );
		
		bool is_gray;
		switch( jpeg.cinfo.out_color_components ){
			case 1: is_gray = true; break;
			case 3: is_gray = false; break;
			default: return ERROR_UNSUPPORTED;
		}
		QImage frame( jpeg.cinfo.output_width, jpeg.cinfo.output_height, QImage::Format_RGB32 );
		
		//Read image
		auto buffer = std::make_unique<JSAMPLE[]>( jpeg.bytesPerLine() );
		JSAMPLE* arr[1] = { buffer.get() };
		while( jpeg.cinfo.output_scanline < jpeg.cinfo.output_height ){
			auto out = (QRgb*)frame.scanLine( jpeg.cinfo.output_scanline );
			jpeg_read_scanlines( &jpeg.cinfo, arr, 1 );
			
			if( is_gray )
				for( unsigned ix=0; ix<jpeg.cinfo.output_width; ix++ )
					out[ix] = qRgb( buffer[ix], buffer[ix], buffer[ix] );
			else
				for( unsigned ix=0; ix<jpeg.cinfo.output_width; ix++ )
					out[ix] = qRgb( buffer[ix*3+0], buffer[ix*3+1], buffer[ix*3+2] );
		}
		
		//Check all markers
		for( auto marker = jpeg.cinfo.marker_list; marker; marker = marker->next ){
			//Check for and read ICC profile
			if( ICC_META_TEST.validate( marker ) ){
				cache.set_profile( ColorProfile::fromMem(
						marker->data        + ICC_META_TEST.length
					,	marker->data_length - ICC_META_TEST.length
					) );
			}
			if( EXIF_META_TEST.validate( marker ) ){
				meta exif(
						marker->data        + EXIF_META_TEST.length
					,	marker->data_length - EXIF_META_TEST.length
					);
				
				cache.set_orientation( exif.get_orientation() );
				
				//Read thumbnail
				cache.thumbnail = exif.get_thumbnail();
				//TODO: We actually want to read this BEFORE the full image ;)
				
				//TODO: Actually do something with this info. Perhaps check for a profile as well!
			}
			/* Save data to file for debugging
			QFile f( "Jpeg marker " + QString::number(marker->marker-JPEG_APP0) + ".bin" );
			f.open( QIODevice::WriteOnly );
			f.write( (char*)marker->data, marker->data_length );
			//*/
		}
		jpeg_finish_decompress( &jpeg.cinfo );
		
		cache.add_frame( frame, 0 );
		
		//Cleanup and return
		cache.set_fully_loaded();
		return ERROR_NONE;
	}
	catch( int err_code ){
		switch( err_code ){
			case JERR_NO_SOI: return ERROR_TYPE_UNKNOWN;
			default: return ERROR_FILE_BROKEN;
		};
	}
}
Beispiel #7
0
/*PAGE
 *
 * command_retrieve
 *
 * Perform the "RETR" command (send file to client).
 *
 * Input parameters:
 *   info - corresponding SessionInfo structure
 *   char *filename  - source filename.
 *
 * Output parameters:
 *   NONE
 *
 */
static void
command_retrieve(FTPD_SessionInfo_t  *info, char const *filename)
{
  int                 s = -1;
  int                 fd = -1;
  char                buf[FTPD_DATASIZE];
  struct stat         stat_buf;
  int                 res = 0;

  if(!can_read())
  {
    send_reply(info, 550, "Access denied.");
    return;
  }

  if (0 > (fd = open(filename, O_RDONLY)))
  {
    send_reply(info, 550, "Error opening file.");
    return;
  }

  if (fstat(fd, &stat_buf) == 0 && S_ISDIR(stat_buf.st_mode))
  {
    if (-1 != fd)
      close(fd);
    send_reply(info, 550, "Is a directory.");
    return;
  }

  send_mode_reply(info);

  s = data_socket(info);

  if (0 <= s)
  {
    int n = -1;

    if(info->xfer_mode == TYPE_I)
    {
      while ((n = read(fd, buf, FTPD_DATASIZE)) > 0)
      {
        if(send(s, buf, n, 0) != n)
          break;
      }
    }
    else if (info->xfer_mode == TYPE_A)
    {
      int rest = 0;
      while (rest == 0 && (n = read(fd, buf, FTPD_DATASIZE)) > 0)
      {
        char const* e = buf;
        char const* b;
        int i;
        rest = n;
        do
        {
          char lf = '\0';

          b = e;
          for(i = 0; i < rest; ++i, ++e)
          {
            if(*e == '\n')
            {
              lf = '\n';
              break;
            }
          }
          if(send(s, b, i, 0) != i)
            break;
          if(lf == '\n')
          {
            if(send(s, "\r\n", 2, 0) != 2)
              break;
            ++e;
            ++i;
          }
        }
        while((rest -= i) > 0);
      }
    }

    if (0 == n)
    {
      if (0 == close(fd))
      {
        fd = -1;
        res = 1;
      }
    }
  }

  if (-1 != fd)
    close(fd);

  if (0 == res)
    send_reply(info, 451, "File read error.");
  else
    send_reply(info, 226, "Transfer complete.");

  close_data_socket(info);

  return;
}
Beispiel #8
0
static void fb_gpm_in(void *nic)
{
#ifndef USE_GPM_DX
	static int lx = -1, ly = -1;
#endif
	struct event ev;
	Gpm_Event gev;
	again:
	if (Gpm_GetEvent(&gev) <= 0) {
		unhandle_fb_mouse();
		return;
	}
	/*fprintf(stderr, "%x %x %d %d %d %d\n", gev.type, gev.buttons, gev.dx, gev.dy, gev.wdx, gev.wdy);*/
#ifndef USE_GPM_DX
	if (gev.x != lx || gev.y != ly) {
		mouse_x = (gev.x - 1) * fb_xsize / fb_txt_xsize + fb_xsize / fb_txt_xsize / 2 - 1;
		mouse_y = (gev.y - 1) * fb_ysize / fb_txt_ysize + fb_ysize / fb_txt_ysize / 2 - 1;
		lx = gev.x, ly = gev.y;
	}
#else
	if (gev.dx || gev.dy) {
		if (!((int)gev.type & gpm_smooth)) {
			mouse_x += gev.dx * 8;
			mouse_y += gev.dy * 8;
		}
#ifdef GPM_HAVE_SMOOTH
		else {
			mouse_x += gev.dx;
			mouse_y += gev.dy;
		}
#endif
	}
#endif
	ev.ev = EV_MOUSE;
	if (mouse_x >= fb_xsize) mouse_x = fb_xsize - 1;
	if (mouse_y >= fb_ysize) mouse_y = fb_ysize - 1;
	if (mouse_x < 0) mouse_x = 0;
	if (mouse_y < 0) mouse_y = 0;

	if (!((int)gev.type & gpm_smooth) && (gev.dx || gev.dy)) {
		mouse_x = (mouse_x + 8) / 8 * 8 - 4;
		mouse_y = (mouse_y + 8) / 8 * 8 - 4;
		if (mouse_x >= fb_xsize) mouse_x = fb_xsize - 1;
		if (mouse_y >= fb_ysize) mouse_y = fb_ysize - 1;
		if (mouse_x < 0) mouse_x = 0;
		if (mouse_y < 0) mouse_y = 0;
	}

	ev.x = mouse_x;
	ev.y = mouse_y;
	if (gev.buttons & GPM_B_LEFT) ev.b = B_LEFT;
	else if (gev.buttons & GPM_B_MIDDLE) ev.b = B_MIDDLE;
	else if (gev.buttons & GPM_B_RIGHT) ev.b = B_RIGHT;
	else ev.b = 0;
	if ((int)gev.type & GPM_DOWN) ev.b |= B_DOWN;
	else if ((int)gev.type & GPM_UP) ev.b |= B_UP;
	else if ((int)gev.type & GPM_DRAG) ev.b |= B_DRAG;
	else ev.b |= B_MOVE;

#ifdef HAVE_WDX_WDY
	if ((ev.b & BM_ACT) == B_DRAG || (ev.b & BM_ACT) == B_MOVE) {
		if (gev.wdy < 0) {
			ev.b &= ~BM_BUTT;
			ev.b |= B_WHEELDOWN;
		} else if (gev.wdy > 0) {
			ev.b &= ~BM_BUTT;
			ev.b |= B_WHEELUP;
		}
#if 0
	/* it doesn't work anyway - the exps2 protocol doesn't support it and evdev support in gpm is buggy */
		else if (gev.wdx < 0) {
			ev.b &= ~BM_BUTT;
			ev.b |= B_WHEELRIGHT;
		} else if (gev.wdx > 0) {
			ev.b &= ~BM_BUTT;
			ev.b |= B_WHEELLEFT;
#endif
	}
#endif

#ifndef USE_GPM_DX
	if (fb_msetsize < 0) {
	} else if (fb_msetsize < 10) {
		fb_msetsize++;
	} else if ((ev.b & BM_ACT) == B_MOVE && !(ev.b & BM_BUTT)) {
		fb_mouse_setsize();
		fb_msetsize = -1;
	}
#endif

	if (((ev.b & BM_ACT) == B_MOVE && !(ev.b & BM_BUTT)) || (ev.b & BM_ACT) == B_DRAG) {
		if (can_read(fb_hgpm)) goto again;
	}

	last_mouse_buttons = (int)ev.b;
	if (!current_virtual_device) return;
	if (current_virtual_device->mouse_handler) current_virtual_device->mouse_handler(current_virtual_device, ev.x, ev.y, (int)ev.b);
	redraw_mouse();
}

static int handle_fb_mouse(void)
{
	Gpm_Connect conn;
#ifndef USE_GPM_DX
	int gpm_ver = 0;
	struct winsize ws;
	fb_old_ws_v = 0;
#endif
	fb_hgpm = -1;
#ifndef USE_GPM_DX
	Gpm_GetLibVersion(&gpm_ver);
	fb_msetsize = -1;
	if (gpm_ver >= 11900) {
		int rs;
		EINTRLOOP(rs,ioctl(1, TIOCGWINSZ, &ws));
		if (rs != -1) {
			memcpy(&fb_old_ws, &ws, sizeof(struct winsize));
			fb_old_ws_v = 1;
			ws.ws_row *= 2;
			EINTRLOOP(rs, ioctl(1, TIOCSWINSZ, &ws));
			fb_msetsize = 0;
			memcpy(&fb_new_ws, &ws, sizeof ws);
		}
	}
	get_terminal_size(1, &fb_txt_xsize, &fb_txt_ysize);
#endif
	conn.eventMask = (unsigned short)~0U;
	conn.defaultMask = gpm_smooth;
	conn.minMod = 0;
	conn.maxMod = (unsigned short)~0U;
	if ((fb_hgpm = Gpm_Open(&conn, 0)) < 0) {
		unhandle_fb_mouse();
		return -1;
	}
	set_handlers(fb_hgpm, fb_gpm_in, (void (*)(void *))NULL, (void (*)(void *))NULL, NULL);
#ifdef SIGTSTP
	install_signal_handler(SIGTSTP, (void (*)(void *))sig_tstp, NULL, 0);
#endif
#ifdef SIGCONT
	install_signal_handler(SIGCONT, (void (*)(void *))sig_cont, NULL, 0);
#endif
#ifdef SIGTTIN
	install_signal_handler(SIGTTIN, (void (*)(void *))sig_tstp, NULL, 0);
#endif

	return 0;
}
Beispiel #9
0
void do_note( CHAR_DATA * ch, char *arg_passed, bool IS_MAIL )
{
  char buf[MAX_STRING_LENGTH];
  char arg[MAX_INPUT_LENGTH];
  NOTE_DATA *pnote = NULL;
  BOARD_DATA *board = NULL;
  int vnum = 0;
  int anum = 0;
  int first_list = 0;
  OBJ_DATA *paper = NULL, *tmpobj = NULL;
  EXTRA_DESCR_DATA *ed = NULL;
  char notebuf[MAX_STRING_LENGTH];
  char short_desc_buf[MAX_STRING_LENGTH];
  char long_desc_buf[MAX_STRING_LENGTH];
  char keyword_buf[MAX_STRING_LENGTH];
  bool mfound = FALSE;
  bool wasfound = FALSE;

  if( IS_NPC( ch ) )
    return;

  if( !ch->desc )
  {
    bug( "do_note: no descriptor", 0 );
    return;
  }

  switch ( ch->substate )
  {
    default:
      break;
    case SUB_WRITING_NOTE:
      if( ( paper = get_eq_char( ch, WEAR_HOLD ) ) == NULL
	  || paper->item_type != ITEM_PAPER )
      {
	bug( "do_note: player not holding paper", 0 );
	stop_editing( ch );
	return;
      }
      ed = ( EXTRA_DESCR_DATA * ) ch->dest_buf;
      STRFREE( ed->description );
      ed->description = copy_buffer( ch );
      stop_editing( ch );
      return;
  }

  set_char_color( AT_NOTE, ch );
  arg_passed = one_argument( arg_passed, arg );
  smash_tilde( arg_passed );

  if( !str_cmp( arg, "list" ) )
  {
    board = find_board( ch );
    if( !board )
    {
      send_to_char( "There is no board here to look at.\r\n", ch );
      return;
    }
    if( !can_read( ch, board ) )
    {
      send_to_char
	( "You cannot make any sense of the cryptic scrawl on this board...\r\n",
	  ch );
      return;
    }

    first_list = atoi( arg_passed );
    if( first_list )
    {
      if( IS_MAIL )
      {
	send_to_char
	  ( "You cannot use a list number (at this time) with mail.\r\n",
	    ch );
	return;
      }

      if( first_list < 1 )
      {
	send_to_char( "You can't read a message before 1!\r\n", ch );
	return;
      }
    }


    if( !IS_MAIL )
    {
      vnum = 0;
      set_pager_color( AT_NOTE, ch );
      for( pnote = board->first_note; pnote; pnote = pnote->next )
      {
	vnum++;
	if( ( first_list && vnum >= first_list ) || !first_list )
	  pager_printf( ch, "%2d%c %-12s%c %-12s %s\r\n",
	      vnum,
	      is_note_to( ch, pnote ) ? ')' : '}',
	      pnote->sender,
	      ( pnote->voting !=
		VOTE_NONE ) ? ( pnote->voting ==
		  VOTE_OPEN ? 'V' : 'C' ) : ':',
	      pnote->to_list, pnote->subject );
      }
      act( AT_ACTION, "$n glances over the messages.", ch, NULL, NULL,
	  TO_ROOM );
      return;
    }
    else
    {
      vnum = 0;


      if( IS_MAIL )		/* SB Mail check for Brit */
      {
	for( pnote = board->first_note; pnote; pnote = pnote->next )
	  if( is_note_to( ch, pnote ) )
	    mfound = TRUE;

	if( !mfound && !IS_IMMORTAL( ch ) )
	{
	  ch_printf( ch, "You have no mail.\r\n" );
	  return;
	}
      }

      for( pnote = board->first_note; pnote; pnote = pnote->next )
	if( is_note_to( ch, pnote ) || IS_IMMORTAL( ch ) )
	  ch_printf( ch, "%2d%c %s: %s\r\n",
	      ++vnum,
	      is_note_to( ch, pnote ) ? '-' : '}',
	      pnote->sender, pnote->subject );
      return;
    }
  }

  if( !str_cmp( arg, "read" ) )
  {
    bool fAll = FALSE;

    board = find_board( ch );
    if( !board )
    {
      send_to_char( "There is no board here to look at.\r\n", ch );
      return;
    }
    if( !can_read( ch, board ) )
    {
      send_to_char
	( "You cannot make any sense of the cryptic scrawl on this board...\r\n",
	  ch );
      return;
    }

    if( !str_cmp( arg_passed, "all" ) )
    {
      fAll = TRUE;
      anum = 0;
    }
    else if( is_number( arg_passed ) )
    {
      fAll = FALSE;
      anum = atoi( arg_passed );
    }
    else
    {
      send_to_char( "Note read which number?\r\n", ch );
      return;
    }

    set_pager_color( AT_NOTE, ch );
    if( !IS_MAIL )
    {
      vnum = 0;
      for( pnote = board->first_note; pnote; pnote = pnote->next )
      {
	vnum++;
	if( vnum == anum || fAll )
	{
	  wasfound = TRUE;
	  pager_printf( ch, "[%3d] %s: %s\r\n%s\r\nTo: %s\r\n%s",
	      vnum,
	      pnote->sender,
	      pnote->subject,
	      pnote->date, pnote->to_list, pnote->text );

	  if( pnote->yesvotes[0] != '\0' || pnote->novotes[0] != '\0'
	      || pnote->abstentions[0] != '\0' )
	  {
	    send_to_pager
	      ( "------------------------------------------------------------\r\n",
		ch );
	    pager_printf( ch,
		"Votes:\r\nYes:     %s\r\nNo:      %s\r\nAbstain: %s\r\n",
		pnote->yesvotes, pnote->novotes,
		pnote->abstentions );
	  }
	  act( AT_ACTION, "$n reads a message.", ch, NULL, NULL,
	      TO_ROOM );
	}
      }
      if( !wasfound )
	ch_printf( ch, "No such message: %d\r\n", anum );
      return;
    }
    else
    {
      vnum = 0;
      for( pnote = board->first_note; pnote; pnote = pnote->next )
      {
	if( is_note_to( ch, pnote ) || IS_IMMORTAL( ch ) )
	{
	  vnum++;
	  if( vnum == anum || fAll )
	  {
	    wasfound = TRUE;
	    pager_printf( ch, "[%3d] %s: %s\r\n%s\r\nTo: %s\r\n%s",
		vnum,
		pnote->sender,
		pnote->subject,
		pnote->date,
		pnote->to_list, pnote->text );
	  }
	}
      }
      if( !wasfound )
	ch_printf( ch, "No such message: %d\r\n", anum );
      return;
    }
  }

  /* Voting added by Narn, June '96 */
  if( !str_cmp( arg, "vote" ) )
  {
    char arg2[MAX_INPUT_LENGTH];
    arg_passed = one_argument( arg_passed, arg2 );

    board = find_board( ch );
    if( !board )
    {
      send_to_char( "There is no bulletin board here.\r\n", ch );
      return;
    }
    if( !can_read( ch, board ) )
    {
      send_to_char( "You cannot vote on this board.\r\n", ch );
      return;
    }

    if( is_number( arg2 ) )
      anum = atoi( arg2 );
    else
    {
      send_to_char( "Note vote which number?\r\n", ch );
      return;
    }

    vnum = 1;
    for( pnote = board->first_note; pnote && vnum < anum;
	pnote = pnote->next )
      vnum++;
    if( !pnote )
    {
      send_to_char( "No such note.\r\n", ch );
      return;
    }

    /* Options: open close yes no abstain */
    /* If you're the author of the note and can read the board you can open 
       and close voting, if you can read it and voting is open you can vote.
       */
    if( !str_cmp( arg_passed, "open" ) )
    {
      if( str_cmp( ch->name, pnote->sender ) )
      {
	send_to_char( "You are not the author of this message.\r\n",
	    ch );
	return;
      }
      pnote->voting = VOTE_OPEN;
      act( AT_ACTION, "$n opens voting on a note.", ch, NULL, NULL,
	  TO_ROOM );
      send_to_char( "Voting opened.\r\n", ch );
      write_board( board );
      return;
    }
    if( !str_cmp( arg_passed, "close" ) )
    {
      if( str_cmp( ch->name, pnote->sender ) )
      {
	send_to_char( "You are not the author of this message.\r\n",
	    ch );
	return;
      }
      pnote->voting = VOTE_CLOSED;
      act( AT_ACTION, "$n closes voting on a note.", ch, NULL, NULL,
	  TO_ROOM );
      send_to_char( "Voting closed.\r\n", ch );
      write_board( board );
      return;
    }

    /* Make sure the note is open for voting before going on. */
    if( pnote->voting != VOTE_OPEN )
    {
      send_to_char( "Voting is not open on this note.\r\n", ch );
      return;
    }

    /* Can only vote once on a note. */
    sprintf( buf, "%s %s %s",
	pnote->yesvotes, pnote->novotes, pnote->abstentions );
    if( is_name( ch->name, buf ) )
    {
      send_to_char( "You have already voted on this note.\r\n", ch );
      return;
    }
    if( !str_cmp( arg_passed, "yes" ) )
    {
      sprintf( buf, "%s %s", pnote->yesvotes, ch->name );
      DISPOSE( pnote->yesvotes );
      pnote->yesvotes = str_dup( buf );
      act( AT_ACTION, "$n votes on a note.", ch, NULL, NULL, TO_ROOM );
      send_to_char( "Ok.\r\n", ch );
      write_board( board );
      return;
    }
    if( !str_cmp( arg_passed, "no" ) )
    {
      sprintf( buf, "%s %s", pnote->novotes, ch->name );
      DISPOSE( pnote->novotes );
      pnote->novotes = str_dup( buf );
      act( AT_ACTION, "$n votes on a note.", ch, NULL, NULL, TO_ROOM );
      send_to_char( "Ok.\r\n", ch );
      write_board( board );
      return;
    }
    if( !str_cmp( arg_passed, "abstain" ) )
    {
      sprintf( buf, "%s %s", pnote->abstentions, ch->name );
      DISPOSE( pnote->abstentions );
      pnote->abstentions = str_dup( buf );
      act( AT_ACTION, "$n votes on a note.", ch, NULL, NULL, TO_ROOM );
      send_to_char( "Ok.\r\n", ch );
      write_board( board );
      return;
    }
    do_note( ch, STRLIT_EMPTY, FALSE );
  }
  if( !str_cmp( arg, "write" ) )
  {
    if( ch->substate == SUB_RESTRICTED )
    {
      send_to_char
	( "You cannot write a note from within another command.\r\n",
	  ch );
      return;
    }
    if( ( paper = get_eq_char( ch, WEAR_HOLD ) ) == NULL
	|| paper->item_type != ITEM_PAPER )
    {
      paper = create_object( get_obj_index( OBJ_VNUM_NOTE ) );
      if( ( tmpobj = get_eq_char( ch, WEAR_HOLD ) ) != NULL )
	unequip_char( ch, tmpobj );
      paper = obj_to_char( paper, ch );
      equip_char( ch, paper, WEAR_HOLD );
      act( AT_MAGIC, "$n grabs a message disk to record a note.",
	  ch, NULL, NULL, TO_ROOM );
      act( AT_MAGIC, "You get a message disk to record your note.",
	  ch, NULL, NULL, TO_CHAR );
    }
    if( paper->value[0] < 2 )
    {
      paper->value[0] = 1;
      ed = SetOExtra( paper, "_text_" );
      ch->substate = SUB_WRITING_NOTE;
      ch->dest_buf = ed;
      start_editing( ch, ed->description );
      return;
    }
    else
    {
      send_to_char( "You cannot modify this message.\r\n", ch );
      return;
    }
  }

  if( !str_cmp( arg, "subject" ) )
  {
    if( !arg_passed || arg_passed[0] == '\0' )
    {
      send_to_char( "What do you wish the subject to be?\r\n", ch );
      return;
    }
    if( ( paper = get_eq_char( ch, WEAR_HOLD ) ) == NULL
	|| paper->item_type != ITEM_PAPER )
    {
      paper = create_object( get_obj_index( OBJ_VNUM_NOTE ) );
      if( ( tmpobj = get_eq_char( ch, WEAR_HOLD ) ) != NULL )
	unequip_char( ch, tmpobj );
      paper = obj_to_char( paper, ch );
      equip_char( ch, paper, WEAR_HOLD );
      act( AT_MAGIC, "$n grabs a message disk.",
	  ch, NULL, NULL, TO_ROOM );
      act( AT_MAGIC, "You get a message disk to record your note.",
	  ch, NULL, NULL, TO_CHAR );
    }
    if( paper->value[1] > 1 )
    {
      send_to_char( "You cannot modify this message.\r\n", ch );
      return;
    }
    else
    {
      paper->value[1] = 1;
      ed = SetOExtra( paper, "_subject_" );
      STRFREE( ed->description );
      ed->description = STRALLOC( arg_passed );
      send_to_char( "Ok.\r\n", ch );
      return;
    }
  }

  if( !str_cmp( arg, "to" ) )
  {
    struct stat fst;
    char fname[1024];
    if( !arg_passed || arg_passed[0] == '\0' )
    {
      send_to_char( "Please specify an addressee.\r\n", ch );
      return;
    }
    if( ( paper = get_eq_char( ch, WEAR_HOLD ) ) == NULL
	|| paper->item_type != ITEM_PAPER )
    {
      paper = create_object( get_obj_index( OBJ_VNUM_NOTE ) );
      if( ( tmpobj = get_eq_char( ch, WEAR_HOLD ) ) != NULL )
	unequip_char( ch, tmpobj );
      paper = obj_to_char( paper, ch );
      equip_char( ch, paper, WEAR_HOLD );
      act( AT_MAGIC, "$n gets a message disk to record a note.",
	  ch, NULL, NULL, TO_ROOM );
      act( AT_MAGIC, "You grab a message disk to record your note.",
	  ch, NULL, NULL, TO_CHAR );
    }

    if( paper->value[2] > 1 )
    {
      send_to_char( "You cannot modify this message.\r\n", ch );
      return;
    }

    arg_passed[0] = UPPER( arg_passed[0] );

    sprintf( fname, "%s%c/%s", PLAYER_DIR, tolower( ( int ) arg_passed[0] ),
	capitalize( arg_passed ) );

    if( !IS_MAIL || stat( fname, &fst ) != -1
	|| !str_cmp( arg_passed, "all" ) )
    {
      paper->value[2] = 1;
      ed = SetOExtra( paper, "_to_" );
      STRFREE( ed->description );
      ed->description = STRALLOC( arg_passed );
      send_to_char( "Ok.\r\n", ch );
      return;
    }
    else
    {
      send_to_char( "No player exists by that name.\r\n", ch );
      return;
    }

  }

  if( !str_cmp( arg, "show" ) )
  {
    const char *subject = "";
    const char *to_list = "";
    const char *text = "";

    if( ( paper = get_eq_char( ch, WEAR_HOLD ) ) == NULL
	|| paper->item_type != ITEM_PAPER )
    {
      send_to_char( "You are not holding a message disk.\r\n", ch );
      return;
    }

    if( ( subject =
	  get_extra_descr( "_subject_", paper->first_extradesc ) ) == NULL )
      subject = "(no subject)";
    if( ( to_list =
	  get_extra_descr( "_to_", paper->first_extradesc ) ) == NULL )
      to_list = "(nobody)";
    sprintf( buf, "%s: %s\r\nTo: %s\r\n", ch->name, subject, to_list );
    send_to_char( buf, ch );
    if( ( text =
	  get_extra_descr( "_text_", paper->first_extradesc ) ) == NULL )
      text = "The disk is blank.\r\n";
    send_to_char( text, ch );
    return;
  }

  if( !str_cmp( arg, "post" ) )
  {
    char *strtime = NULL;
    const char *text = NULL;

    if( ( paper = get_eq_char( ch, WEAR_HOLD ) ) == NULL
	|| paper->item_type != ITEM_PAPER )
    {
      send_to_char( "You are not holding a message disk.\r\n", ch );
      return;
    }

    if( paper->value[0] == 0 )
    {
      send_to_char( "There is nothing written on this disk.\r\n", ch );
      return;
    }

    if( paper->value[1] == 0 )
    {
      send_to_char( "This message has no subject... using 'none'.\r\n",
	  ch );
      paper->value[1] = 1;
      ed = SetOExtra( paper, "_subject_" );
      STRFREE( ed->description );
      ed->description = STRALLOC( "none" );
    }

    if( paper->value[2] == 0 )
    {
      if( IS_MAIL )
      {
	send_to_char( "This message is addressed to no one!\r\n", ch );
	return;
      }
      else
      {
	send_to_char
	  ( "This message is addressed to no one... sending to 'all'!\r\n",
	    ch );
	paper->value[2] = 1;
	ed = SetOExtra( paper, "_to_" );
	STRFREE( ed->description );
	ed->description = STRALLOC( "All" );
      }
    }

    board = find_board( ch );
    if( !board )
    {
      send_to_char
	( "There is no terminal here to upload your message to.\r\n",
	  ch );
      return;
    }
    if( !can_post( ch, board ) )
    {
      send_to_char
	( "You cannot use this terminal. It is encrypted...\r\n", ch );
      return;
    }

    if( board->num_posts >= board->max_posts )
    {
      send_to_char
	( "This terminal is full. There is no room for your message.\r\n",
	  ch );
      return;
    }

    act( AT_ACTION, "$n uploads a message.", ch, NULL, NULL, TO_ROOM );

    strtime = ctime( &current_time );
    strtime[strlen( strtime ) - 1] = '\0';
    CREATE( pnote, NOTE_DATA, 1 );
    pnote->date = STRALLOC( strtime );

    text = get_extra_descr( "_text_", paper->first_extradesc );
    pnote->text = text ? STRALLOC( text ) : STRALLOC( "" );
    text = get_extra_descr( "_to_", paper->first_extradesc );
    pnote->to_list = text ? STRALLOC( text ) : STRALLOC( "all" );
    text = get_extra_descr( "_subject_", paper->first_extradesc );
    pnote->subject = text ? STRALLOC( text ) : STRALLOC( "" );
    pnote->sender = QUICKLINK( ch->name );
    pnote->voting = 0;
    pnote->yesvotes = str_dup( "" );
    pnote->novotes = str_dup( "" );
    pnote->abstentions = str_dup( "" );

    LINK( pnote, board->first_note, board->last_note, next, prev );
    board->num_posts++;
    write_board( board );
    send_to_char( "You upload your message to the terminal.\r\n", ch );
    extract_obj( paper );
    return;
  }

  if( !str_cmp( arg, "remove" )
      || !str_cmp( arg, "take" ) || !str_cmp( arg, "copy" ) )
  {
    char take = 0;

    board = find_board( ch );
    if( !board )
    {
      send_to_char
	( "There is no terminal here to download a note from!\r\n", ch );
      return;
    }
    if( !str_cmp( arg, "take" ) )
      take = 1;
    else if( !str_cmp( arg, "copy" ) )
    {
      if( !IS_IMMORTAL( ch ) )
      {
	send_to_char( "Huh?  Type 'help note' for usage.\r\n", ch );
	return;
      }
      take = 2;
    }
    else
      take = 0;

    if( !is_number( arg_passed ) )
    {
      send_to_char( "Note remove which number?\r\n", ch );
      return;
    }

    if( !can_read( ch, board ) )
    {
      send_to_char
	( "You can't make any sense of what's posted here, let alone remove anything!\r\n",
	  ch );
      return;
    }

    anum = atoi( arg_passed );
    vnum = 0;
    for( pnote = board->first_note; pnote; pnote = pnote->next )
    {
      if( IS_MAIL && ( ( is_note_to( ch, pnote ) )
	    || IS_IMMORTAL( ch ) ) )
	vnum++;
      else if( !IS_MAIL )
	vnum++;
      if( ( !str_cmp( ch->name, pnote->sender )
	    || can_remove( ch, board ) ) && ( vnum == anum ) )
      {
	if( ( is_name( "all", pnote->to_list ) )
	    && ( !IS_IMMORTAL( ch ) ) && ( take == 1 ) )
	{
	  send_to_char
	    ( "Notes addressed to 'all' can not be taken.\r\n", ch );
	  return;
	}

	if( take != 0 )
	{
	  paper = create_object( get_obj_index( OBJ_VNUM_NOTE ) );
	  ed = SetOExtra( paper, "_sender_" );
	  STRFREE( ed->description );
	  ed->description = QUICKLINK( pnote->sender );
	  ed = SetOExtra( paper, "_text_" );
	  STRFREE( ed->description );
	  ed->description = QUICKLINK( pnote->text );
	  ed = SetOExtra( paper, "_to_" );
	  STRFREE( ed->description );
	  ed->description = QUICKLINK( pnote->to_list );
	  ed = SetOExtra( paper, "_subject_" );
	  STRFREE( ed->description );
	  ed->description = QUICKLINK( pnote->subject );
	  ed = SetOExtra( paper, "_date_" );
	  STRFREE( ed->description );
	  ed->description = QUICKLINK( pnote->date );
	  ed = SetOExtra( paper, "note" );
	  STRFREE( ed->description );
	  sprintf( notebuf, "From: " );
	  strcat( notebuf, pnote->sender );
	  strcat( notebuf, "\r\nTo: " );
	  strcat( notebuf, pnote->to_list );
	  strcat( notebuf, "\r\nSubject: " );
	  strcat( notebuf, pnote->subject );
	  strcat( notebuf, "\r\n\r\n" );
	  strcat( notebuf, pnote->text );
	  strcat( notebuf, "\r\n" );
	  ed->description = STRALLOC( notebuf );
	  paper->value[0] = 2;
	  paper->value[1] = 2;
	  paper->value[2] = 2;
	  sprintf( short_desc_buf, "a note from %s to %s",
	      pnote->sender, pnote->to_list );
	  STRFREE( paper->short_descr );
	  paper->short_descr = STRALLOC( short_desc_buf );
	  sprintf( long_desc_buf,
	      "A note from %s to %s lies on the ground.",
	      pnote->sender, pnote->to_list );
	  STRFREE( paper->description );
	  paper->description = STRALLOC( long_desc_buf );
	  sprintf( keyword_buf, "note parchment paper %s",
	      pnote->to_list );
	  STRFREE( paper->name );
	  paper->name = STRALLOC( keyword_buf );
	}
	if( take != 2 )
	  note_remove( board, pnote );
	send_to_char( "Ok.\r\n", ch );
	if( take == 1 )
	{
	  act( AT_ACTION, "$n downloads a message.", ch, NULL, NULL,
	      TO_ROOM );
	  obj_to_char( paper, ch );
	}
	else if( take == 2 )
	{
	  act( AT_ACTION, "$n copies a message.", ch, NULL, NULL,
	      TO_ROOM );
	  obj_to_char( paper, ch );
	}
	else
	  act( AT_ACTION, "$n removes a message.", ch, NULL, NULL,
	      TO_ROOM );
	return;
      }
    }

    send_to_char( "No such message.\r\n", ch );
    return;
  }

  send_to_char( "Huh? Type 'help note' for usage.\r\n", ch );
}
int sys_read(int fd, userptr_t buf, int len, int* retval)
{
	// argument checks.

	if(fd <0 || fd>= OPEN_MAX)
		return EBADF;
	
	int result;
	char kern_buffer[len + 1];

	// are we using this properly?.. check jinghao's blog for example
	// no actual use for the kern buffer, just doing this to check if memory location is valid.

	if(buf!= NULL)
	{
		result = copyin(buf, kern_buffer, len); // using this because users are stupid/malicious and can pass invalid memory addresses to the kernel.
	
		if(result)
		{
			kprintf("read copy in bad \n");
			return result;

		}
	}

	struct file_handle* fh = get_file_handle(curproc->t_file_table, fd);
	
	if(fh == NULL)
		return EBADF;

	if(!can_read(fh->openflags)) // could have other flags Or'd with O_RDONLY, need to change this.
		return EBADF;
	

// !!!! Should we do copyin's to kernel space, or will the VOP_WRITE take care of the invalid address issue for us.

	lock_acquire(fh->fh_lock); // IS this really necessary??.. turns out it is , offset should be synchronized. imagine if parent and child call this at the same time.
	struct iovec iov;
	struct uio u;

	iov.iov_ubase = (userptr_t)buf;
	iov.iov_len = len;		 // length of the memory space
	u.uio_iov = &iov;
	u.uio_iovcnt = 1;
	u.uio_resid = len;          // amount to read from the file
	u.uio_offset = fh->offset;
	u.uio_segflg =  UIO_USERSPACE;
	u.uio_rw = UIO_READ;
	u.uio_space = proc_getas(); // lifted from loadelf.c, is this the right way to do it?

	result = VOP_READ(fh->file, &u);
	if (result) {
		lock_release(fh->fh_lock);
		return result;
	}

	if (u.uio_resid != 0) {
//		kprintf("ELF: short read on segment - file truncated?\n");
	}

	// should update offset in the file handle.use lock. uio_offset will be updated. can use it directly.
	fh->offset = u.uio_offset;

	lock_release(fh->fh_lock);

	*retval = len - u.uio_resid; // number of bytes gets returned to the user
	return 0; 


}
Beispiel #11
0
int CAN::read(CANMessage &msg, int handle) {
    return can_read(&_can, &msg, handle);
}
Beispiel #12
0
/**
 * @param const int seconds Timeout in seconds
 */
list<int> IOSelect::can_read(const int seconds) {
	struct timeval timeout = {seconds, 0};
	return can_read(&timeout);
}
int main(int argc, char **argv)
{
	int size;
	int fd;
	unsigned long id;  
	unsigned char data[8];
        char *port = "/dev/can1";	/// use "1" to "4" for steinhoff
        int opt;
	int status;
	int read_err = 0;
	int msg_count = 0;
	timestamp_t start_ts, end_ts, diff_ts; /// report start and end times
	can_err_count_t errs;

        while ((opt = getopt(argc, argv, "p:")) != -1) {
                switch (opt) {
                  case 'p':
                        port = strdup(optarg);
                        break;
                  default:
                        printf("Usage: %s -p <port>\n", argv[0]);
                        exit(1);
                }
        }

	fd = can_open(port, O_RDONLY);

	if (fd == -1)
		exit(EXIT_FAILURE);	// error message printed by can_open 

	// Save starting time
	get_current_timestamp(&start_ts);

        if(setjmp(exit_env) != 0) {
		unsigned int i;
		get_current_timestamp(&end_ts);
		print_timestamp(stdout, &start_ts);
		printf(" ");
		print_timestamp(stdout, &end_ts);
		printf(" ");
		decrement_timestamp(&end_ts, &start_ts, &diff_ts);
		print_timestamp(stdout, &diff_ts); 	
		printf("\n");

		errs = can_get_errs(fd);

		if (read_err > 0)
			printf(" %d client read errors\n", read_err);

		printf("Error counts  at finish:\n");
		printf("intr_in_handler_count %u\n", errs.intr_in_handler_count);
		printf("rx_interrupt_count %u\n", errs.rx_interrupt_count);
		printf("rx_message_lost_count %u\n", errs.rx_message_lost_count);
		printf("tx_interrupt_count %u\n", errs.tx_interrupt_count);
		printf("shadow_buffer_count %u\n", errs.shadow_buffer_count);

		if (fd != -1)
			status = can_close(&fd);

		for (i = 0; i < msg_count; i++) { 
			save_data_t *p = &saved_data[i];
			printf("%u ", i);
			printf("%hhu ", p->can_id); 
			printf("%hd ", p->longitudinal);
			printf("%hd ", p->vertical);
			printf("%hd ", p->lateral);
			printf("%hhu ", p->thread_counter); 
			printf("%hhu ",	p->sensor_group_counter); 
			printf("\n");
		}

		if (status != -1)			
			exit(EXIT_SUCCESS);
		else
			exit(EXIT_FAILURE);	// can_close prints error info
        } else
		sig_ign(sig_list, sig_hand);

	/// Clear error counts in driver
	errs =  can_clear_errs(fd);

	printf("Error counts at start:\n");
	printf("intr_in_handler_count %u\n", errs.intr_in_handler_count);
	printf("rx_interrupt_count %u\n", errs.rx_interrupt_count);
	printf("rx_message_lost_count %u\n", errs.rx_message_lost_count);
	printf("tx_interrupt_count %u\n", errs.tx_interrupt_count);
	printf("shadow_buffer_count %u\n", errs.shadow_buffer_count);

	for(;;) {
		id = 0;		
		size = can_read(fd,&id,(char *)NULL,data,8);

		if (size < 0) 
			read_err++;	
		else {
			saved_data[msg_count].can_id = id;
			saved_data[msg_count].longitudinal = 
				(*(short *) &data[2]);
			saved_data[msg_count].vertical = 
				(*(short *) &data[0]);
			saved_data[msg_count].lateral = 
				(*(short *) &data[6]);
			saved_data[msg_count].sensor_group_counter = 
				 data[4];
			saved_data[msg_count].thread_counter = 
				 data[5];
		}
		msg_count++;
		if (msg_count >= max_count)
			longjmp(exit_env, 1);
	}
}