예제 #1
0
void device_image_interface::determine_open_plan(int is_create, UINT32 *open_plan)
{
    int i = 0;

    /* emit flags */
    if (!is_create && is_readable() && is_writeable())
        open_plan[i++] = OPEN_FLAG_READ | OPEN_FLAG_WRITE;
    if (!is_create && !is_readable() && is_writeable())
        open_plan[i++] = OPEN_FLAG_WRITE;
    if (!is_create && is_readable())
        open_plan[i++] = OPEN_FLAG_READ;
    if (is_writeable() && is_creatable())
        open_plan[i++] = OPEN_FLAG_READ | OPEN_FLAG_WRITE | OPEN_FLAG_CREATE;
    open_plan[i] = 0;
}
예제 #2
0
파일: diimage.cpp 프로젝트: RalfVB/mame
std::vector<UINT32> device_image_interface::determine_open_plan(bool is_create)
{
	std::vector<UINT32> open_plan;

	// emit flags into a vector
	if (!is_create && is_readable() && is_writeable())
		open_plan.push_back(OPEN_FLAG_READ | OPEN_FLAG_WRITE);
	if (!is_create && !is_readable() && is_writeable())
		open_plan.push_back(OPEN_FLAG_WRITE);
	if (!is_create && is_readable())
		open_plan.push_back(OPEN_FLAG_READ);
	if (is_create && is_writeable() && is_creatable())
		open_plan.push_back(OPEN_FLAG_READ | OPEN_FLAG_WRITE | OPEN_FLAG_CREATE);

	return open_plan;
}
예제 #3
0
cell *
prepare_dictionary(int *argcp, char *(*argvp[]))
{
    u_char *origin;
    u_char *here;
    u_char *xlimit;
    int dict_size;
    u_char *extension;

    char *dictionary_file = "";

    // Allocate space for the Forth dictionary and read its initial contents
    origin = aln_alloc(MAXDICT, variables);

    xlimit = &origin[MAXDICT];
    if(*argcp < 2
       || (extension = strrchr((*argvp)[1],'.')) == NULL
       || strcmp(extension, ".dic") != 0 ) {
	dictionary_file = is_readable("app.dic") ? "app.dic" : DEFAULT_EXE;
    } else {
        dictionary_file = (*argvp)[1];
        *argcp -= 1;
        *argvp += 1;
    }

    dict_size = read_dictionary(dictionary_file, origin, variables);
    here = &origin[dict_size];

    init_compiler(origin, xlimit, 0xfffe, here, xlimit, variables);
    return variables;
}
예제 #4
0
			virtual hexabus::Packet::Ptr handle_query() const {
				if ( !is_readable() )
					return Packet::Ptr(new ErrorPacket(HXB_ERR_UNKNOWNEID));

				boost::optional<TValue> value = _read();
				if ( !value ) {
					std::stringstream oss;
					oss << "Error reading endpoint " << name() << " (" << eid() << ")";
					throw hexabus::GenericException(oss.str());
				}
				return Packet::Ptr(new InfoPacket<TValue>(eid(), *value));
			}
예제 #5
0
파일: create.cpp 프로젝트: amireh/Karazeh
  STAGE_RC create_operation::stage() {
    auto file_manager = config_.file_manager;

    const path_t destination(get_destination());
    const path_t destination_dir(destination.parent_path());

    if (config_.verbose) {
      indent();

      debug() << "Caching path: "<< cache_path_;
      debug() << "Destination path: " << destination;

      deindent();
    }

    // Prepare our staging directory
    if (!file_manager->ensure_directory(cache_dir_)) {
      error() << "Unable to create caching directory: " << cache_dir_;
      return STAGE_UNAUTHORIZED;
    }

    // Prepare our destination directory, if necessary
    if (!file_manager->ensure_directory(destination_dir)) {
      error() << "Unable to create destination dir: " << destination_dir;
      return STAGE_UNAUTHORIZED;
    }

    // Make sure the destination is free
    if (file_manager->is_readable(destination) && !marked_for_deletion_) {
      error() << "Destination is occupied!";

      return STAGE_FILE_EXISTS;
    }

    // Can we write to the destination?
    if (!file_manager->is_writable(destination)) {
      error() << "Destination isn't writable!";
      return STAGE_UNAUTHORIZED;
    }

    // Can we write to the staging destination?
    if (!file_manager->is_writable(cache_path_)) {
      error() << "The cache isn't writable: " << cache_path_;
      return STAGE_UNAUTHORIZED;
    }

    if (!config_.downloader->fetch(src_uri, cache_path_, src_checksum)) {
      throw invalid_resource(src_uri);
    }

    return STAGE_OK;
  }
예제 #6
0
파일: update.cpp 프로젝트: amireh/Karazeh
  STAGE_RC update_operation::deploy() {
    auto file_manager = config_.file_manager;

    debug() << "patching file " << basis_path_ << " using delta " << delta_path_ << " out to " << patched_path_;

    if (
      !file_manager->is_readable(basis_path_) ||
      !file_manager->is_readable(delta_path_)
    ) {
      return STAGE_INVALID_STATE;
    }

    rs_result rc = encoder_.patch(basis_path_.c_str(), delta_path_.c_str(), patched_path_.c_str());

    if (rc != RS_DONE) {
      error()
        << "Patching file " << basis_path_ << " using patch " << delta_path_
        <<" has failed. librsync rc: " << rc;

      return STAGE_ENCODING_ERROR;
    }

    hasher::digest_rc digest = config_.hasher->hex_digest(patched_path_);

    if (digest != patched_checksum) {
      error()
        << "Checksum mismatch: "
        << digest.digest << " vs " << patched_checksum
        << " in file " << patched_path_;

      return STAGE_FILE_INTEGRITY_MISMATCH;
    }

    const path_t temp_path(path_t(patched_path_.string() + ".tmp").make_preferred());

    // move the patched file to a temporary location until we can move it over
    // to the destination:
    file_manager->move(patched_path_, temp_path);

    // free the destination; move the old file to where the patched file was so
    // that we can roll back if necessary:
    file_manager->move(basis_path_, patched_path_); // !! repository side effect !!

    // finally, move over the patched file to where the old file was:
    file_manager->move(temp_path, basis_path_); // !! repository side effect !!

    patched_ = true;

    return STAGE_OK;
  }
예제 #7
0
파일: UIFile.hpp 프로젝트: EQ4/lad
    static Glib::RefPtr<Gtk::Builder> open(const std::string& base_name) {
        std::string ui_filename;
#ifdef PATCHAGE_BINLOC
        const std::string bundle = bundle_location();
        if (!bundle.empty()) {
            ui_filename = bundle + "/" + base_name + ".ui";
            if (is_readable(ui_filename)) {
                std::cout << "Loading UI file " << ui_filename << std::endl;
                return Gtk::Builder::create_from_file(ui_filename);
            }
        }
#endif
        ui_filename = std::string(PATCHAGE_DATA_DIR) + "/" + base_name + ".ui";
        if (is_readable(ui_filename)) {
            std::cout << "Loading UI file " << ui_filename << std::endl;
            return Gtk::Builder::create_from_file(ui_filename);
        }

        std::stringstream ss;
        ss << "Unable to find " << base_name << std::endl;
        throw std::runtime_error(ss.str());
        return Glib::RefPtr<Gtk::Builder>();
    }
예제 #8
0
파일: update.cpp 프로젝트: amireh/Karazeh
  STAGE_RC update_operation::stage() {
    auto file_manager = config_.file_manager;

    // basis must exist
    if (!file_manager->is_readable(basis_path_)) {
      error() << "basis file does not exist at: " << basis_path_;

      return STAGE_FILE_MISSING;
    }

    // basis checksum check
    hasher::digest_rc digest = config_.hasher->hex_digest(basis_path_);

    if (digest != basis_checksum) {
      error()
        << "Basis file checksum mismatch: "
        << digest.digest << " vs " << basis_checksum
        << " in file " << basis_path_;

      return STAGE_FILE_INTEGRITY_MISMATCH;
    }

    // prepare our cache directory, if necessary
    if (!file_manager->is_directory(cache_dir_)) {
      if (!file_manager->create_directory(cache_dir_)) {
        error() << "Unable to create cache directory: " << cache_dir_;
        return STAGE_UNAUTHORIZED;
      }
    }

    // TODO: free space checks, need at least 2x basis file size + delta size

    // get the delta patch
    if (!config_.downloader->fetch(delta_url_, delta_path_, delta_checksum)) {
      throw invalid_resource(delta_url_);
    }

    // create the signature
    debug() << "generating signature for " << basis_path_ << " out to " << signature_path_;

    rs_result rc = encoder_.signature(basis_path_, signature_path_);

    if (rc != RS_DONE) {
      error() << "Generating of signature for file " << basis_path_ << " has failed. librsync rc: " << rc;
      return STAGE_ENCODING_ERROR;
    }

    return STAGE_OK;
  }
예제 #9
0
/*
 * filter the permissions we have on the entry into buckets
 */
void
record_access_level(const char *path, struct stat *sb)
{
    if (is_setuid(sb))
        record_access(&g_suid, path, sb);
    else if (is_setgid(sb))
        record_access(&g_sgid, path, sb);
    else if (is_writable(sb))
        record_access(&g_writable, path, sb);
#ifdef RECORD_LESS_INTERESTING
    else if (is_readable(sb))
        record_access(&g_readable, path, sb);
    else if (is_executable(sb))
        record_access(&g_executable, path, sb);
#endif
}
예제 #10
0
파일: update.cpp 프로젝트: amireh/Karazeh
  void update_operation::rollback() {
    auto file_manager = config_.file_manager;
    auto hasher       = config_.hasher;

    // did we patch the file? keep in mind that if we did:
    //
    // - patched_path_ would point to the **original** file
    // - basis_path_ would point to the **patched** file
    //
    // to avoid confusion, we'll gonna rename the references to "original" and
    // "patched":
    const path_t    &original_path(patched_path_);
    const string_t  &original_checksum(basis_checksum);
    const path_t    &modified_path(basis_path_);
    const string_t  &modified_checksum(patched_checksum);

    if (!file_manager->is_readable(modified_path)) {
      return (void)STAGE_INVALID_STATE;
    }

    auto checksum = hasher->hex_digest(modified_path);

    if (checksum == modified_checksum) {
      // make sure the original still exists
      if (!file_manager->exists(original_path)) {
        error() << "Basis no longer exists in cache, can not rollback!";

        return (void)STAGE_INVALID_STATE;
      }
      else if (hasher->hex_digest(original_path) != original_checksum) {
        error() << "Basis file seems to have changed, can not rollback!";

        return (void)STAGE_INVALID_STATE;
      }

      // remove the modified file:
      file_manager->remove_file(modified_path);

      // and move the original file back in its place:
      file_manager->move(original_path, modified_path);
    }
  }
예제 #11
0
파일: CtFile.cpp 프로젝트: applemind/JC
/**
 * read  -  读取文件数据
 * Param : data 保存读取的数据
 *         len 要读取的数据长度
 * Return: 默认返回已读取到的数据长度,返回-1为读取失败
 */
int CtFile::read(void *data, const size_t len)
{
	if( ! ( is_open() && is_readable() ) )
		return -1;
	if( data == nullptr )
		return -1;
	
	int ret;
#ifdef WIN32
	{	/*** microsoft ***/
		if( ! ReadFile(m_file_handle, data, len, (LPDWORD)&ret, nullptr) )
			ret = -1;
	}
#else
	{	/*** unix ***/
		ret = read(m_file_handle, data, len);
	}
#endif
	return ret;
}
예제 #12
0
// Listens for an ack, returning the ack number. Returns -99 if timeout
int listen_for_ack(int sockfd) {
  int recvlen;
  int ack_number = -99;
  struct packet receive;

  if (is_readable(sockfd)) {
    recvlen = recvfrom(sockfd, &receive, sizeof(receive), 0, NULL, NULL);
    if (should_lose_packet()) {
      if (receive.type == TYPE_ACK)
        printf("Simulated loss of ack # %d\n", receive.seq);
      else
        printf("Simulated loss of packet type %d. (Was expecting ACK).\n", receive.type);
      return -99;
    }
    if (should_corrupt_packet()) {
      if (receive.type == TYPE_ACK)
        printf("Simulated corruption of ack # %d\n", receive.seq);
      else
        printf("Simulated corruption of packet type %d. (Was expecting ACK).\n", receive.type);
      return -99;
    }
    if (corrupt(&receive)) {
      printf("Received actual corrupt packet\n");
      return -99;
    }
  }
  else {
    return -99;
  }  

  if (recvlen < 0)
    error("ERROR receiving ack from client");
  if (receive.type != TYPE_ACK) {
    fprintf(stderr, "Expected ACK, received type %d", receive.type);
    return -99;
  }
  ack_number = receive.seq;

  printf("Received ack %d.\n", ack_number);
  return ack_number;
}
예제 #13
0
파일: create.cpp 프로젝트: amireh/Karazeh
  STAGE_RC create_operation::deploy() {
    auto file_manager = config_.file_manager;
    const path_t destination(get_destination());

    // Make sure the destination is free
    if (file_manager->is_readable(destination)) {
      error() << "Destination is occupied: " << destination;
      return STAGE_FILE_EXISTS;
    }

    // Can we write to the destination?
    if (!file_manager->is_writable(destination)) {
      error() << "Destination isn't writable: " << destination;
      return STAGE_UNAUTHORIZED;
    }

    // Can we write to the staging destination?
    if (!file_manager->is_writable(cache_path_)) {
      error() << "Temp isn't writable: " << cache_path_;
      return STAGE_UNAUTHORIZED;
    }

    // Move the staged file to the destination
    info() << "Creating " << destination;
    file_manager->move(cache_path_, destination);

    // validate integrity
    hasher::digest_rc rc = config_.hasher->hex_digest(destination);

    if (rc != src_checksum) {
      error() << "Created file integrity mismatch: " << rc.digest << " vs " << src_checksum;
      return STAGE_FILE_INTEGRITY_MISMATCH;
    }

    if (is_executable) {
      debug() << "MARKING EXECUTABLE!\n";
      file_manager->make_executable(destination);
    }

    return STAGE_OK;
  }
예제 #14
0
static gboolean is_accessible_directory(mode_t mode)
{
        if(!S_ISDIR(mode))
                return FALSE;
        return is_readable(mode) && is_executable(mode);
}
예제 #15
0
파일: main.cpp 프로젝트: GENIVI/navigation
int main(int  argc , char**  argv )
{
    GMainLoop * mainloop ;

    // Set the global C and C++ locale to the user-configured locale,
    // so we can use std::cout with UTF-8, via Glib::ustring, without exceptions.
    std::locale::global(std::locale(""));

    //index used for argument analysis
    int next_option;

    /* Valid letters for short options. */
    const char* const short_options = "hf:i:";
    /* Valid string for long options. */
    const struct option long_options[] = {
        { "help",     0, NULL, 'h' },
        { "file", 1, NULL, 'f' },
        { "internationalisation", 2, NULL, 'i' },
        { NULL,       0, NULL, 0   }   /* Always at the end of the table.  */
    };
    char* database_filename = NULL; //database filename
    QString language = "en"; //english by default

    program_name = argv[0];

    do {
        next_option = getopt_long (argc, argv, short_options,
                                  long_options, NULL);
        switch (next_option)
        {
        case 'h':   /* -h --help */
            print_usage (stdout, 0);
            break;
        case 'f':   /* -f --file database */
            database_filename = argv[2];
            if (!is_readable(database_filename))
                print_usage (stderr, 1);
            break;
        case 'i':   /* -i --internationalisation language */
            language = argv[4];
            break;
        case '?':   /* Invalid option. */
            print_usage (stderr, 1);
        case -1:    /* End of options.  */
            break;
        default:    /* Error  */
            print_usage (stderr, 1);
        }
    }
    while (next_option != -1);

    QApplication a(argc, argv);
    QTranslator translator;
    if (QResource::registerResource("poi-client-resource.rcc",QDir::currentPath()))
    {
        if (translator.load("poi-contentaccess-module_"+ language))
        {
            a.installTranslator(&translator);
            MainWindow mainWindow;

            // creating the dispatcher
            dispatcher = new DBus::Glib::BusDispatcher();
            DBus::default_dispatcher = dispatcher;
            dispatcher->attach(NULL);

            // create a connection on the session bus
            dbusConnection = new DBus::Connection(DBus::Connection::SessionBus());
            dbusConnection->setup(dispatcher);

            // create the server for contentAccessModule
            dbusConnection->request_name(contentAccessModule_SERVICE_NAME);
            servercontentAccessModule=new contentAccessModuleServer(*dbusConnection,database_filename);

            // connect it to the HMI panel
            mainWindow.ConnectTocontentAccessModuleServer(servercontentAccessModule);

            // connect the HMI panel to it
            servercontentAccessModule->connectToHMI(&mainWindow);

            // create a client for poiContentAccess
            clientpoiContentAccess = new poiContentAccess(*dbusConnection);

            // connect it to the HMI panel
            mainWindow.ConnectTopoiContentAccessClient(clientpoiContentAccess);

            // Create a new GMainLoop with default context and initial state of "not running "
            mainloop = g_main_loop_new (g_main_context_default() , FALSE );

           // loop listening
            mainWindow.InitUi();
            mainWindow.show();

            int ret = a.exec();

            // clean memory
            delete servercontentAccessModule;
            delete dbusConnection;
            delete dispatcher;
        }
        else
        {
            print_usage (stderr, 2);
        }
    }
    else
    {
        print_usage (stderr, 3);
    }
    return EXIT_SUCCESS;
}
예제 #16
0
파일: axel.c 프로젝트: 3rdexp/xsandbox
/* Main 'loop' */
void axel_do(axel_t *axel)
{
#if WIN32
	WSAEVENT hEventObject = WSACreateEvent();
	DWORD byte;
#else
	fd_set fds[1];
	struct timeval timeval[1];
	int hifd;
#endif
	int i;
	long long int remaining, size;

	/* Create statefile if necessary */
	if (axel->next_state < gettime())
	{
		save_state(axel);
		axel->next_state = gettime() + axel->conf->save_state_interval;
	}

	/* Wait for data on (one of) the connections */
#if !WIN32
	FD_ZERO(fds);
	hifd = 0;
	for (i = 0; i < axel->conf->num_connections; i++)
	{
		if (axel->conn[i].enabled) 
		{
			FD_SET(axel->conn[i].fd, fds);
		}
		hifd = max(hifd, axel->conn[i].fd);
	}

	if (0 == hifd)
	{
#ifdef DEBUG
		printf("DEBUG no connection yet. Wait...\n");
#endif
		/* No connections yet. Wait... */
		usleep(100000);
		goto conn_check;
	}
	else
	{
		timeval->tv_sec = 0;
		timeval->tv_usec = 100000;
		/* A select() error probably means it was interrupted
		   by a signal, or that something else's very wrong...	*/
		if (-1 == select(hifd + 1, fds, NULL, NULL, timeval))
		{
			axel->ready = -1;
			return;
		}
	}
#endif

	/* Handle connections which need attention */
	for (i = 0; i < axel->conf->num_connections; i++) 
	{
		if (axel->conn[i].enabled) 
		{
#if WIN32
			if (is_readable(axel, axel->conn[i].fd, hEventObject))
#else
			if (FD_ISSET(axel->conn[i].fd, fds))
#endif
			{
				axel->conn[i].last_transfer = gettime();
#if WIN32
				memset(buffer, 0, max(MAX_STRING, axel->conf->buffer_size));
				size = recv(axel->conn[i].fd, buffer, axel->conf->buffer_size, 0);
#else
				size = read(axel->conn[i].fd, buffer, axel->conf->buffer_size);
#endif
#if WIN32
				if (SOCKET_ERROR == size)
#else
				if (-1 == size)
#endif
				{
#if !WIN32
					if (axel->conf->verbose)
					{
						axel_message( axel, _("Error on connection %i! "
							"Connection closed"), i );
					}
#endif
					axel->conn[i].enabled = 0;
					conn_disconnect(&axel->conn[i]);
					continue;
				}
				else if (0 == size)
				{
					if (axel->conf->verbose)
					{
						/* Only abnormal behaviour if: */
						if (axel->conn[i].currentbyte < axel->conn[i].lastbyte && axel->size != INT_MAX)
						{
							axel_message(axel, _("Connection %i unexpectedly closed"), i);
						}
						else
						{
							axel_message(axel, _("Connection %i finished"), i);
						}
					}
					if (!axel->conn[0].supported)
					{
						axel->ready = 1;
					}
					axel->conn[i].enabled = 0;
					conn_disconnect(&axel->conn[i]);
					continue;
				}
				/* remaining == Bytes to go */
				remaining = axel->conn[i].lastbyte - axel->conn[i].currentbyte + 1;
				if (remaining < size)
				{
					if (axel->conf->verbose)
					{
						axel_message(axel, _("Connection %i finished"), i);
					}
					axel->conn[i].enabled = 0;
					conn_disconnect(&axel->conn[i]);
					size = remaining;
					/* Don't terminate, still stuff to write!	*/
				}
				/* This should always succeed..				*/
#if WIN32
				SetFilePointer(axel->outfd, axel->conn[i].currentbyte, NULL, FILE_BEGIN);
				if (0 == WriteFile(axel->outfd, buffer, size, &byte, NULL))
#else
				lseek(axel->outfd, axel->conn[i].currentbyte, SEEK_SET);
				if (write(axel->outfd, buffer, size) != size)
#endif
				{
					axel_message(axel, _("Write error!"));
					axel->ready = -1;
					return;
				}
				axel->conn[i].currentbyte += size;
				axel->bytes_done += size;
			}
			else
			{
				if (gettime() > axel->conn[i].last_transfer + axel->conf->connection_timeout)
				{
					if (axel->conf->verbose) 
					{
						axel_message(axel, _("Connection %i timed out"), i);
					}
					conn_disconnect(&axel->conn[i]);
					axel->conn[i].enabled = 0;
				}
			}
		}
	}
	if (axel->ready) 
	{
		return;
	}
	
conn_check:
	/* Look for aborted connections and attempt to restart them. */
	for (i = 0; i < axel->conf->num_connections; i++)
	{
		if (!axel->conn[i].enabled 
            && axel->conn[i].currentbyte < axel->conn[i].lastbyte)
		{
			if (0 == axel->conn[i].state)
			{	
				// Wait for termination of this thread
#if WIN32
				WaitForSingleObject(axel->conn[i].setup_thread, INFINITE);
				CloseHandle(axel->conn[i].setup_thread);
#else
				pthread_join(*(axel->conn[i].setup_thread), NULL);
#endif	
				conn_set(&axel->conn[i], axel->url->text);
				axel->url = axel->url->next;
				if (axel->conf->verbose >= 2) 
				{
					axel_message(axel, _("Connection %i downloading from %s:%i using interface %s"), 
						i, axel->conn[i].host, axel->conn[i].port, axel->conn[i].local_if);
				}
				
				axel->conn[i].state = 1;
#if WIN32
				axel->conn[i].setup_thread = CreateThread(NULL, 0, setup_thread_cb, &axel->conn[i], 0, NULL);
				if (NULL != axel->conn[i].setup_thread) 
#else
				if (pthread_create(axel->conn[i].setup_thread, NULL, setup_thread_cb, &axel->conn[i]) == 0)
#endif
				{
					axel->conn[i].last_transfer = gettime();
				}
				else
				{
					axel_message(axel, _("thread error in axel_do!!!"));
					axel->ready = -1;
				}
			}
			else
			{
				if (gettime() > axel->conn[i].last_transfer + axel->conf->reconnect_delay)
				{
#if WIN32
					TerminateThread(axel->conn[i].setup_thread, 0);
                    CloseHandle(axel->conn[i].setup_thread);
#else
					pthread_cancel(*axel->conn[i].setup_thread);
#endif
					axel->conn[i].state = 0;
				}
			}
		}
	}

	/* Calculate current average speed and finish_time		*/
	axel->bytes_per_second = (int)((double)(axel->bytes_done - axel->start_byte) / (gettime() - axel->start_time));
	axel->finish_time = (int)(axel->start_time + (double)(axel->size - axel->start_byte) / axel->bytes_per_second);

	/* Check speed. If too high, delay for some time to slow things
	   down a bit. I think a 5% deviation should be acceptable.	*/
	if (0 < axel->conf->max_speed)
	{
		if (1.05 < (float) axel->bytes_per_second / axel->conf->max_speed) 
		{
			axel->delay_time += 10000;
		}
		else if (((float)axel->bytes_per_second / axel->conf->max_speed < 0.95) 
            && 10000 <= (axel->delay_time)) 
		{
			axel->delay_time -= 10000;
		}
		else if (((float)axel->bytes_per_second / axel->conf->max_speed < 0.95)) 
		{
			axel->delay_time = 0;
		}
		usleep(axel->delay_time);
	}
	
	/* Ready? */
	if (axel->bytes_done == axel->size) 
	{
		axel->ready = 1;
	}
}
예제 #17
0
string amiq_rm_field::to_string() {
	ostringstream convert;
	convert << name << " Lsb Position: " << lsb_position << " Size: " << size << " W: " << is_writable() << " R: " << is_readable() << " Reset: "
			<< reset_value;
	return convert.str();
}
예제 #18
0
int net_socket_tcp::read_line(tu_string* str, int maxbytes, float timeout_seconds)
// Try to read a string, up to the next '\n' character.
// Returns the actual bytes read.
//
// If the last character in the string is not '\n', then
// either we read maxbytes, or we timed out or the socket
// closed or something.
{
	assert(str);

	uint64 start = tu_timer::get_ticks();
	int timeout = int(timeout_seconds * 1000);	// ticks, ms
	int total_bytes_read = 0;

	for (;;)       
	{
		// Read a byte at a time.  Probably slow!
		char c;
		bool waiting = false;
		int bytes_read = recv(m_sock, &c, 1, 0);
		if (bytes_read == SOCKET_ERROR)
		{
			m_error = WSAGetLastError();
			if (m_error == WSAEWOULDBLOCK)
			{
				// No data ready.
				m_error = 0;
				waiting = true;
			}
			else
			{
				// Presumably something bad.
				fprintf(stderr, "net_socket_tcp::read() error in recv, error code = %d\n",
					WSAGetLastError());
				return 0;
			}
		} 
		else
		if (bytes_read == 0)
		{
			if (is_readable() && recv(m_sock, &c, 1, 0) == 0)
			{
				// Socket must close
				return total_bytes_read ? total_bytes_read : -1;

			}
			waiting = true;
		}

		if (waiting) 
		{
			// Timeout?
			if (tu_timer::get_ticks() - start >= timeout)
			{
				// Timed out.
				return 0;
			}

			// sleep a bit
			if (timeout - (tu_timer::get_ticks() - start) >= 10)
			{
				tu_timer::sleep(10);
			}
			continue;
		}

		assert(bytes_read == 1);
		total_bytes_read++;

		if (c == '\n')
		{
			// Done.
//			printf("recv: '%s'\n", str->c_str());
			return total_bytes_read;
		}

		// '\n'(0x0D) and '\r'(0x0A) are not written into str
		if (c != '\r')
		{
			(*str) += c;
		}

		if (maxbytes > 0 && total_bytes_read >= maxbytes)
		{
			// Caller doesn't want any more bytes.
			return total_bytes_read;
		}

		// else keep reading.
	}

	return 0;
}
예제 #19
0
int main(int argc, char *argv[])
{
    int sockfd; // socket descriptor
    struct hostent *server; // contains tons of information, including the server's IP address
    int portno;
    char * filename;
    FILE * f;
    double lossprob;
    double corruptprob;
    int result;
    socklen_t servlen;
    struct sockaddr_in serv_addr;
    struct packet request;
    struct packet receive;
    int expected_seq = 0;

    // initialize random number generator
    srand(time(NULL));

    if (argc < 6) {
       fprintf(stderr,"usage %s <hostname> <port> <filename> <loss probability> <corruption probability>\n", argv[0]);
       exit(1);
    }

    // get command line arguments
    server = gethostbyname(argv[1]);
    portno = atoi(argv[2]);
    filename = argv[3];
    lossprob = atof(argv[4]);
    corruptprob = atof(argv[5]);

    // error checks on arguments
    if (lossprob < 0.0 || lossprob > 1.0)
        error("packet loss probability must be between 0 and 1");
    if (corruptprob < 0.0 || corruptprob > 1.0)
        error("packet corruption probability must be between 0 and 1");
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }

    // create UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) 
        error("ERROR opening socket");
    
    // fill in address info
    memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons(portno);
    
    // create request
    memset((char *) &request, 0, sizeof(request));
    strcpy(request.data, filename);
    request.length = strlen(filename) + 1;
    request.type = TYPE_REQUEST;
    checksum(&request);

    // send request
    if (sendto(sockfd, &request, sizeof(request), 0, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
      error("ERROR sending request");
    printf("Sent request for file %s\n", filename);

    // in case request is lost at sender, enter timeout and resend if necessary
    int received_first_ack = 0;
    clock_t timer_start = clock();

    // create copy of file on receiver's end
    char * prefix = "copy_";
    char * filecopy = malloc(strlen(filename) + strlen(prefix) + 1);
    strcpy(filecopy, prefix);
    strcat(filecopy, filename);
    f = fopen(filecopy, "w");

    // scan for messages from server
    int time_wait_running = 0;
    while (1) {

        // resend request if timeout
        if (!received_first_ack && ( diff_ms(timer_start, clock()) > RETRANSMIT_TIMEOUT )) {
            // send request
            if (sendto(sockfd, &request, sizeof(request), 0, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
              error("ERROR sending request");
            printf("Sent request for file %s\n", filename);
            timer_start = clock();
        }

        if ( time_wait_running && ( diff_ms(timer_start, clock()) > TIME_WAIT ) ) {
            printf("Exiting time wait state.\n");
            break;
        }
        if (is_readable(sockfd)) {
            result = rdt_receive(sockfd, &receive, sizeof(receive), (struct sockaddr *) &serv_addr, &servlen, lossprob, corruptprob, expected_seq);
            if (received_first_ack == 0) {
                received_first_ack = 1;
            }
            if (result == RESULT_PACKET_OK) {
                send_ack(expected_seq, sockfd, serv_addr);
                expected_seq++;
                // transfer data to receiver's copy of the file
                fwrite(receive.data, 1, receive.length, f);
            }
            // don't send ACK if packet loss
            else if (result == RESULT_PACKET_CORRUPT || result == RESULT_PACKET_OUT_OF_ORDER) {
                send_ack(expected_seq - 1, sockfd, serv_addr);
            }
        }
        // only end if final ACK wasn't out of order, lost, or corrupt
        if(receive.type == TYPE_FINAL_DATA && result == RESULT_PACKET_OK && time_wait_running == 0) {
            printf("Final ACK sent, entering time wait state in case ACK is not received by sender.\n");
            timer_start = clock();
            time_wait_running = 1;
        }
    }


    close(sockfd);
    fclose(f);
    free(filecopy);
    return 0;
}
예제 #20
0
static gboolean is_accessible_file(mode_t mode)
{
        if(!S_ISREG(mode))
                return FALSE;
        return is_readable(mode);
}
예제 #21
0
int rp_bazaar_app_get_local_list(const char *dir, cJSON **json_root,
                                 ngx_pool_t *pool, int verbose)
{
	static int once = 1;
	if (once) {
		system("bazaar idgen 0");	
		once = 0;
	}
	
    DIR *dp;
    struct dirent *ep;

    if((dp = opendir(dir)) == NULL)
        return rp_module_cmd_error(json_root, "Can not open apps directory", 
                                   strerror(errno), pool);

    while((ep = readdir (dp))) {
        const char *app_id = ep->d_name;
        cJSON *info = NULL;

        /* check if structure is correct, we need: 
         *  <app_id>/info/info.json
         *  <app_id>/info/icon.png
         *  <app_id>/controllerhf.so
         *  <app_id>/fpga.bit
         * And we must be able to load the application and test mandatory
         * functions.
         */
        
        if (!is_readable(dir, app_id, "info/icon.png"))
            continue;
        if (!is_readable(dir, app_id, "fpga.conf"))
            continue;
        if (!is_controller_ok(dir, app_id, "controllerhf.so"))
            continue;
        if (!get_info(&info, dir, app_id, pool))
            continue;
        if (info == NULL)
            continue;

        /* We have an application */
        int demo = !is_registered(dir, app_id, "controllerhf.so");
		
        if (verbose) {
            /* Attach whole info JSON */
            cJSON_AddItemToObject(info, "type", cJSON_CreateString(demo ? "demo" : "run", pool), pool);
            cJSON_AddItemToObject(*json_root, app_id, info, pool);
        } else {
            /* Include version only */
            cJSON *j_ver = cJSON_GetObjectItem(info, "version");

            if(j_ver == NULL) {
                fprintf(stderr, "Cannot get version from info JSON.\n");
                cJSON_Delete(info, pool);
                continue;
            }
            
            cJSON_AddItemToObject(*json_root, app_id, cJSON_CreateString(j_ver->valuestring, pool), pool);
            cJSON_AddItemToObject(*json_root, "type", cJSON_CreateString(demo ? "demo" : "run", pool), pool);
            cJSON_Delete(j_ver, pool);
            cJSON_Delete(info, pool);
        }
    }

    closedir(dp);

    return 0;
}
예제 #22
0
파일: port.c 프로젝트: mundis/slap
/* open a serial-port device file, without possibly nasty side-effects.
 * If successful, a newly-open file-descriptor is returned. Otherwise, -1
 * is returned and errno is set to reflect the error.
 * The semantics of open() are used, except that:
 *
 *	(1) the file is opened without waiting for DCD to be asserted;
 *
 *	(2) the file is opened with signal-on-serial-break (termios BRKINT) 
 *	    disabled, and the open is done atomically with respect to SIGINT.
 *
 *	(3) flags which do not make sense for serial-port devices are ignored
 *	    (O_CREAT, O_EXCL, O_TRUNC, O_APPEND).
 *
 *	(4) Upon successful open, the serial-port's initial termios modes
 *	    (before suppression of BRKINT) are recorded at *saved_termios,
 *	    so that the caller can restore the extant port settings before
 *	    exit()-ing or close()-ing the file. NOTE: closetty() does such
 *	    a restore atomically with respect to SIGINT.
 *
 *	(5) The error ENOTTY is delivered if the specified name does not
 *	    refer to a serial-port device.
 *
 *	(6) If the file name is NULL, empty or "-", a new file-descriptor
 *	    referring to the same file as standard-output is generated,
 *	    rather than actually open()-ing the file.
 */
INT opentty(const CHAR *name, INT oflag, struct termios *save)
	{
	INT fd;
	struct termios tm;
	sigset_t mask, oldmask;

	assert(name && *name);

	oflag &= ~(O_CREAT|O_EXCL|O_TRUNC|O_APPEND);

	/* must block SIGINT to avoid possible interrruption between
	 * open() and supression of termios BRKINT mode...
	 * NOTE: must ensure that we can restore the current signal mask
	 * when finished.
	 */
	sigemptyset(&mask);
	sigemptyset(&oldmask);
	sigaddset(&mask, SIGINT);
	sigprocmask(SIG_BLOCK, &mask, &oldmask);

	if (!strcmp(name, "-"))
		{
		fd = dup(STDOUT_FILENO);
		switch (oflag & O_ACCMODE)
			{
		case O_RDONLY:
			if (!is_readable(fd))
				{
				sigprocmask(SIG_SETMASK, &oldmask, NULL);
				close(fd);
				return (-1);
				}
			break;
		case O_WRONLY:
			if (!is_writable(fd))
				{
				sigprocmask(SIG_SETMASK, &oldmask, NULL);
				close(fd);
				return (-1);
				}
			break;
		default:
			if (!is_readable(fd) || !is_writable(fd))
				{
				sigprocmask(SIG_SETMASK, &oldmask, NULL);
				close(fd);
				return (-1);
				}
			break;
			}
		}
	else
		{
		/* initially open with explicit O_NONBLOCK to avoid waiting for
		 * carrier-detect during open():
		 */
		if ((fd = open(name, oflag|O_NONBLOCK, 0)) < 0)
			{
			sigprocmask(SIG_SETMASK, &oldmask, NULL);
			return (-1);
			}
		}

	/* now set desired file-status flags:
	 */
	oflag &= ~O_ACCMODE;
	if (fcntl(fd, F_SETFL, oflag) < 0)
		{
		sigprocmask(SIG_SETMASK, &oldmask, NULL);
		close(fd);
		return (-1);
		}

	/* record original termios modes, for restore-on-close; and turn off
	 * BRKINT mode on the port; ....notice that this will catch
	 * the ENOTTY error as a handy side effect.
	 */
	if ((tcgetattr(fd, save) < 0) || (tcgetattr(fd, &tm) < 0))
		{
		sigprocmask(SIG_SETMASK, &oldmask, NULL);
		close(fd);
		return (-1);
		}
	tm.c_iflag &= ~BRKINT;
	if (tcsetattr(fd, TCSAFLUSH, &tm) < 0)
		{
		sigprocmask(SIG_SETMASK, &oldmask, NULL);
		close(fd);
		return (-1);
		}
	tcflush(fd, TCIOFLUSH);	/* paranoia! */

	/* now is safe to unblock SIGINT:
	 */
	sigprocmask(SIG_SETMASK, &oldmask, NULL);

	/* all done! */
	return (fd);
	}
예제 #23
0
void diag(FILE *output)
{
	char *yn[] = { "No", "Yes", "Unknown" };

	fprintf(output,"CVSNT Diagnostic output\n");
	fprintf(output,"-----------------------\n");
	fprintf(output,"\n");
	fprintf(output,"Server version: "CVSNT_PRODUCTVERSION_STRING"\n");
	fprintf(output,"OS Version: %s\n",get_os_version());
	fprintf(output,"\n");
	fprintf(output,"CVS Service installed: %s\n",service_installed("Cvsnt")?"Yes":"No");
	fprintf(output,"LockService installed: %s\n",service_installed("CvsLock")?"Yes":"No");
	fprintf(output,"\n");
	fprintf(output,":pserver: installed: %s\n",protocol_installed("pserver")?"Yes":"No");
	fprintf(output,":sserver: installed: %s\n",protocol_installed("sserver")?"Yes":"No");
	fprintf(output,":gserver: installed: %s\n",protocol_installed("gserver")?"Yes":"No");
	fprintf(output,":server: installed: %s\n",protocol_installed("server")?"Yes":"No");
	fprintf(output,":ssh: installed: %s\n",protocol_installed("ssh")?"Yes":"No");
	fprintf(output,":sspi: installed: %s\n",protocol_installed("sspi")?"Yes":"No");
	fprintf(output,":ext: installed: %s\n",protocol_installed("ext")?"Yes":"No");
	fprintf(output,"\n");
	fprintf(output,"Installation Path: %s\n",get_reg_string("InstallPath"));
	fprintf(output,"Repository 0 Path: %s\n",get_reg_string("Repository0"));
	fprintf(output,"Repository 0 Name: %s\n",get_reg_string("Repository0Name"));
	fprintf(output,"Repository 1 Path: %s\n",get_reg_string("Repository1"));
	fprintf(output,"Repository 1 Name: %s\n",get_reg_string("Repository1Name"));
	fprintf(output,"Repository 2 Path: %s\n",get_reg_string("Repository2"));
	fprintf(output,"Repository 2 Name: %s\n",get_reg_string("Repository2Name"));
	fprintf(output,"Repository 3 Path: %s\n",get_reg_string("Repository3"));
	fprintf(output,"Repository 3 Name: %s\n",get_reg_string("Repository3Name"));
	fprintf(output,"CVS Temp directory: %s\n",get_reg_string("TempDir"));
	fprintf(output,"CA Certificate File: %s\n",get_reg_string("CertificateFile"));
	fprintf(output,"Private Key File: %s\n",get_reg_string("PrivateKeyFile"));
	fprintf(output,"Local Users Only: %s\n",get_reg_int("DontUseDomain")?"Yes":"No");
	fprintf(output,"Default LockServer: %s\n",get_reg_string("LockServer"));
	fprintf(output,"Disable Reverse DNS: %s\n",get_reg_int("NoReverseDns")?"Yes":"No");
	fprintf(output,"Server Tracing: %s\n",get_reg_int("AllowTrace")?"Yes":"No");
	fprintf(output,"Case Sensitive: %s\n",get_reg_int("CaseSensitive")?"Yes":"No");
	fprintf(output,"Server listen port: %d\n",get_reg_int("PServerPort"));
	fprintf(output,"Compatibility (Non-cvsnt clients):\n");
	fprintf(output,"\tReport old CVS version: %s\n",get_reg_int("Compat0_OldVersion")?"Yes":"No");
	fprintf(output,"\tHide extended status: %s\n",get_reg_int("Compat0_HideStatus")?"Yes":"No");
	fprintf(output,"\tEmulate co -n bug: %s\n",get_reg_int("Compat0_OldCheckout")?"Yes":"No");
	fprintf(output,"\tIgnore client wrappers: %s\n",get_reg_int("Compat0_IgnoreWrappers")?"Yes":"No");
	fprintf(output,"Compatibility (CVSNT clients):\n");
	fprintf(output,"\tReport old CVS version: %s\n",get_reg_int("Compat1_OldVersion")?"Yes":"No");
	fprintf(output,"\tHide extended status: %s\n",get_reg_int("Compat1_HideStatus")?"Yes":"No");
	fprintf(output,"\tEmulate co -n bug: %s\n",get_reg_int("Compat1_OldCheckout")?"Yes":"No");
	fprintf(output,"\tIgnore client wrappers: %s\n",get_reg_int("Compat1_IgnoreWrappers")?"Yes":"No");
	fprintf(output,"Default domain: %s\n",get_reg_string("DefaultDomain"));
	fprintf(output,"Force run as user: %s\n",get_reg_string("RunAsUser"));
	fprintf(output,"\n");
	fprintf(output,"Temp dir readable by current user: %s\n",yn[is_readable(false,get_reg_string("TempDir"))]);
//	fprintf(output,"Temp dir readable by LocalSystem: %s\n",yn[is_readable(true,get_reg_string("TempDir"))]);
	fprintf(output,"Repository0 readable by current user: %s\n",yn[is_readable(false,get_reg_string("Repository0"))]);
//	fprintf(output,"Repository0 readable by LocalSystem: %s\n",yn[is_readable(true,get_reg_string("Repository0"))]);
	fprintf(output,"Temp dir writable by current user: %s\n",yn[is_writable(false,get_reg_string("TempDir"))]);
//	fprintf(output,"Temp dir writable by LocalSystem: %s\n",yn[is_writable(true,get_reg_string("TempDir"))]);
	fprintf(output,"\n");
	fprintf(output,"AV files detected:\n");
	print_found_files(output,"_AVP32.EXE\0_AVPCC.EXE\0_AVPM.EXE\0AVP32.EXE\0AVPCC.EXE\0AVPM.EXE\0"
							"N32SCANW.EXE\0NAVAPSVC.EXE\0NAVAPW32.EXE\0NAVLU32.EXE\0NAVRUNR.EXE\0NAVW32.EXE"
							"NAVWNT.EXE\0NOD32.EXE\0NPSSVC.EXE\0NRESQ32.EXE\0NSCHED32.EXE\0NSCHEDNT.EXE"
							"NSPLUGIN.EXE\0SCAN.EXE\0AVGSRV.EXE\0AVGSERV.EXE\0AVGCC32.EXE\0AVGCC.EXE\0"
							"AVGAMSVR.EXE\0AVGUPSVC.EXE\0NOD32KRN.EXE\0NOD32KUI.EXE\0");

	fprintf(output,"\n");
	WSADATA wsa = {0};
	if(WSAStartup(MAKEWORD(2,0),&wsa))
		fprintf(output,"Winsock intialisation failed!\n");
	else
	{
		fprintf(output,"Installed Winsock protocols:\n\n");
		DWORD dwSize=0;
		LPWSAPROTOCOL_INFO proto;
		WSAEnumProtocols(NULL,NULL,&dwSize);
		proto=(LPWSAPROTOCOL_INFO)malloc(dwSize);
		WSAEnumProtocols(NULL,proto,&dwSize);
		for(int n=0; n<(int)(dwSize/sizeof(proto[0])); n++)
		{
			if(!strncmp(proto[n].szProtocol,"MSAFD NetBIOS",13))
				continue; // Ignore netbios layers
			fprintf(output,"%d: %s\n",proto[n].dwCatalogEntryId,proto[n].szProtocol);
		}
		free(proto);
	}
}
예제 #24
0
파일: samba3hide.c 프로젝트: Arkhont/samba
bool torture_samba3_hide(struct torture_context *torture)
{
	struct smbcli_state *cli;
	const char *fname = "test.txt";
	int fnum;
	NTSTATUS status;
	struct smbcli_tree *hideunread;
	struct smbcli_tree *hideunwrite;

	if (!torture_open_connection_share(
		    torture, &cli, torture, torture_setting_string(torture, "host", NULL),
		    torture_setting_string(torture, "share", NULL), torture->ev)) {
		torture_fail(torture, "torture_open_connection_share failed\n");
	}

	status = torture_second_tcon(torture, cli->session, "hideunread",
				     &hideunread);
	torture_assert_ntstatus_ok(torture, status, "second_tcon(hideunread) failed\n");

	status = torture_second_tcon(torture, cli->session, "hideunwrite",
				     &hideunwrite);
	torture_assert_ntstatus_ok(torture, status, "second_tcon(hideunwrite) failed\n");

	status = smbcli_unlink(cli->tree, fname);
	if (NT_STATUS_EQUAL(status, NT_STATUS_CANNOT_DELETE)) {
		smbcli_setatr(cli->tree, fname, 0, -1);
		smbcli_unlink(cli->tree, fname);
	}

	fnum = smbcli_open(cli->tree, fname, O_RDWR|O_CREAT, DENY_NONE);
	if (fnum == -1) {
		torture_fail(torture,
			talloc_asprintf(torture, "Failed to create %s - %s\n", fname, smbcli_errstr(cli->tree)));
	}

	smbcli_close(cli->tree, fnum);

	if (!smbcli_file_exists(cli->tree, fname)) {
		torture_fail(torture, talloc_asprintf(torture, "%s does not exist\n", fname));
	}

	/* R/W file should be visible everywhere */

	status = smbcli_chmod(cli->tree, fname, UNIX_R_USR|UNIX_W_USR);
	torture_assert_ntstatus_ok(torture, status, "smbcli_chmod failed\n");

	if (!is_writeable(torture, cli->tree, fname)) {
		torture_fail(torture, "File not writable\n");
	}
	if (!is_readable(cli->tree, fname)) {
		torture_fail(torture, "File not readable\n");
	}
	if (!is_visible(cli->tree, fname)) {
		torture_fail(torture, "r/w file not visible via normal share\n");
	}
	if (!is_visible(hideunread, fname)) {
		torture_fail(torture, "r/w file not visible via hide unreadable\n");
	}
	if (!is_visible(hideunwrite, fname)) {
		torture_fail(torture, "r/w file not visible via hide unwriteable\n");
	}

	/* R/O file should not be visible via hide unwriteable files */

	status = smbcli_chmod(cli->tree, fname, UNIX_R_USR);
	torture_assert_ntstatus_ok(torture, status, "smbcli_chmod failed\n");

	if (is_writeable(torture, cli->tree, fname)) {
		torture_fail(torture, "r/o is writable\n");
	}
	if (!is_readable(cli->tree, fname)) {
		torture_fail(torture, "r/o not readable\n");
	}
	if (!is_visible(cli->tree, fname)) {
		torture_fail(torture, "r/o file not visible via normal share\n");
	}
	if (!is_visible(hideunread, fname)) {
		torture_fail(torture, "r/o file not visible via hide unreadable\n");
	}
	if (is_visible(hideunwrite, fname)) {
		torture_fail(torture, "r/o file visible via hide unwriteable\n");
	}

	/* inaccessible file should be only visible on normal share */

	status = smbcli_chmod(cli->tree, fname, 0);
	torture_assert_ntstatus_ok(torture, status, "smbcli_chmod failed\n");

	if (is_writeable(torture, cli->tree, fname)) {
		torture_fail(torture, "inaccessible file is writable\n");
	}
	if (is_readable(cli->tree, fname)) {
		torture_fail(torture, "inaccessible file is readable\n");
	}
	if (!is_visible(cli->tree, fname)) {
		torture_fail(torture, "inaccessible file not visible via normal share\n");
	}
	if (is_visible(hideunread, fname)) {
		torture_fail(torture, "inaccessible file visible via hide unreadable\n");
	}
	if (is_visible(hideunwrite, fname)) {
		torture_fail(torture, "inaccessible file visible via hide unwriteable\n");
	}

	smbcli_chmod(cli->tree, fname, UNIX_R_USR|UNIX_W_USR);
	smbcli_unlink(cli->tree, fname);
	
	return true;
}