Пример #1
0
gesture*
make_gesture_array(u_int size)
{
    return((gesture*)safe_malloc(size * sizeof(gesture)));
}
Пример #2
0
static int
send_file_chunk (guestfs_h *g, int cancel, const char *buf, size_t buflen)
{
  uint32_t len;
  ssize_t r;
  guestfs_chunk chunk;
  XDR xdr;
  CLEANUP_FREE char *msg_out = NULL;
  size_t msg_out_size;

  /* Allocate the chunk buffer.  Don't use the stack to avoid
   * excessive stack usage and unnecessary copies.
   */
  msg_out = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE + 4 + 48);
  xdrmem_create (&xdr, msg_out + 4, GUESTFS_MAX_CHUNK_SIZE + 48, XDR_ENCODE);

  /* Serialize the chunk. */
  chunk.cancel = cancel;
  chunk.data.data_len = buflen;
  chunk.data.data_val = (char *) buf;

  if (!xdr_guestfs_chunk (&xdr, &chunk)) {
    error (g, _("xdr_guestfs_chunk failed (buf = %p, buflen = %zu)"),
           buf, buflen);
    xdr_destroy (&xdr);
    return -1;
  }

  len = xdr_getpos (&xdr);
  xdr_destroy (&xdr);

  /* Reduce the size of the outgoing message buffer to the real length. */
  msg_out = safe_realloc (g, msg_out, len + 4);
  msg_out_size = len + 4;

  xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
  xdr_uint32_t (&xdr, &len);

  /* Did the daemon send a cancellation message? */
  r = check_daemon_socket (g);
  if (r == -2) {
    debug (g, "got daemon cancellation");
    return -2;
  }
  if (r == -1)
    return -1;
  if (r == 0) {
    guestfs_int_unexpected_close_error (g);
    child_cleanup (g);
    return -1;
  }

  /* Send the chunk. */
  r = g->conn->ops->write_data (g, g->conn, msg_out, msg_out_size);
  if (r == -1)
    return -1;
  if (r == 0) {
    guestfs_int_unexpected_close_error (g);
    child_cleanup (g);
    return -1;
  }

  return 0;
}
Пример #3
0
static int output_data(char *buf, int32 nbytes)
{
  FLAC__int32 *oggbuf;
  FLAC__int16 *s;
  int i;
  int nch = (dpm.encoding & PE_MONO) ? 1 : 2;

  FLAC_ctx *ctx = flac_ctx;

  if (dpm.fd < 0)
    return 0;

  if (ctx == NULL) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC stream is not initialized");
    return -1;
  }

  oggbuf = (FLAC__int32 *)safe_malloc(nbytes * sizeof(FLAC__int32) / nch);

  /*
    packing 16 -> 32 bit sample
  */
  s = (FLAC__int16 *)buf;
  for (i = 0; i < nbytes / nch; i++) {
    oggbuf[i] = *s++;
  }

#ifdef LEGACY_FLAC
#ifdef AU_OGGFLAC
  if (flac_options.isogg) {
    ctx->state.ogg = OggFLAC__stream_encoder_get_state(ctx->encoder.ogg.stream);
    if (ctx->state.ogg != OggFLAC__STREAM_ENCODER_OK) {
      if (ctx->state.ogg == OggFLAC__STREAM_ENCODER_FLAC_STREAM_ENCODER_ERROR) {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC stream verify error (%s)",
		  FLAC__StreamDecoderStateString[OggFLAC__stream_encoder_get_verify_decoder_state(ctx->encoder.ogg.stream)]);
      }
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode OggFLAC stream (%s)",
		OggFLAC__StreamEncoderStateString[ctx->state.ogg]);
      flac_session_close();
      return -1;
    }

    if (!OggFLAC__stream_encoder_process_interleaved(ctx->encoder.ogg.stream, oggbuf,
						     nbytes / nch / 2)) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode OggFLAC stream");
      flac_session_close();
      return -1;
    }
  }
  else
#endif /* AU_OGGFLAC */
	if (flac_options.seekable) {
    ctx->state.s_flac = FLAC__seekable_stream_encoder_get_state(ctx->encoder.flac.s_stream);
    if (ctx->state.s_flac != FLAC__STREAM_ENCODER_OK) {
      if (ctx->state.s_flac == FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR |
	  FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC stream verify error (%s)",
		  FLAC__SeekableStreamDecoderStateString[FLAC__seekable_stream_encoder_get_verify_decoder_state(ctx->encoder.flac.s_stream)]);
      }
      else {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode FLAC stream (%s)",
		  FLAC__SeekableStreamEncoderStateString[ctx->state.s_flac]);
      }
      flac_session_close();
      return -1;
    }

    if (!FLAC__seekable_stream_encoder_process_interleaved(ctx->encoder.flac.s_stream, oggbuf,
						  nbytes / nch / 2 )) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode FLAC stream");
      flac_session_close();
      return -1;
    }
	}
  else
	{
    ctx->state.flac = FLAC__stream_encoder_get_state(ctx->encoder.flac.stream);
    if (ctx->state.flac != FLAC__STREAM_ENCODER_OK) {
      if (ctx->state.flac == FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR |
	  FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA) {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC stream verify error (%s)",
		  FLAC__StreamDecoderStateString[FLAC__stream_encoder_get_verify_decoder_state(ctx->encoder.flac.stream)]);
      }
      else {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode FLAC stream (%s)",
		  FLAC__StreamEncoderStateString[ctx->state.flac]);
      }
      flac_session_close();
      return -1;
    }

    if (!FLAC__stream_encoder_process_interleaved(ctx->encoder.flac.stream, oggbuf,
						  nbytes / nch / 2 )) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode FLAC stream");
      flac_session_close();
      return -1;
    }
  }
#else /* !LEGACY_FLAC */
  ctx->state.flac = FLAC__stream_encoder_get_state(ctx->encoder.flac.stream);
  if (ctx->state.flac != FLAC__STREAM_ENCODER_OK) {
    if (ctx->state.flac == FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "FLAC stream verify error (%s)",
		FLAC__StreamDecoderStateString[FLAC__stream_encoder_get_verify_decoder_state(ctx->encoder.flac.stream)]);
    }
    else {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode FLAC stream (%s)",
		FLAC__StreamEncoderStateString[ctx->state.flac]);
    }
    flac_session_close();
    return -1;
  }

  if (!FLAC__stream_encoder_process_interleaved(ctx->encoder.flac.stream, oggbuf,
						nbytes / nch / 2 )) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "cannot encode FLAC stream");
    flac_session_close();
    return -1;
  }
#endif
  ctx->in_bytes += nbytes;

  free(oggbuf);
  return 0;
}
Пример #4
0
static status_t
vmi_init_private(
    vmi_instance_t *vmi,
    uint32_t flags,
    uint64_t id,
    const char *name,
    vmi_config_t config)
{
    uint32_t access_mode = flags & 0x0000FFFF;
    uint32_t init_mode = flags & 0x00FF0000;
    uint32_t config_mode = flags & 0xFF000000;
    status_t status = VMI_FAILURE;

    /* allocate memory for instance structure */
    *vmi = (vmi_instance_t) safe_malloc(sizeof(struct vmi_instance));
    memset(*vmi, 0, sizeof(struct vmi_instance));

    /* initialize instance struct to default values */
    dbprint(VMI_DEBUG_CORE, "LibVMI Version 0.11.0\n");  //TODO change this with each release

    /* save the flags and init mode */
    (*vmi)->flags = flags;
    (*vmi)->init_mode = init_mode;
    (*vmi)->config_mode = config_mode;

    /* the config hash table is set up later based on mode */
    (*vmi)->config = NULL;

    /* set page mode to unknown */
    (*vmi)->page_mode = VMI_PM_UNKNOWN;

    /* setup the caches */
    pid_cache_init(*vmi);
    sym_cache_init(*vmi);
    rva_cache_init(*vmi);
    v2p_cache_init(*vmi);

    if ( init_mode & VMI_INIT_SHM_SNAPSHOT ) {
#if ENABLE_SHM_SNAPSHOT == 1
        v2m_cache_init(*vmi);
#else
        errprint("LibVMI wasn't compiled with SHM support!\n");
        status = VMI_FAILURE;
        goto error_exit;
#endif
    }

    /* connecting to xen, kvm, file, etc */
    if (VMI_FAILURE == set_driver_type(*vmi, access_mode, id, name)) {
        goto error_exit;
    }

    /* driver-specific initilization */
    if (VMI_FAILURE == driver_init(*vmi)) {
        goto error_exit;
    }
    dbprint(VMI_DEBUG_CORE, "--completed driver init.\n");

    /* resolve the id and name */
    if (VMI_FAILURE == set_id_and_name(*vmi, access_mode, id, name)) {
        goto error_exit;
    }

    /* init vmi for specific file/domain through the driver */
    if (VMI_FAILURE == driver_init_vmi(*vmi)) {
        goto error_exit;
    }

    /* setup the page offset size */
    if (VMI_FAILURE == init_page_offset(*vmi)) {
        goto error_exit;
    }

    /* get the memory size */
    if (driver_get_memsize(*vmi, &(*vmi)->allocated_ram_size, &(*vmi)->max_physical_address) == VMI_FAILURE) {
        errprint("Failed to get memory size.\n");
        goto error_exit;
    }
    dbprint(VMI_DEBUG_CORE, "**set size = %"PRIu64" [0x%"PRIx64"]\n", (*vmi)->size,
        (*vmi)->size);

    // for file mode we need os-specific heuristics to deduce the architecture
    // for live mode, having arch_interface set even in VMI_PARTIAL mode
    // allows use of dtb-based translation methods.
    if (VMI_FILE != (*vmi)->mode) {
        if(VMI_FAILURE == arch_init(*vmi)) {
            if (init_mode & VMI_INIT_COMPLETE) {
                dbprint(VMI_DEBUG_CORE, "--failed to determine architecture of live vm and INIT_COMPLETE.\n");
                goto error_exit;
            } else {
                dbprint(VMI_DEBUG_CORE, "--failed to determine architecture of live vm and INIT_PARTIAL, continuing.\n");
            }
        } else {
            dbprint(VMI_DEBUG_CORE, "--succesfully completed architecture init.\n");
        }
    }


    /* we check VMI_INIT_COMPLETE first as
       VMI_INIT_PARTIAL is not exclusive */
    if (init_mode & VMI_INIT_COMPLETE) {
        switch((*vmi)->config_mode) {
            case VMI_CONFIG_STRING:
                /* read and parse the config string */
                if(VMI_FAILURE == read_config_string(*vmi, (char*)config)) {
                    goto error_exit;
                }
                break;
            case VMI_CONFIG_GLOBAL_FILE_ENTRY:
                /* read and parse the config file */
                if(VMI_FAILURE == read_config_file_entry(*vmi)) {
                    goto error_exit;
                }
                break;
            case VMI_CONFIG_GHASHTABLE:
                /* read and parse the ghashtable */
                if (!config) {
                    goto error_exit;
                }
                (*vmi)->config = (GHashTable*)config;
                break;
            case VMI_CONFIG_NONE:
            default:
                /* init_complete requires configuration
                   falling back to VMI_CONFIG_GLOBAL_FILE_ENTRY is unsafe here
                   as the config pointer is probably NULL */
                goto error_exit;
        }

        if(VMI_FAILURE == set_os_type_from_config(*vmi)) {
            dbprint(VMI_DEBUG_CORE, "--failed to determine os type from config\n");
            goto error_exit;
        }

        /* setup OS specific stuff */
        switch ( (*vmi)->os_type )
        {
#ifdef ENABLE_LINUX
        case VMI_OS_LINUX:
            if(VMI_FAILURE == linux_init(*vmi)) {
                goto error_exit;
            }
            break;
#endif
#ifdef ENABLE_WINDOWS
        case VMI_OS_WINDOWS:
            if(VMI_FAILURE == windows_init(*vmi)) {
                goto error_exit;
            }
            break;
#endif
        default:
            goto error_exit;
        }

        status = VMI_SUCCESS;

    } else if (init_mode & VMI_INIT_PARTIAL) {

        status = VMI_SUCCESS;

    } else {

        errprint("Need to specify either VMI_INIT_PARTIAL or VMI_INIT_COMPLETE.\n");
        goto error_exit;

    }

    if(init_mode & VMI_INIT_EVENTS) {
#if ENABLE_XEN_EVENTS == 1
        /* Enable event handlers */
        events_init(*vmi);
#else
        errprint("LibVMI wasn't compiled with events support!\n");
        status = VMI_FAILURE;
#endif
    }

error_exit:
    return status;
}
Пример #5
0
int
guestfs_int_send (guestfs_h *g, int proc_nr,
		  uint64_t progress_hint, uint64_t optargs_bitmask,
		  xdrproc_t xdrp, char *args)
{
  struct guestfs_message_header hdr;
  XDR xdr;
  uint32_t len;
  int serial = g->msg_next_serial++;
  ssize_t r;
  CLEANUP_FREE char *msg_out = NULL;
  size_t msg_out_size;

  if (!g->conn) {
    guestfs_int_unexpected_close_error (g);
    return -1;
  }

  /* We have to allocate this message buffer on the heap because
   * it is quite large (although will be mostly unused).  We
   * can't allocate it on the stack because in some environments
   * we have quite limited stack space available, notably when
   * running in the JVM.
   */
  msg_out = safe_malloc (g, GUESTFS_MESSAGE_MAX + 4);
  xdrmem_create (&xdr, msg_out + 4, GUESTFS_MESSAGE_MAX, XDR_ENCODE);

  /* Serialize the header. */
  hdr.prog = GUESTFS_PROGRAM;
  hdr.vers = GUESTFS_PROTOCOL_VERSION;
  hdr.proc = proc_nr;
  hdr.direction = GUESTFS_DIRECTION_CALL;
  hdr.serial = serial;
  hdr.status = GUESTFS_STATUS_OK;
  hdr.progress_hint = progress_hint;
  hdr.optargs_bitmask = optargs_bitmask;

  if (!xdr_guestfs_message_header (&xdr, &hdr)) {
    error (g, _("xdr_guestfs_message_header failed"));
    return -1;
  }

  /* Serialize the args.  If any, because some message types
   * have no parameters.
   */
  if (xdrp) {
    if (!(*xdrp) (&xdr, args, 0)) {
      error (g, _("dispatch failed to marshal args"));
      return -1;
    }
  }

  /* Get the actual length of the message, resize the buffer to match
   * the actual length, and write the length word at the beginning.
   */
  len = xdr_getpos (&xdr);
  xdr_destroy (&xdr);

  msg_out = safe_realloc (g, msg_out, len + 4);
  msg_out_size = len + 4;

  xdrmem_create (&xdr, msg_out, 4, XDR_ENCODE);
  xdr_uint32_t (&xdr, &len);

  /* Look for stray daemon cancellation messages from earlier calls
   * and ignore them.
   */
  r = check_daemon_socket (g);
  /* r == -2 (cancellation) is ignored */
  if (r == -1)
    return -1;
  if (r == 0) {
    guestfs_int_unexpected_close_error (g);
    child_cleanup (g);
    return -1;
  }

  /* Send the message. */
  r = g->conn->ops->write_data (g, g->conn, msg_out, msg_out_size);
  if (r == -1)
    return -1;
  if (r == 0) {
    guestfs_int_unexpected_close_error (g);
    child_cleanup (g);
    return -1;
  }

  return serial;
}
Пример #6
0
driver_exec_t *driver_exec_create(select_group_t *group, char *process, char *name)
{
  driver_exec_t *driver_exec = (driver_exec_t*) safe_malloc(sizeof(driver_exec_t));
  message_options_t options[2];

  /* Declare some WIN32 variables needed for starting the sub-process. */
#ifdef WIN32
  STARTUPINFOA         startupInfo;
  PROCESS_INFORMATION  processInformation;
  SECURITY_ATTRIBUTES  sa;
#endif

  driver_exec->process = process;
  driver_exec->group   = group;
  driver_exec->name    = name ? name : process;

  /* Subscribe to the messages we care about. */
  message_subscribe(MESSAGE_DATA_IN,         handle_message, driver_exec);

  /* Set up the session options and create the session. */
  options[0].name    = "name";
  options[0].value.s = driver_exec->name;

  options[1].name    = NULL;

  driver_exec->session_id = message_post_create_session(options);
#ifdef WIN32
  /* Create a security attributes structure. This is required to inherit handles. */
  ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
  sa.nLength              = sizeof(SECURITY_ATTRIBUTES);
  sa.lpSecurityDescriptor = NULL;
  sa.bInheritHandle       = TRUE;

  /* Create the anonymous pipes. */
  if(!CreatePipe(&driver_exec->exec_stdin[PIPE_READ], &driver_exec->exec_stdin[PIPE_WRITE], &sa, 0))
    DIE("exec: Couldn't create pipe for stdin");
  if(!CreatePipe(&driver_exec->exec_stdout[PIPE_READ], &driver_exec->exec_stdout[PIPE_WRITE], &sa, 0))
    DIE("exec: Couldn't create pipe for stdout");

  fprintf(stderr, "Attempting to load the program: %s\n", driver_exec->process);

  /* Initialize the STARTUPINFO structure. */
  ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
  startupInfo.cb         = sizeof(STARTUPINFO);
  startupInfo.dwFlags    = STARTF_USESTDHANDLES;
  startupInfo.hStdInput  = driver_exec->exec_stdin[PIPE_READ];
  startupInfo.hStdOutput = driver_exec->exec_stdout[PIPE_WRITE];
  startupInfo.hStdError = driver_exec->exec_stdout[PIPE_WRITE];

  /* Initialize the PROCESS_INFORMATION structure. */
  ZeroMemory(&processInformation, sizeof(PROCESS_INFORMATION));

  /* Create the actual process with an overly-complicated CreateProcess function. */
  if(!CreateProcessA(NULL, driver_exec->process, 0, &sa, TRUE, CREATE_NO_WINDOW, 0, NULL, &startupInfo, &processInformation))
  {
    fprintf(stderr, "Failed to create the process");
    exit(1);
  }

  /* Save the process id and the handle. */
  driver_exec->pid = processInformation.dwProcessId;
  driver_exec->exec_handle = processInformation.hProcess;

  /* Close the duplicate pipes we created -- this lets us detect the proicess termination. */
  CloseHandle(driver_exec->exec_stdin[PIPE_READ]);
  CloseHandle(driver_exec->exec_stdout[PIPE_WRITE]);
  CloseHandle(driver_exec->exec_stdout[PIPE_WRITE]);

  fprintf(stderr, "Successfully created the process!\n\n");

  /* Create a socket_id value - this is a totally arbitrary value that's only used so we can find this entry later. */
  driver_exec->socket_id = --driver_exec->socket_id;

  /* On Windows, add the sub-process's stdout as a pipe. */
  select_group_add_pipe(driver_exec->group, driver_exec->socket_id, driver_exec->exec_stdout[PIPE_READ], driver_exec);
  select_set_recv(driver_exec->group, driver_exec->socket_id, exec_callback);
  select_set_closed(driver_exec->group, driver_exec->socket_id, exec_closed_callback);
#else
  LOG_INFO("Attempting to start process '%s'...", driver_exec->process);

  /* Create communication channels. */
  if(pipe(driver_exec->pipe_stdin) == -1)
  {
    LOG_FATAL("exec: couldn't create pipe (%d)", errno);
    exit(1);
  }

  if(pipe(driver_exec->pipe_stdout) == -1)
  {
    LOG_FATAL("exec: couldn't create pipe (%d)", errno);
    exit(1);
  }

  driver_exec->pid = fork();

  if(driver_exec->pid == -1)
  {
    LOG_FATAL("exec: couldn't create process (%d)", errno);
    exit(1);
  }

  /* If we're in the child process... */
  if(driver_exec->pid == 0)
  {
    /* Copy the pipes. */
    if(dup2(driver_exec->pipe_stdin[PIPE_READ], STDIN_FILENO) == -1)
      nbdie("exec: couldn't duplicate STDIN handle");

    if(dup2(driver_exec->pipe_stdout[PIPE_WRITE], STDOUT_FILENO) == -1)
      nbdie("exec: couldn't duplicate STDOUT handle");

    if(dup2(driver_exec->pipe_stdout[PIPE_WRITE], STDERR_FILENO) == -1)
      nbdie("exec: couldn't duplicate STDERR handle");

    /* Execute the new process. */
    execlp("/bin/sh", "sh", "-c", driver_exec->process, (char*) NULL);

    /* If execlp returns, bad stuff happened. */
    LOG_FATAL("exec: execlp failed (%d)", errno);
    exit(1);
  }

  LOG_WARNING("Started: %s (pid: %d)", driver_exec->process, driver_exec->pid);
  close(driver_exec->pipe_stdin[PIPE_READ]);
  close(driver_exec->pipe_stdout[PIPE_WRITE]);

  /* Add the sub-process's stdout as a socket. */
  select_group_add_socket(driver_exec->group, driver_exec->pipe_stdout[PIPE_READ], SOCKET_TYPE_STREAM, driver_exec);
  select_set_recv(driver_exec->group,         driver_exec->pipe_stdout[PIPE_READ], exec_callback);
  select_set_closed(driver_exec->group,       driver_exec->pipe_stdout[PIPE_READ], exec_closed_callback);
#endif
  return driver_exec;
}
Пример #7
0
int ea_setxattr_rcs(const char *path, const char *name, const char *value, size_t size)
{
  metadata_t *metadata;
  version_t *version;
  
  rcs_ignore_deleted = 1;
  metadata = rcs_translate_to_metadata(path, rcs_version_path);
  rcs_ignore_deleted = 0;
  if (!metadata)
    return -ENOENT;

  if (!strcmp(name,"rcs.purge"))
    {
      /* Copy the value to NUL-terminate it */
      char *local;
      local = safe_malloc(size + 1);
      local[size] = '\0';
      memcpy(local, value, size);

      // Get the full path to the metadatafile
      char *mdfile=helper_build_meta_name(path, METADATA_PREFIX);
      if (!mdfile)
        return -ENOENT;
        
      int c=1; // how many versions to delete
      int vnum=1; // number of versions
      
      if(!strcmp(local,"A")) {
        // Delete them all
        // we don't have to count the versions
        // we just leave c and vnum at 1
      } else {
        // we have a number, so set c to it
        c=atoi(local);
        
        // Count the number of versions there are
        version = metadata->md_versions;
        while(version->v_next) { 
          version=version->v_next;
          vnum++; 
        }
      }
      
      /* Let's do this... Crawl through the list, nulling
       * next's and unlinking files
       */
      version_t *next;
      version = metadata->md_versions;
      if(c >= vnum) {
        // we're toasting them all...
        while(version) {
          //unlink file.. scary!
          unlink(version->v_rfile);
          /* No need to clean up version data.
           * This is done later by rcs_free_metadata */
          version=version->v_next;
        }
        
        // Free the metadata from cache
        cache_drop_metadata(metadata);
        rcs_free_metadata(metadata);
        
        // kill the metadata file too.. SCARY!!!
        unlink(mdfile);
      } else {
        // cull
        vnum-=c; // number of versions we want to _keep_.
        while(version) {
          if(vnum > 1) {
            // we want to keep this version
            vnum--;
            version=version->v_next;
        }
          else if (vnum == 1) {
          // this is the last version to keep
          vnum--;
          next=version->v_next;
            version->v_next = NULL;
          version=next;
        }
          else {
            //delete this version
            
          //unlink file.. scary!
          unlink(version->v_rfile);
          
            next=version->v_next;
          free(version->v_rfile);
          free(version);
            version=next;
          }
        }
        
        // We've made changes to the metadata, and got at least one
        // version left.. need to update it
        if (write_metadata_file(mdfile, metadata) == -1) {
          free(mdfile);
          return -errno;
        }
      }
      
      free(mdfile);
      return 0;
      
    }
  else if (!strcmp(name, "rcs.locked_version"))
    {
      struct fuse_context *context;
      unsigned int length;
      int vid, svid;
      char *dflfile, *metafile, *local;

      /* Copy the value to NUL-terminate it */
      local = safe_malloc(size + 1);
      local[size] = '\0';
      memcpy(local, value, size);

      vid = 0; svid = 0;
      if ((sscanf(local, "%d.%d%n", &vid, &svid, &length) != 2) ||
        (length != size))
        {
          free(local);
          return -EINVAL;
        }
      free(local);

      /* Check if we actually have that version (or a compatible version) */
      version = rcs_find_version(metadata, vid, svid);
      if (!version)
        return -EINVAL;

      /*
       * Only allow a user to change the version if the new version has the
       * same owner as the one requesting the change, or if the user is root,
       * to prevent curious users from resurrecting versions with too lax
       * permissions.
       */
      context = fuse_get_context();
      if ((context->uid != 0) && (context->uid != version->v_uid))
        return -EACCES;

      /* Try to commit to disk */
      dflfile = helper_build_meta_name(path, DFL_VERSION_PREFIX);
      if (dflfile == NULL)
        {
          /* This happens if parent directiory is deleted */
          return -ENOENT;
        }
      else if (write_default_file(dflfile, vid, svid) != 0)
        {
          free(dflfile);
          return -errno;
        }
      free(dflfile);
      
      /* If ok, change in RAM */
      metadata->md_dfl_vid = vid;
      metadata->md_dfl_svid = svid;
      
      /* remove deletion flag from metadata*/
      if (metadata->md_deleted)
      {
        metadata->md_deleted = 0;
        metafile = helper_build_meta_name(path, METADATA_PREFIX);
        if (write_metadata_file(metafile, metadata) != 0)
        {
          free(metafile);
          return -errno;
        }
        free(metafile);
      }

      return 0;
    }
  else if (!strcmp(name, "rcs.metadata_dump"))
    {
      /* This one is read-only */
      return -EPERM;
    }
  else
    {
      /* unknown rcs.*-attribute */
      return -EPERM;
    }
}
Пример #8
0
int mutt_parse_hook (BUFFER *buf, BUFFER *s, unsigned long data, BUFFER *err)
{
  HOOK *ptr;
  BUFFER command, pattern;
  int rc, not = 0;
  regex_t *rx = NULL;
  pattern_t *pat = NULL;
  char path[_POSIX_PATH_MAX];

  mutt_buffer_init (&pattern);
  mutt_buffer_init (&command);

  if (*s->dptr == '!')
  {
    s->dptr++;
    SKIPWS (s->dptr);
    not = 1;
  }

  mutt_extract_token (&pattern, s, 0);

  if (!MoreArgs (s))
  {
    strfcpy (err->data, _("too few arguments"), err->dsize);
    goto error;
  }

  mutt_extract_token (&command, s, (data & (MUTT_FOLDERHOOK | MUTT_SENDHOOK | MUTT_SEND2HOOK | MUTT_ACCOUNTHOOK | MUTT_REPLYHOOK)) ?  MUTT_TOKEN_SPACE : 0);

  if (!command.data)
  {
    strfcpy (err->data, _("too few arguments"), err->dsize);
    goto error;
  }

  if (MoreArgs (s))
  {
    strfcpy (err->data, _("too many arguments"), err->dsize);
    goto error;
  }

  if (data & (MUTT_FOLDERHOOK | MUTT_MBOXHOOK))
  {
    /* Accidentally using the ^ mailbox shortcut in the .muttrc is a
     * common mistake */
    if ((*pattern.data == '^') && (! CurrentFolder))
    {
      strfcpy (err->data, _("current mailbox shortcut '^' is unset"), err->dsize);
      goto error;
    }

    strfcpy (path, pattern.data, sizeof (path));
    _mutt_expand_path (path, sizeof (path), 1);

    /* Check for other mailbox shortcuts that expand to the empty string.
     * This is likely a mistake too */
    if (!*path && *pattern.data)
    {
      strfcpy (err->data, _("mailbox shortcut expanded to empty regexp"), err->dsize);
      goto error;
    }

    FREE (&pattern.data);
    memset (&pattern, 0, sizeof (pattern));
    pattern.data = safe_strdup (path);
  }
  else if (DefaultHook && !(data & (MUTT_CHARSETHOOK | MUTT_ICONVHOOK | MUTT_ACCOUNTHOOK))
           && (!WithCrypto || !(data & MUTT_CRYPTHOOK))
      )
  {
    char tmp[HUGE_STRING];

    /* At this stage remain only message-hooks, reply-hooks, send-hooks,
     * send2-hooks, save-hooks, and fcc-hooks: All those allowing full
     * patterns. If given a simple regexp, we expand $default_hook.
     */
    strfcpy (tmp, pattern.data, sizeof (tmp));
    mutt_check_simple (tmp, sizeof (tmp), DefaultHook);
    FREE (&pattern.data);
    memset (&pattern, 0, sizeof (pattern));
    pattern.data = safe_strdup (tmp);
  }

  if (data & (MUTT_MBOXHOOK | MUTT_SAVEHOOK | MUTT_FCCHOOK))
  {
    strfcpy (path, command.data, sizeof (path));
    mutt_expand_path (path, sizeof (path));
    FREE (&command.data);
    memset (&command, 0, sizeof (command));
    command.data = safe_strdup (path);
  }

  /* check to make sure that a matching hook doesn't already exist */
  for (ptr = Hooks; ptr; ptr = ptr->next)
  {
    if (ptr->type == data &&
	ptr->rx.not == not &&
	!mutt_strcmp (pattern.data, ptr->rx.pattern))
    {
      if (data & (MUTT_FOLDERHOOK | MUTT_SENDHOOK | MUTT_SEND2HOOK | MUTT_MESSAGEHOOK | MUTT_ACCOUNTHOOK | MUTT_REPLYHOOK | MUTT_CRYPTHOOK))
      {
	/* these hooks allow multiple commands with the same
	 * pattern, so if we've already seen this pattern/command pair, just
	 * ignore it instead of creating a duplicate */
	if (!mutt_strcmp (ptr->command, command.data))
	{
	  FREE (&command.data);
	  FREE (&pattern.data);
	  return 0;
	}
      }
      else
      {
	/* other hooks only allow one command per pattern, so update the
	 * entry with the new command.  this currently does not change the
	 * order of execution of the hooks, which i think is desirable since
	 * a common action to perform is to change the default (.) entry
	 * based upon some other information. */
	FREE (&ptr->command);
	ptr->command = command.data;
	FREE (&pattern.data);
	return 0;
      }
    }
    if (!ptr->next)
      break;
  }

  if (data & (MUTT_SENDHOOK | MUTT_SEND2HOOK | MUTT_SAVEHOOK | MUTT_FCCHOOK | MUTT_MESSAGEHOOK | MUTT_REPLYHOOK))
  {
    if ((pat = mutt_pattern_comp (pattern.data,
	   (data & (MUTT_SENDHOOK | MUTT_SEND2HOOK | MUTT_FCCHOOK)) ? 0 : MUTT_FULL_MSG,
				  err)) == NULL)
      goto error;
  }
  else
  {
    /* Hooks not allowing full patterns: Check syntax of regexp */
    rx = safe_malloc (sizeof (regex_t));
#ifdef MUTT_CRYPTHOOK
    if ((rc = REGCOMP (rx, NONULL(pattern.data), ((data & (MUTT_CRYPTHOOK|MUTT_CHARSETHOOK|MUTT_ICONVHOOK)) ? REG_ICASE : 0))) != 0)
#else
    if ((rc = REGCOMP (rx, NONULL(pattern.data), (data & (MUTT_CHARSETHOOK|MUTT_ICONVHOOK)) ? REG_ICASE : 0)) != 0)
#endif /* MUTT_CRYPTHOOK */
    {
      regerror (rc, rx, err->data, err->dsize);
      FREE (&rx);
      goto error;
    }
  }

  if (ptr)
  {
    ptr->next = safe_calloc (1, sizeof (HOOK));
    ptr = ptr->next;
  }
  else
    Hooks = ptr = safe_calloc (1, sizeof (HOOK));
  ptr->type = data;
  ptr->command = command.data;
  ptr->pattern = pat;
  ptr->rx.pattern = pattern.data;
  ptr->rx.rx = rx;
  ptr->rx.not = not;
  return 0;

error:
  FREE (&pattern.data);
  FREE (&command.data);
  return (-1);
}
Пример #9
0
static void DocWndConvertText(char *in, int in_size, char *out, int out_size)
{
	char *buffer = (char *)safe_malloc(sizeof(char)*out_size);
	int buffer_size = out_size;
	int i=0, j=0;
	int nl = 0;

// Convert Return Code CR, LF -> CR+LF ,
//         Control Code -> ^? (^@, ^A, ^B, ...).
// stage1:
	for(;;){
		if(i>=in_size || j>=buffer_size-1)
			goto stage1_end;
		if(nl==13){
			if(in[i]==13){
				if(j>=buffer_size-2)
					goto stage1_end;
				buffer[j++] = 13;
				buffer[j++] = 10;
				i++;
				nl = 13;
				continue;
			}
			if(in[i]==10){
				if(j>=buffer_size-2)
					goto stage1_end;
				buffer[j++] = 13;
				buffer[j++] = 10;
				i++;
				nl = 0;
				continue;
			}
			if(j>=buffer_size-2)
				goto stage1_end;
			buffer[j++] = 13;
			buffer[j++] = 10;
			if(in[i]>=0 && in[i]<=0x1f && in[i]!='\t'){
				if(j>=buffer_size-2)
					goto stage1_end;
				buffer[j++] = '^';
				buffer[j++] = ControlCode[in[i]];
			} else {
				if(j>=buffer_size-1)
					goto stage1_end;
				buffer[j++] = in[i];
			}
			i++;
			nl = 0;
			continue;
		}
		if(nl==10){
			if(in[i]==13||in[i]==10){
				if(j>=buffer_size-2)
					goto stage1_end;
				buffer[j++] = 13;
				buffer[j++] = 10;
				nl = in[i];
				i++;
				continue;
			}
			if(j>=buffer_size-2)
				goto stage1_end;
			buffer[j++] = 13;
			buffer[j++] = 10;
			if(in[i]>=0 && in[i]<=0x1f && in[i]!='\t'){
				if(j>=buffer_size-2)
					goto stage1_end;
				buffer[j++] = '^';
				buffer[j++] = ControlCode[in[i]];
			} else {
				if(j>=buffer_size-1)
					goto stage1_end;
				buffer[j++] = in[i];
			}
			i++;
			nl = 0;
			continue;
		}
		if(in[i]==13||in[i]==10){
			nl = in[i];
			i++;
			continue;
		}
		if(in[i]>=0 && in[i]<=0x1f && in[i]!='\t'){
			if(j>=buffer_size-2)
				goto stage1_end;
			buffer[j++] = '^';
			buffer[j++] = ControlCode[in[i]];
		} else {
			if(j>=buffer_size-1)
				goto stage1_end;
			buffer[j++] = in[i];
		}
		i++;
		nl = 0;
		continue;
	}
stage1_end:
	buffer[j] = '\0';
// Convert KANJI Code.
// stage2:
#ifndef MAX2
#define MAX2(x,y) ((x)>=(y)?(x):(y))
#endif
	switch(PlayerLanguage){
  	case LANGUAGE_ENGLISH:
 	default:
		strncpy(out,buffer,MAX2(buffer_size-1,out_size-1));
		out[out_size-1] = '\0';
		break;
	case LANGUAGE_JAPANESE:
		strncpy(out,buffer,MAX2(buffer_size-1,out_size-1));
		nkf_convert(buffer,out,out_size-1,NULL,"SJIS");
		out[out_size-1] = '\0';
		break;
	}
}
Пример #10
0
/*
 * Called for each dataset.  If the object is of an appropriate type,
 * add it to the avl tree and recurse over any children as necessary.
 */
static int
zfs_callback(zfs_handle_t *zhp, void *data)
{
	callback_data_t *cb = data;
	boolean_t should_close = B_TRUE;
	boolean_t include_snaps = zfs_include_snapshots(zhp, cb);
	boolean_t include_bmarks = (cb->cb_types & ZFS_TYPE_BOOKMARK);

	if ((zfs_get_type(zhp) & cb->cb_types) ||
	    ((zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) && include_snaps)) {
		uu_avl_index_t idx;
		zfs_node_t *node = safe_malloc(sizeof (zfs_node_t));

		node->zn_handle = zhp;
		uu_avl_node_init(node, &node->zn_avlnode, avl_pool);
		if (uu_avl_find(cb->cb_avl, node, cb->cb_sortcol,
		    &idx) == NULL) {
			if (cb->cb_proplist) {
				if ((*cb->cb_proplist) &&
				    !(*cb->cb_proplist)->pl_all)
					zfs_prune_proplist(zhp,
					    cb->cb_props_table);

				if (zfs_expand_proplist(zhp, cb->cb_proplist,
				    (cb->cb_flags & ZFS_ITER_RECVD_PROPS),
				    (cb->cb_flags & ZFS_ITER_LITERAL_PROPS))
				    != 0) {
					free(node);
					return (-1);
				}
			}
			uu_avl_insert(cb->cb_avl, node, idx);
			should_close = B_FALSE;
		} else {
			free(node);
		}
	}

	/*
	 * Recurse if necessary.
	 */
	if (cb->cb_flags & ZFS_ITER_RECURSE &&
	    ((cb->cb_flags & ZFS_ITER_DEPTH_LIMIT) == 0 ||
	    cb->cb_depth < cb->cb_depth_limit)) {
		cb->cb_depth++;

		/*
		 * If we are not looking for filesystems, we don't need to
		 * recurse into filesystems when we are at our depth limit.
		 */
		if ((cb->cb_depth < cb->cb_depth_limit ||
		    (cb->cb_flags & ZFS_ITER_DEPTH_LIMIT) == 0 ||
		    (cb->cb_types &
		    (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME))) &&
		    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
			(void) zfs_iter_filesystems(zhp, zfs_callback, data);
		}

		if (((zfs_get_type(zhp) & (ZFS_TYPE_SNAPSHOT |
		    ZFS_TYPE_BOOKMARK)) == 0) && include_snaps) {
			(void) zfs_iter_snapshots(zhp,
			    (cb->cb_flags & ZFS_ITER_SIMPLE) != 0,
			    zfs_callback, data, 0, 0);
		}

		if (((zfs_get_type(zhp) & (ZFS_TYPE_SNAPSHOT |
		    ZFS_TYPE_BOOKMARK)) == 0) && include_bmarks) {
			(void) zfs_iter_bookmarks(zhp, zfs_callback, data);
		}

		cb->cb_depth--;
	}

	if (should_close)
		zfs_close(zhp);

	return (0);
}
Пример #11
0
int main(int argc, char *argv[])
{
  /* Define the options specific to the DNS protocol. */
  struct option long_options[] =
  {
    {"host", required_argument, 0, 0},
    {"port", required_argument, 0, 0},
    {0,      0,                 0, 0}  /* End */
  };
  char        c;
  int         option_index;
  const char *option_name;

  options        = safe_malloc(sizeof(options_t));

  srand(time(NULL));

  /* Set up some default options. */
  options->s               = -1;

  options->host    = DEFAULT_HOST;
  options->port    = DEFAULT_PORT;
  options->buffer  = buffer_create(BO_BIG_ENDIAN);
  options->group   = select_group_create();
  options->session = session_create(options->group, tcpcat_send, options, 65535);

  /* Parse the command line options. */
  opterr = 0;
  while((c = getopt_long_only(argc, argv, "", long_options, &option_index)) != EOF)
  {
    switch(c)
    {
      case 0:
        option_name = long_options[option_index].name;

        if(!strcmp(option_name, "host"))
        {
          options->host = optarg;
        }
        else if(!strcmp(option_name, "port"))
        {
          options->port = atoi(optarg);
        }
        else
        {
          LOG_FATAL("Unknown option: %s\n", option_name);
          exit(1);
          /* TODO: Usage */
        }
        break;

      case '?':
      default:
        /* Do nothing; we expect some unknown arguments. */
        break;
    }
  }

  /* Tell the user what's going on */
  LOG_INFO("Host: %s\n", options->host);
  LOG_INFO("Port: %d\n", options->port);

  atexit(cleanup);

  /* Add the timeout function */
  select_set_timeout(options->group, timeout, (void*)options);

  while(TRUE)
    select_group_do_select(options->group, 1000);

  return 0;
}
Пример #12
0
static ADDRESS *mutt_expand_aliases_r (ADDRESS *a, LIST **expn)
{
  ADDRESS *head = NULL, *last = NULL, *t, *w;
  LIST *u;
  char i;
  const char *fqdn;
  
  while (a)
  {
    if (!a->group && !a->personal && a->mailbox && strchr (a->mailbox, '@') == NULL)
    {
      t = mutt_lookup_alias (a->mailbox);

      if (t)
      {	
        i = 0;
        for (u = *expn; u; u = u->next)
	{
	  if (mutt_strcmp (a->mailbox, u->data) == 0) /* alias already found */
	  {
	    dprint (1, (debugfile, "mutt_expand_aliases_r(): loop in alias found for '%s'\n", a->mailbox));
	    i = 1;
	    break;
	  }
	}

        if (!i)
	{
          u = safe_malloc (sizeof (LIST));
          u->data = safe_strdup (a->mailbox);
          u->next = *expn;
          *expn = u;
	  w = rfc822_cpy_adr (t, 0);
	  w = mutt_expand_aliases_r (w, expn);
	  if (head)
	    last->next = w;
	  else
	    head = last = w;
	  while (last && last->next)
	    last = last->next;
        }
	t = a;
	a = a->next;
	t->next = NULL;
	rfc822_free_address (&t);
	continue;
      }
      else
      {
	struct passwd *pw = getpwnam (a->mailbox);

	if (pw)
	{
	  char namebuf[STRING];
	  
	  mutt_gecos_name (namebuf, sizeof (namebuf), pw);
	  mutt_str_replace (&a->personal, namebuf);
	  
#ifdef EXACT_ADDRESS
	  FREE (&a->val);
#endif
	}
      }
    }

    if (head)
    {
      last->next = a;
      last = last->next;
    }
    else
      head = last = a;
    a = a->next;
    last->next = NULL;
  }

  if (option (OPTUSEDOMAIN) && (fqdn = mutt_fqdn(1)))
  {
    /* now qualify all local addresses */
    rfc822_qualify (head, fqdn);
  }

  return (head);
}
Пример #13
0
rec_element*
initialize_rec_element(rec_element* re,
		       char type,
		       u_int size,
		       void* trans,
		       rec_confidence conf)
{
    if( re != NULL ) {

	re->re_type = type;
	re->re_conf = conf;
	re->re_result.aval = NULL;
	
	switch (type) {
	    
	  case REC_GESTURE:
	    if( size > 0 && trans != NULL ) {
		re->re_result.gval = 
		     (gesture*)safe_malloc(sizeof(gesture));
		memcpy((void*)re->re_result.gval,trans,sizeof(gesture));
	    }
	    break;
	    
	  case REC_ASCII:
	  case REC_VAR:
	  case REC_OTHER:
	    if( size > 0 && trans != NULL ) {
		re->re_result.aval = 
		     (char*)safe_malloc((size+1)*sizeof(char));
		memcpy((void*)re->re_result.aval,trans,size*sizeof(char));
		re->re_result.aval[size] = '\000';
	    }
	    break;
	    
	  case REC_WCHAR:
	    if( size > 0 && trans != NULL ) {
		re->re_result.wval = 
		     (wchar_t*)safe_malloc((size+1)*sizeof(wchar_t));
		memcpy((void*)re->re_result.wval,trans,size*sizeof(wchar_t));
		re->re_result.wval[size] = '\000';
	    }
	    break;
	    
	  case REC_CORR:
	    if( size > 0 && trans != NULL ) {
	      re->re_result.rcval =
		   (rec_correlation*)safe_malloc(sizeof(rec_correlation));
	      memcpy((void*)re->re_result.rcval,
		     trans,
		     sizeof(rec_correlation));
	    }
	    break;

	  default:
	    return(NULL);
	}

    }

    return(re);
}
Пример #14
0
static rec_info* make_rec_info(char* directory,char* name,char** subset)
{
    int i,len;
    rec_info* ri;
    char* locale;

    ri = (rec_info*)safe_malloc(sizeof(rec_info));
    ri->ri_locale = NULL;
    ri->ri_name = NULL;
    ri->ri_subset = NULL;

    /*Get locale*/

    if( (locale = getenv(LANG)) == NULL ) {
	locale = strdup(REC_DEFAULT_LOCALE);
    }

    if( (ri->ri_locale = strdup(locale)) == NULL ) {
	delete_rec_info(ri);
	return(NULL);
    }

    /*Get shared library pathname.*/

/*
 *    if( (ri->ri_name = shared_library_name(directory,locale,name)) == NULL ) {
 *	delete_rec_info(ri);
 *	return(NULL);
 *    }
 */

    /*Initialize the subset information.*/

    if( subset != NULL ) {
	
	/*Count the subset strings.*/

	for( len = 1; subset[len] != NULL; len++ ) ;
	
	/*Copy the subset strings.*/
	
	ri->ri_subset = (char**)safe_malloc((len +1)*sizeof(char*));
	
	for( i = 0; i < len; i++ ) {
	    if( subset[i] != NULL ) {
		if( (ri->ri_subset[i] = strdup(subset[i])) == NULL ) {
		    delete_rec_info(ri);
		    return(NULL);
		}
	    } else {
		ri->ri_subset[i] = subset[i];
	    }
	}

	ri->ri_subset[i] = NULL;

    } else {

	ri->ri_subset = NULL;
    }
    
    return(ri);
}
Пример #15
0
struct irec *find_all_interfaces(struct iname *names,
				 struct iname *addrs,
				 int port)
{

  /* this code is adapted from Stevens, page 434. It finally
     destroyed my faith in the C/unix API */
  int len = 100 * sizeof(struct ifreq);
  int lastlen = 0;
  char *buf, *ptr;
  struct ifconf ifc;
  struct irec *ret = NULL;
  int fd = socket(PF_INET, SOCK_DGRAM, 0);
  
  if (fd == -1)
    die("cannot create socket to enumerate interfaces: %s", NULL);
        
  while (1)
    {
      buf = safe_malloc(len);
      ifc.ifc_len = len;
      ifc.ifc_buf = buf;
      if (ioctl(fd, SIOCGIFCONF, &ifc) < 0)
	{
	  if (errno != EINVAL || lastlen != 0)
	    die("ioctl error while enumerating interfaces: %s", NULL);
	}
      else
	{
	  if (ifc.ifc_len == lastlen)
	    break; /* got a big enough buffer now */
	  lastlen = ifc.ifc_len;
	}
      len += 10* sizeof(struct ifreq);
      safe_free(buf);
    }

  for (ptr = buf; ptr < buf + ifc.ifc_len; )
    {
      struct ifreq *ifr = (struct ifreq *) ptr;
      union mysockaddr addr;
#ifdef HAVE_SOCKADDR_SA_LEN
      ptr += ifr->ifr_addr.sa_len + IF_NAMESIZE;
#else
      ptr += sizeof(struct ifreq);
#endif

      /* copy address since getting flags overwrites */
      if (ifr->ifr_addr.sa_family == AF_INET)
	{
	  addr.in = *((struct sockaddr_in *) &ifr->ifr_addr);
	  addr.in.sin_port = htons(port);
	  
	  if (ioctl(fd, SIOCGIFFLAGS, ifr) < 0)
	    die ("ioctl error getting interface flags: %s", NULL);
	      	  
	  ret = add_iface(ret, ifr->ifr_flags, ifr->ifr_name, &addr, 
			  names, addrs);
	}
#ifdef HAVE_IPV6
      else if (ifr->ifr_addr.sa_family == AF_INET6)
	{
#ifdef HAVE_BROKEN_SOCKADDR_IN6
	  addr.in6 = *((struct my_sockaddr_in6 *) &ifr->ifr_addr);
#else
	  addr.in6 = *((struct sockaddr_in6 *) &ifr->ifr_addr);
#endif
	  addr.in6.sin6_port = htons(port);
	  addr.in6.sin6_flowinfo = htonl(0);
	  
	  if (ioctl(fd, SIOCGIFFLAGS, ifr) < 0)
	    die("ioctl error getting interface flags: %s", NULL);
	    	  
	  ret = add_iface(ret, ifr->ifr_flags, ifr->ifr_name, &addr, 
			      names, addrs);
	}
#endif /* IPV6 */
	
    }
  safe_free(buf);
  close(fd);
  
#if defined(HAVE_LINUX_IPV6_PROC) && defined(HAVE_IPV6)
  /* IPv6 addresses don't seem to work with SIOCGIFCONF. Barf */
  /* This code snarfed from net-tools 1.60 and certainly linux specific, though
     it shouldn't break on other Unices, and their SIOGIFCONF might work. */
  {
    FILE *f = fopen(IP6INTERFACES, "r");
    
    if (f)
      {
	union mysockaddr addr;
	unsigned int plen, scope, flags, if_idx;
	char devname[20], addrstring[32];
	
	while (fscanf(f, "%32s %02x %02x %02x %02x %20s\n",
		      addrstring, &if_idx, &plen, &scope, &flags, devname) != EOF) 
	  {
	    int i;
	    unsigned char *addr6p = (unsigned char *) &addr.in6.sin6_addr;
	    memset(&addr, 0, sizeof(addr));
	    addr.sa.sa_family = AF_INET6;
	    for (i=0; i<16; i++)
	      {
		unsigned int byte;
		sscanf(addrstring+i+i, "%02x", &byte);
		addr6p[i] = byte;
	      }
#ifdef HAVE_SOCKADDR_SA_LEN 
	    /* For completeness - should never be defined on Linux. */
	    addr.in6.sin6_len = sizeof(struct sockaddr_in6);
#endif
	    addr.in6.sin6_port = htons(port);
	    addr.in6.sin6_flowinfo = htonl(0);
	    addr.in6.sin6_scope_id = htonl(scope);
	    
	    ret = add_iface(ret, flags, devname, &addr, names, addrs);
	  }
	
	fclose(f);
      }
  }
#endif /* LINUX */

  /* if a whitelist provided, make sure the if names on it were OK */
  while(names)
    {
      if (!names->found)
	die("unknown interface %s", names->name);
      
      names = names->next;
    }
	
  while(addrs)
    {
      if (!addrs->found)
	{
#ifdef HAVE_IPV6
	  char addrbuff[INET6_ADDRSTRLEN];
#else
	  char addrbuff[INET_ADDRSTRLEN];
#endif
	  if (addrs->addr.sa.sa_family == AF_INET)
	    inet_ntop(AF_INET, &addrs->addr.in.sin_addr,
		      addrbuff, INET_ADDRSTRLEN);
#ifdef HAVE_IPV6
	  else
	    inet_ntop(AF_INET6, &addrs->addr.in6.sin6_addr,
		      addrbuff, INET6_ADDRSTRLEN);
#endif
	  die("no interface with address %s", addrbuff);
	}
      addrs = addrs->next;
    }
    
  return ret;
}
Пример #16
0
void save_high_res_screen_image ( void )
{
	char
		filename[100],
		image_filename[100];

	int
		x,
		y,
		x_repeat,
		y_repeat,
		screen_width,
		screen_height,
		screen_pitch;

	unsigned short int
		*huge_screen_shot_memory;

	unsigned char
		*screen_data;

	x_repeat = 8;

	y_repeat = 8;

	screen_width = get_screen_width ( video_screen );

	screen_height = get_screen_height ( video_screen );

	huge_screen_shot_memory = ( unsigned short int * ) safe_malloc ( sizeof ( unsigned short int ) * screen_width * screen_height * x_repeat * y_repeat );

	for ( y = 0; y < y_repeat; y++ )
	{

		for ( x = 0; x < x_repeat; x++ )
		{

			unsigned short int
				*destination_ptr,
				*screen_line;

			int
				screen_y;

			//
			// Render the big views
			//

			draw_application_highres_screen ( x, y, x_repeat, y_repeat );

			if ( lock_screen ( video_screen ) )
			{
	
				screen_data = get_screen_data ( video_screen );
	
				screen_pitch = get_screen_pitch ( video_screen );
	
				destination_ptr = huge_screen_shot_memory + ( y * x_repeat * screen_width * screen_height ) + ( x * screen_width );
	
				for ( screen_y = 0; screen_y < screen_height; screen_y++ )
				{
	
					screen_line = ( unsigned short int * ) ( screen_data + ( screen_y * screen_pitch ) );
	
					memcpy ( destination_ptr, screen_line, screen_width * sizeof ( unsigned short int ) );
	
					destination_ptr += x_repeat * screen_width;
				}
	
				unlock_screen ( video_screen );
			}
		}
	}

	//
	// find first screen shot index
	//

	if (!found_first_screen_shot_index)
	{
		while (TRUE)
		{
			sprintf (image_filename, "%sIMAGE%03d.PSD", LARGE_IMAGE_PATH, screen_shot_index);

			if (file_exist (image_filename))
			{
				screen_shot_index++;

				if (screen_shot_index == 1000)
				{
					break;
				}
			}
			else
			{
				found_first_screen_shot_index = TRUE;

				break;
			}
		}
	}

	//
	// write screen files and viewpoint data file
	//

	if (screen_shot_index <= MAX_SCREEN_SHOT_INDEX)
	{
		sprintf (filename, "IMAGE%03d", screen_shot_index);

		debug_log ("Saving screen image (%s)", filename);

		sprintf (image_filename, "%s%s.PSD", LARGE_IMAGE_PATH, filename);

		write_psd_screen_file ( image_filename,
												screen_width * x_repeat,
												screen_height * y_repeat,
												screen_width * x_repeat * sizeof ( unsigned short int ),
												( unsigned char * ) huge_screen_shot_memory );

		screen_shot_index++;
	}
	else
	{
		debug_colour_log (DEBUG_COLOUR_RED, "Exceeded screen image limit");
	}

	safe_free ( huge_screen_shot_memory );
}
Пример #17
0
void xskin_start_interface( int pipe_in ) {

  int xskin_sc;
  XEvent xskin_e;
  XSetWindowAttributes xskin_attr;

  XSizeHints xskin_hint;
  XClassHint xskin_chint;
  XTextProperty ct;
  char *namlist[2];


  /* setup window */

  xskin_d     = XOpenDisplay( NULL );
  xskin_sc    = DefaultScreen( xskin_d );
  xskin_r     = RootWindow( xskin_d, xskin_sc );
  xskin_gc    = DefaultGC( xskin_d, xskin_sc );
  xskin_vis   = DefaultVisual( xskin_d, xskin_sc );
  xskin_depth = DefaultDepth( xskin_d, xskin_sc );

  xskin_w = XCreateSimpleWindow( xskin_d, xskin_r, 0, 0,
				 skin_width, skin_height, 0,
				 WhitePixel( xskin_d, xskin_sc ),
				 BlackPixel( xskin_d, xskin_sc ) );

  xskin_attr.backing_store = True;
  xskin_attr.override_redirect = False;
  XChangeWindowAttributes( xskin_d, xskin_w,
			   CWBackingStore|CWOverrideRedirect, &xskin_attr );

  XSelectInput( xskin_d, xskin_w,
		KeyPressMask|ExposureMask|
		EnterWindowMask|LeaveWindowMask|
		ButtonPressMask|ButtonReleaseMask|
		Button1MotionMask );

  xskin_hint.flags = USSize | PMinSize | PMaxSize | USPosition;
  xskin_hint.width = xskin_hint.min_width = xskin_hint.max_width
    = skin_width;
  xskin_hint.height = xskin_hint.min_height = xskin_hint.max_height
    = skin_height;
  XSetNormalHints( xskin_d, xskin_w, &xskin_hint );

  xskin_chint.res_name  = XSKIN_RES_NAME;
  xskin_chint.res_class = XSKIN_RES_CLASS;
  XSetClassHint( xskin_d, xskin_w, &xskin_chint );

  namlist[0]=(char *)safe_malloc(strlen(XSKIN_WINDOW_NAME)+1);
  strcpy( namlist[0], XSKIN_WINDOW_NAME );
  XmbTextListToTextProperty( xskin_d, namlist, 1, XCompoundTextStyle, &ct );
  XSetWMName( xskin_d, xskin_w, &ct );
  XSetWMIconName( xskin_d, xskin_w, &ct );
  free(namlist[0]);


  /* setup pixmaps */

  if ( load_skins()!=0 ) goto finish;

  XSetWindowBackgroundPixmap( xskin_d, xskin_w, xskin_back );
  XClearWindow( xskin_d, xskin_w );

  XMapWindow( xskin_d, xskin_w );
  while( 1 ) {
    XNextEvent( xskin_d, &xskin_e );
    if ( xskin_e.type == Expose ) break; 
  }

  fshuf=0;
  frep=0;
  fequ=1;
  fpll=1;
  fplay=0;
  fpause=0;
  fremain=0;
  play_val=1;
  vol_val=50;
  last_current_time=0;
  total_time=0;
  speana_buf = NULL;
  strcpy( last_text, "welcome to timidity" );

  install_sighandler();

  repaint();
  ts_spectrum( -1, speana_buf );

  XFlush(xskin_d);

  xskin_jobs( pipe_in );   /* tskin main jobs */

finish:
  signal_vector(0);  /* finish */
}
Пример #18
0
/*
 * aazip - compress files using a transform based compression system
 */
int main(int argc, char** argv)
{
    FILE* f;
    bit_file_t* of;
    char* infile,*outfile;
    uint8_t* input,*lupdate,*bwt,lumode;
    int32_t I,osize,opt;
    uint32_t size;
    mode_t lupdate_alg;
    float ient,oent;
    uint64_t cost,tstart,tstop,elapsed;

    /* parse command line parameter */
    opt = GETOPT_FINISHED;
    if (argc <= 1) {
        print_usage(argv[0]);
        exit(EXIT_FAILURE);
    }
    while ((opt = getopt(argc, argv, "m:h")) != GETOPT_FINISHED) {
        switch (opt) {
            case 'm':
                if (strcmp(optarg, "simple") == 0) lupdate_alg = SIMPLE;
                else if (strcmp(optarg, "mtf") == 0) lupdate_alg = MTF;
                else if (strcmp(optarg, "fc") == 0) lupdate_alg = FC;
                else if (strcmp(optarg, "wfc") == 0) lupdate_alg = WFC;
                else if (strcmp(optarg, "timestamp") == 0) lupdate_alg = TS;
                else fatal("ERROR: mode <%s> unknown!\n", optarg);
                break;
            case 'h':
            default:
                print_usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }
    /* read input file name */
    if (optind < argc) infile = argv[optind];
    else {
        print_usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    /* read input file */
    f = safe_fopen(infile,"r");
    size = safe_filesize(f);
    input = (uint8_t*) safe_malloc(size+1);
    if (fread(input,1,size,f)!=(size_t)size) {
        fatal("read input file.");
    }
    safe_fclose(f);
    input[size] = 0;

    /* TODO calculate input entropy */
    ient = 0.0f;

    /* perform bwt */
    bwt = (uint8_t*) safe_malloc(size);

    tstart = gettime();

    bwt = transform_bwt(input,size,bwt,&I);

    /* peform list update */
    switch (lupdate_alg) {
        case SIMPLE:
            fprintf(stdout,"ALGORITHM: simple\n");
            lupdate = lupdate_simple(bwt,size,input,&cost);
            break;
        case MTF:
            fprintf(stdout,"ALGORITHM: move to front\n");
            lupdate = lupdate_movetofront(bwt,size,input,&cost);
            break;
        case FC:
            fprintf(stdout,"ALGORITHM: frequency count\n");
            lupdate = lupdate_freqcount(bwt,size,input,&cost);
            break;
        case WFC:
            fprintf(stdout,"ALGORITHM: weighted frequency count\n");
            lupdate = lupdate_wfc(bwt,size,input,&cost);
            break;
        case TS:
            fprintf(stdout,"ALGORITHM: timestamp\n");
            lupdate = lupdate_timestamp(bwt,size,input,&cost);
            break;
        default:
            fatal("unkown list update algorithm.");
    }

    fprintf(stdout,"INPUT: %s (%d bytes)\n",infile,size);
    fprintf(stdout,"COST: %lu\n",cost);

    /* TODO calculate entropy after list update*/
    oent = 0.0f;

    /* write output */
    outfile = safe_strcat(infile,".aazip");
    /* create bit file for writing */
    of = BitFileOpen(outfile, BF_WRITE);

    /* write aa zip header */
    BitFilePutChar('A', of);
    BitFilePutChar('A', of);

    /* write I */
    BitFilePutBitsInt(of,&I,32,sizeof(uint32_t));

    /* write lupdate mode */
    lumode = lupdate_alg;
    BitFilePutBitsInt(of,&lumode,8,sizeof(uint8_t));


    fprintf(stderr,"I %d lumode %d\n",I,lumode);

    /* perform huffman coding */
    encode_huffman(lupdate,size,of);

    tstop = gettime();

    elapsed = tstop - tstart;
    fprintf(stdout,"TIME: %.3f s\n",(float)elapsed/1000000);

    /* flush and get file stats */
    BitFileFlushOutput(of,0);
    f = BitFileToFILE(of);
    osize = ftell(f);

    fprintf(stdout,"OUTPUT: %s\n",outfile);
    fprintf(stdout,"ENTROPY: %.2f bps / %.2f bps\n",ient,oent);
    fprintf(stdout,"COMPRESSION: %.2f\n",((float)osize/(float)size)*100);

    /* clean up*/
    safe_fclose(f);
    free(input);
    free(bwt);

    return (EXIT_SUCCESS);
}
Пример #19
0
int
setup_sched(struct tcp_sched* sched) {

    in_addr sip, dip;  /* Source & Destination IP */
    in_addr local_ip, remote_ip;	/* ip address of client and server*/
    /*temporary packet buffers*/
    struct pcap_pkthdr header; 	// The header that pcap gives us
    const u_char *packet; 		// The actual packet
    pcap_t *local_handle;
    unsigned int pkt_counter=0;
    ether_hdr *etherhdr = NULL;
    tcp_hdr *tcphdr = NULL;
    ipv4_hdr *iphdr = NULL;
    local_ip.byte1=0;
    local_ip.byte2=0;
    local_ip.byte3=0;
    local_ip.byte4=0;

    remote_ip.byte1=0;
    remote_ip.byte2=0;
    remote_ip.byte3=0;
    remote_ip.byte4=0;

    unsigned int size_ip, i = 0;
    unsigned int size_tcp;
    unsigned int size_payload;
    char errbuf[PCAP_ERRBUF_SIZE];
    unsigned int flags=0;
    bool remote = false; 	/* flags to test if data is from 'cleint'=local or 'server'=remote */
    bool local = false;


    local_handle = pcap_open_offline("newfile.pcap", errbuf);   /*call pcap library function*/

    if (local_handle == NULL) {
        fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf);
        return(2);
    }

    /*Before sending any packet, setup the schedule with the proper parameters*/
    while((packet = pcap_next(local_handle,&header))) {
        pkt_counter++; /*increment number of packets seen*/

        memcpy(&sched[i].pkthdr, &header, sizeof(struct pcap_pkthdr));
        //sched[i].len = header.len;
        //sched[i].caplen = header.caplen;
        sched[i].packet_ptr = safe_malloc(sched[i].pkthdr.len);
        memcpy(sched[i].packet_ptr, packet, sched[i].pkthdr.len);

        /* extract necessary data */
        etherhdr = (ether_hdr*)(sched[i].packet_ptr);
        iphdr = (ipv4_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET);
        size_ip = iphdr->ip_hl << 2;
        if (size_ip < 20) {
            printf("ERROR: Invalid IP header length: %u bytes\n", size_ip);
            return 0;
        }
        tcphdr = (tcp_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip);
        size_tcp = tcphdr->th_off*4;
        if (size_tcp < 20) {
            printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp);
            return 0;
        }
        /* payload = (u_char *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip + size_tcp); */
        size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp));


        /* Source IP and Destination IP */
        sip = iphdr->ip_src;
        dip = iphdr->ip_dst;

        flags = tcphdr->th_flags;

        if (flags == TH_SYN) {	/* set IPs who's local and who's remote based on the SYN flag */
            local_ip = sip;
            remote_ip = dip;
        }

        /*Compare IPs to see which packet is this comming from*/
        if(compip(&local_ip, &remote_ip, &sip)==LOCAL_IP_MATCH) {
            local = true;
            remote = false;
        }
        if(compip(&local_ip, &remote_ip, &sip)==REMOTE_IP_MATCH) {
            local = false;
            remote = true;
        }

        /* Setup rest of Schedule, parameter by parameter */
        /* Refer to header file for details on each of the parameters */

        sched[i].etherhdr = etherhdr;
        sched[i].iphdr = iphdr;
        sched[i].tcphdr = tcphdr;
        sched[i].size_ip = size_ip;
        sched[i].size_tcp = size_tcp;
        sched[i].size_payload = size_payload;
        sched[i].sent_counter = 0;

        /* Do the following only for the first packet (SYN)*/
        if(i==0) {
            sched[i].length_last_ldata = 0;
            sched[i].length_curr_ldata = 0;
            sched[i].length_last_rdata = 0;
            sched[i].length_curr_rdata = 0;
            sched[i].local = true;
            sched[i].remote = false;
            sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq);
            sched[i].curr_lack = 0;
            sched[i].exp_rseq = 0; 	/* Keep track of previous remote seq & ack #s*/
            sched[i].exp_rack = 0;

        }

        /* Local Packet operations */
        else if(local) {
            sched[i].length_last_ldata = sched[i-1].length_curr_ldata;
            sched[i].length_curr_ldata = size_payload;
            sched[i].length_last_rdata = sched[i-1].length_curr_rdata;
            sched[i].length_curr_rdata = 0;
            sched[i].local = true;
            sched[i].remote = false;
            sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq);
            sched[i].curr_lack = ntohl(sched[i].tcphdr->th_ack);
            sched[i].exp_rseq = sched[i-1].exp_rseq; 	/* Keep track of previous remote seq & ack #s*/
            sched[i].exp_rack = sched[i-1].exp_rack;

        }

        /* Remote Packet operations */
        else if(remote) {
            sched[i].length_last_ldata = sched[i-1].length_curr_ldata;
            sched[i].length_curr_ldata = 0;
            sched[i].length_last_rdata = sched[i-1].length_curr_rdata;
            sched[i].length_curr_rdata = size_payload;
            sched[i].local = false;
            sched[i].remote = true;
            sched[i].curr_lseq = sched[i-1].curr_lseq;
            sched[i].curr_lack = sched[i-1].curr_lack;
            sched[i].exp_rseq = ntohl(sched[i].tcphdr->th_seq); 	/* Keep track of previous remote seq & ack #s*/
            sched[i].exp_rack = ntohl(sched[i].tcphdr->th_ack);
            /* Setup global variable where remote FIN-ACK exists*/
            if(flags == (TH_FIN|TH_ACK)) finack_rindex = i;
            //printf("REMOTE --------%d\n",i+1);
        }


        i++; /* increment schedule index */

    } /*end internal loop for reading packets (all in one file)*/

    pcap_close(local_handle);  /*close the pcap file*/

    return pkt_counter; /* Return number of packets scheduled */
}
Пример #20
0
void dhcp_init(struct daemon *daemon)
{
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  struct sockaddr_in saddr;
  int oneopt = 1;
  struct dhcp_config *configs, *cp;

  if (fd == -1)
    die (_("cannot create DHCP socket : %s"), NULL);
  
  if (!fix_fd(fd) || 
#if defined(HAVE_LINUX_NETWORK)
      setsockopt(fd, SOL_IP, IP_PKTINFO, &oneopt, sizeof(oneopt)) == -1 ||
#elif defined(IP_RECVIF)
      setsockopt(fd, IPPROTO_IP, IP_RECVIF, &oneopt, sizeof(oneopt)) == -1 ||
#endif
      setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &oneopt, sizeof(oneopt)) == -1)  
    die(_("failed to set options on DHCP socket: %s"), NULL);
  
  /* When bind-interfaces is set, there might be more than one dnmsasq
     instance binding port 67. That's OK if they serve different networks.
     Need to set REUSEADDR to make this posible, or REUSEPORT on *BSD.
     OpenBSD <= 4.0 screws up IP_RECVIF when SO_REUSEPORT is set, but
     OpenBSD <= 3.9 doesn't have IP_RECVIF anyway, so we just have to elide
     this for OpenBSD 4.0, if you want more than one instance on oBSD4.0, tough. */

#ifndef OpenBSD4_0
  if (daemon->options & OPT_NOWILD)
    {
#ifdef SO_REUSEPORT
      int rc = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &oneopt, sizeof(oneopt));
#else
      int rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &oneopt, sizeof(oneopt));
#endif
      if (rc == -1)
	die(_("failed to set SO_REUSE{ADDR|PORT} on DHCP socket: %s"), NULL);
    }
#endif
  
  memset(&saddr, 0, sizeof(saddr));
  saddr.sin_family = AF_INET;
  saddr.sin_port = htons(DHCP_SERVER_PORT);
  saddr.sin_addr.s_addr = INADDR_ANY;
#ifdef HAVE_SOCKADDR_SA_LEN
  saddr.sin_len = sizeof(struct sockaddr_in);
#endif

  if (bind(fd, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in)))
    die(_("failed to bind DHCP server socket: %s"), NULL);

  daemon->dhcpfd = fd;

#ifndef HAVE_LINUX_NETWORK
  /* When we're not using capabilities, we need to do this here before
     we drop root. Also, set buffer size small, to avoid wasting
     kernel buffers */
  
  if (daemon->options & OPT_NO_PING)
    daemon->dhcp_icmp_fd = -1;
  else if ((daemon->dhcp_icmp_fd = make_icmp_sock()) == -1 ||
	   setsockopt(daemon->dhcp_icmp_fd, SOL_SOCKET, SO_RCVBUF, &oneopt, sizeof(oneopt)) == -1 )
    die(_("cannot create ICMP raw socket: %s."), NULL);
  
  /* Make BPF raw send socket */
  init_bpf(daemon);
#endif
  
  /* If the same IP appears in more than one host config, then DISCOVER
     for one of the hosts will get the address, but REQUEST will be NAKed,
     since the address is reserved by the other one -> protocol loop. */
  for (configs = daemon->dhcp_conf; configs; configs = configs->next)
    for (cp = configs->next; cp; cp = cp->next)
      if ((configs->flags & cp->flags & CONFIG_ADDR) &&	configs->addr.s_addr == cp->addr.s_addr)
	die(_("duplicate IP address %s in dhcp-config directive."), inet_ntoa(cp->addr));
  
  daemon->dhcp_packet.iov_len = sizeof(struct dhcp_packet); 
  daemon->dhcp_packet.iov_base = safe_malloc(daemon->dhcp_packet.iov_len);
    /* These two each hold a DHCP option max size 255
     and get a terminating zero added */
  daemon->dhcp_buff = safe_malloc(256);
  daemon->dhcp_buff2 = safe_malloc(256); 
  daemon->ping_results = NULL;
}
Пример #21
0
int ea_getxattr_rcs(const char *path, const char *name, char *value, size_t size)
{
  metadata_t *metadata;
  version_t *version;
  
  rcs_ignore_deleted = 1;
  metadata = rcs_translate_to_metadata(path, rcs_version_path);
  rcs_ignore_deleted = 0;
  if (!metadata)
    return -ENOENT;

  if (!strcmp(name, "rcs.purge"))
    {
      /* This one is write-only */
      return -EPERM;
    }
  else if (!strcmp(name, "rcs.locked_version"))
    {
      char buffer[64];
      int vid, svid;
      
      if (metadata->md_deleted)
      {
        strcpy(buffer, "0.0");
      }
      else
      {
        if (metadata->md_dfl_vid == -1)
          {
            vid = metadata->md_versions->v_vid;
            svid = metadata->md_versions->v_svid;
          }
        else
          {
            vid = metadata->md_dfl_vid;
            svid = metadata->md_dfl_svid;
          }
  
        /* Get the version number */
        snprintf(buffer, 64, "%i.%i", vid, svid);
      }

      /* Handle the EA protocol */
      if (size == 0)
        return strlen(buffer);
      if (strlen(buffer) > size)
        return -ERANGE;
      strcpy(value, buffer);
      return strlen(buffer);
    }
  else if (!strcmp(name, "rcs.metadata_dump"))
    {
      char **array, *result;
      unsigned int count;
      int res;

      /*
       * We need to pass the version metadata to userspace, but we also need
       * to pass the file type and modification type from the stat syscall,
       * since the userspace program may be running as a non-root, and thus
       * can't see the version store.
       */

      for (count = 0, version = metadata->md_versions; version;
        version = version->v_next)
        count++;
      array = safe_malloc(sizeof(char *) * (count + 1));
      memset(array, 0, sizeof(char *) * (count + 1));

      /* Traverse the version list and build the individual strings */
      for (count = 0, version = metadata->md_versions; version;
        version = version->v_next)
        {
          struct stat st_data;
      
          /* stat() the real file, but just ignore failures (bad version ?) */
          if (lstat(version->v_rfile, &st_data) < 0)
            {
              st_data.st_mode = S_IFREG;
              st_data.st_mtime = -1;
            }
          else
            st_data.st_mode &= ~07777;
      
          if (asprintf(&array[count], "%d:%d:%d:%d:%d:%lld:%ld",
            version->v_vid, version->v_svid,
            version->v_mode | st_data.st_mode, version->v_uid,
            version->v_gid, (long long)st_data.st_size, st_data.st_mtime) < 0)
            {
              unsigned int i;
      
              /* Free everything if it failed */
              for (i = 0; i < count; i++)
                free(array[i]);
              free(array);
              return -ENOMEM;
            }
      
          count++;
        }

      /* Build the final string */
      result = helper_build_composite("A", "|", array);
      helper_free_array(array);

      /* Handle the EA protocol */

      if (size == 0)
        res = strlen(result);
      else if (strlen(result) > size)
        res = -ERANGE;
      else
        {
          strcpy(value, result);
          res = strlen(result);
        }
      free(result);
      return res;
    }
  else if (!strcmp(name, "rcs.list_dir"))
    {
      struct dirent *entry;
      int res;
      DIR *dir;
      char *result;
      size_t result_size;
      string_list_t *file_list;
      string_list_t **file_list_ptr;
    
      file_list = NULL;
      file_list_ptr = &file_list;

      rcs_ignore_deleted = 1;
      version = rcs_find_version(metadata, LATEST, LATEST);
      rcs_ignore_deleted = 0;
      
      dir = opendir(version->v_rfile);
      if (!dir)
        {
          return -errno;
        }      
    
      /* Find the metadata files */
      while ((entry = readdir(dir)))
        {
          /*
           * We want the metadata files (because a versioned file is
           * behind them)
           */
          if (!strcmp(entry->d_name, METADATA_PREFIX))
            {
              /* This is the root's metadata, ignore it */
              continue;
            }
          else if (!strncmp(entry->d_name, METADATA_PREFIX,
                strlen(METADATA_PREFIX)))
            {
              char *file;
              metadata_t *file_metadata;
              int len;
      
              if (strcmp(path, "/"))
                file = helper_build_composite("SS", "/", path,
                  entry->d_name + strlen(METADATA_PREFIX));
              else
                file = helper_build_composite("-S", "/", entry->d_name +
                  strlen(METADATA_PREFIX));
              rcs_ignore_deleted = 1;
              file_metadata = rcs_translate_to_metadata(file, rcs_version_path);
              rcs_ignore_deleted = 0;
              free(file);
              if (!file_metadata)
                {
                  closedir(dir);
                  return -ENOENT;
                }
              
              *file_list_ptr = safe_malloc(sizeof(string_list_t));
              memset(*file_list_ptr, 0, sizeof(string_list_t));
              
              if (file_metadata->md_deleted)
                len = asprintf(&(*file_list_ptr)->sl_data, "0:0:0:0:0:0:0:%s",
                  entry->d_name + strlen(METADATA_PREFIX));
              else
                {
                  version_t *file_version;
                  struct stat st_data;
                  
                  file_version = rcs_find_version(file_metadata, LATEST, LATEST);
                  if (!file_version)
                    {
                      helper_free_string_list(file_list);
                      closedir(dir);
                      return -ENOENT;
                    }
                    
                  /* stat() the real file, but just ignore failures (bad version ?) */
                  if (lstat(file_version->v_rfile, &st_data) < 0)
                    {
                      st_data.st_mode = S_IFREG;
                      st_data.st_mtime = -1;
                    }
                  else
                    st_data.st_mode &= ~07777;
          
                  len = asprintf(&(*file_list_ptr)->sl_data, "%d:%d:%d:%d:%d:%lld:%ld:%s",
                    file_version->v_vid, file_version->v_svid,
                    file_version->v_mode | st_data.st_mode, file_version->v_uid,
                    file_version->v_gid, (long long)st_data.st_size, st_data.st_mtime,
                    entry->d_name + strlen(METADATA_PREFIX));
                }
              if (len < 0)
                {
                  /* Free everything if it failed */
                  helper_free_string_list(file_list);
                  closedir(dir);
                  return -ENOMEM;
                }
              
              file_list_ptr = &(*file_list_ptr)->sl_next;
            }
        }
    
      closedir(dir);

      /* Build the final string */
      result_size = helper_compose_string_list(&result, file_list, '\0');
      helper_free_string_list(file_list);

      /* Handle the EA protocol */

      if (size == 0)
        res = result_size;
      else if (result_size > size)
        res = -ERANGE;
      else
        {
          memcpy(value, result, result_size);
          res = result_size;
        }
      free(result);
      return res;
    }
  else
    {
      /* unknown rcs.*-attribute */
      return -EPERM;
    }
}
Пример #22
0
status_t linux_init(vmi_instance_t vmi) {

    status_t rc;
    os_interface_t os_interface = NULL;

    if (vmi->config == NULL) {
        errprint("No config table found\n");
        return VMI_FAILURE;
    }

    if (vmi->os_data != NULL) {
        errprint("os data already initialized, reinitializing\n");
        free(vmi->os_data);
    }

    vmi->os_data = safe_malloc(sizeof(struct linux_instance));
    bzero(vmi->os_data, sizeof(struct linux_instance));
    linux_instance_t linux_instance = vmi->os_data;

    g_hash_table_foreach(vmi->config, (GHFunc)linux_read_config_ghashtable_entries, vmi);

#if defined(ARM)
    rc = driver_get_vcpureg(vmi, &vmi->kpgd, TTBR1, 0);
#elif defined(I386) || defined(X86_64)
    rc = driver_get_vcpureg(vmi, &vmi->kpgd, CR3, 0);
#endif

    /*
     * The driver failed to get us a pagetable.
     * As a fall-back, try to init using heuristics.
     * This path is taken in FILE mode as well.
     */
    if (VMI_FAILURE == rc)
        if (VMI_FAILURE == linux_filemode_init(vmi))
            goto _exit;

    dbprint(VMI_DEBUG_MISC, "**set vmi->kpgd (0x%.16"PRIx64").\n", vmi->kpgd);

    rc = linux_system_map_symbol_to_address(vmi, "init_task", NULL,
            &vmi->init_task);
    if (VMI_FAILURE == rc) {
        errprint("Could not get init_task from System.map\n");
        goto _exit;
    }

done:
    os_interface = safe_malloc(sizeof(struct os_interface));
    bzero(os_interface, sizeof(struct os_interface));
    os_interface->os_get_offset = linux_get_offset;
    os_interface->os_pid_to_pgd = linux_pid_to_pgd;
    os_interface->os_pgd_to_pid = linux_pgd_to_pid;
    os_interface->os_ksym2v = linux_system_map_symbol_to_address;
    os_interface->os_usym2rva = NULL;
    os_interface->os_rva2sym = NULL;
    os_interface->os_read_unicode_struct = NULL;
    os_interface->os_teardown = linux_teardown;

    vmi->os_interface = os_interface;

    return VMI_SUCCESS;

    _exit:
    free(vmi->os_data);
    vmi->os_data = NULL;
    return VMI_FAILURE;
}
Пример #23
0
int BSPMain( int argc, char **argv ){
	int i;
	char path[ 1024 ], tempSource[ 1024 ];
	qboolean onlyents = qfalse;


	/* note it */
	Sys_Printf( "--- BSP ---\n" );

	SetDrawSurfacesBuffer();
	mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
	memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
	numMapDrawSurfs = 0;

	tempSource[ 0 ] = '\0';

	/* set standard game flags */
	maxSurfaceVerts = game->maxSurfaceVerts;
	maxSurfaceIndexes = game->maxSurfaceIndexes;
	emitFlares = game->emitFlares;

	/* process arguments */
	for ( i = 1; i < ( argc - 1 ); i++ )
	{
		if ( !strcmp( argv[ i ], "-onlyents" ) ) {
			Sys_Printf( "Running entity-only compile\n" );
			onlyents = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-tempname" ) ) {
			strcpy( tempSource, argv[ ++i ] );
		}
		else if ( !strcmp( argv[ i ], "-tmpout" ) ) {
			strcpy( outbase, "/tmp" );
		}
		else if ( !strcmp( argv[ i ],  "-nowater" ) ) {
			Sys_Printf( "Disabling water\n" );
			nowater = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-nodetail" ) ) {
			Sys_Printf( "Ignoring detail brushes\n" ) ;
			nodetail = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-fulldetail" ) ) {
			Sys_Printf( "Turning detail brushes into structural brushes\n" );
			fulldetail = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-nofog" ) ) {
			Sys_Printf( "Fog volumes disabled\n" );
			nofog = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-nosubdivide" ) ) {
			Sys_Printf( "Disabling brush face subdivision\n" );
			nosubdivide = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-leaktest" ) ) {
			Sys_Printf( "Leaktest enabled\n" );
			leaktest = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-verboseentities" ) ) {
			Sys_Printf( "Verbose entities enabled\n" );
			verboseEntities = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-nocurves" ) ) {
			Sys_Printf( "Ignoring curved surfaces (patches)\n" );
			noCurveBrushes = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-notjunc" ) ) {
			Sys_Printf( "T-junction fixing disabled\n" );
			notjunc = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-fakemap" ) ) {
			Sys_Printf( "Generating fakemap.map\n" );
			fakemap = qtrue;
		}
		else if ( !strcmp( argv[ i ],  "-samplesize" ) ) {
			sampleSize = atoi( argv[ i + 1 ] );
			if ( sampleSize < 1 ) {
				sampleSize = 1;
			}
			i++;
			Sys_Printf( "Lightmap sample size set to %dx%d units\n", sampleSize, sampleSize );
		}
		else if ( !strcmp( argv[ i ],  "-custinfoparms" ) ) {
			Sys_Printf( "Custom info parms enabled\n" );
			useCustomInfoParms = qtrue;
		}

		/* sof2 args */
		else if ( !strcmp( argv[ i ], "-rename" ) ) {
			Sys_Printf( "Appending _bsp suffix to misc_model shaders (SOF2)\n" );
			renameModelShaders = qtrue;
		}

		/* ydnar args */
		else if ( !strcmp( argv[ i ],  "-ne" ) ) {
			normalEpsilon = atof( argv[ i + 1 ] );
			i++;
			Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
		}
		else if ( !strcmp( argv[ i ],  "-de" ) ) {
			distanceEpsilon = atof( argv[ i + 1 ] );
			i++;
			Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
		}
		else if ( !strcmp( argv[ i ],  "-mv" ) ) {
			maxLMSurfaceVerts = atoi( argv[ i + 1 ] );
			if ( maxLMSurfaceVerts < 3 ) {
				maxLMSurfaceVerts = 3;
			}
			if ( maxLMSurfaceVerts > maxSurfaceVerts ) {
				maxSurfaceVerts = maxLMSurfaceVerts;
			}
			i++;
			Sys_Printf( "Maximum lightmapped surface vertex count set to %d\n", maxLMSurfaceVerts );
		}
		else if ( !strcmp( argv[ i ],  "-mi" ) ) {
			maxSurfaceIndexes = atoi( argv[ i + 1 ] );
			if ( maxSurfaceIndexes < 3 ) {
				maxSurfaceIndexes = 3;
			}
			i++;
			Sys_Printf( "Maximum per-surface index count set to %d\n", maxSurfaceIndexes );
		}
		else if ( !strcmp( argv[ i ], "-np" ) ) {
			npDegrees = atof( argv[ i + 1 ] );
			if ( npDegrees < 0.0f ) {
				shadeAngleDegrees = 0.0f;
			}
			else if ( npDegrees > 0.0f ) {
				Sys_Printf( "Forcing nonplanar surfaces with a breaking angle of %f degrees\n", npDegrees );
			}
			i++;
		}
		else if ( !strcmp( argv[ i ],  "-snap" ) ) {
			bevelSnap = atoi( argv[ i + 1 ] );
			if ( bevelSnap < 0 ) {
				bevelSnap = 0;
			}
			i++;
			if ( bevelSnap > 0 ) {
				Sys_Printf( "Snapping brush bevel planes to %d units\n", bevelSnap );
			}
		}
		else if ( !strcmp( argv[ i ],  "-texrange" ) ) {
			texRange = atoi( argv[ i + 1 ] );
			if ( texRange < 0 ) {
				texRange = 0;
			}
			i++;
			Sys_Printf( "Limiting per-surface texture range to %d texels\n", texRange );
		}
		else if ( !strcmp( argv[ i ], "-nohint" ) ) {
			Sys_Printf( "Hint brushes disabled\n" );
			noHint = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-flat" ) ) {
			Sys_Printf( "Flatshading enabled\n" );
			flat = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-meta" ) ) {
			Sys_Printf( "Creating meta surfaces from brush faces\n" );
			meta = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-patchmeta" ) ) {
			Sys_Printf( "Creating meta surfaces from patches\n" );
			patchMeta = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-flares" ) ) {
			Sys_Printf( "Flare surfaces enabled\n" );
			emitFlares = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-noflares" ) ) {
			Sys_Printf( "Flare surfaces disabled\n" );
			emitFlares = qfalse;
		}
		else if ( !strcmp( argv[ i ], "-skyfix" ) ) {
			Sys_Printf( "GL_CLAMP sky fix/hack/workaround enabled\n" );
			skyFixHack = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-debugsurfaces" ) ) {
			Sys_Printf( "emitting debug surfaces\n" );
			debugSurfaces = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-debuginset" ) ) {
			Sys_Printf( "Debug surface triangle insetting enabled\n" );
			debugInset = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-debugportals" ) ) {
			Sys_Printf( "Debug portal surfaces enabled\n" );
			debugPortals = qtrue;
		}
		else if ( !strcmp( argv[ i ], "-bsp" ) ) {
			Sys_Printf( "-bsp argument unnecessary\n" );
		}
		else{
			Sys_FPrintf( SYS_WRN, "WARNING: Unknown option \"%s\"\n", argv[ i ] );
		}
	}

	/* fixme: print more useful usage here */
	if ( i != ( argc - 1 ) ) {
		Error( "usage: q3map [options] mapfile" );
	}

	/* copy source name */
	strcpy( source, ExpandArg( argv[ i ] ) );
	StripExtension( source );

	/* ydnar: set default sample size */
	SetDefaultSampleSize( sampleSize );

	/* delete portal, line and surface files */
	sprintf( path, "%s.prt", source );
	remove( path );
	sprintf( path, "%s.lin", source );
	remove( path );
	//%	sprintf( path, "%s.srf", source );	/* ydnar */
	//%	remove( path );

	/* expand mapname */
	strcpy( name, ExpandArg( argv[ i ] ) );
	if ( strcmp( name + strlen( name ) - 4, ".reg" ) ) {
		/* if we are doing a full map, delete the last saved region map */
		sprintf( path, "%s.reg", source );
		remove( path );
		DefaultExtension( name, ".map" );   /* might be .reg */
	}

	/* if onlyents, just grab the entites and resave */
	if ( onlyents ) {
		OnlyEnts();
		return 0;
	}

	/* load shaders */
	LoadShaderInfo();

	/* load original file from temp spot in case it was renamed by the editor on the way in */
	if ( strlen( tempSource ) > 0 ) {
		LoadMapFile( tempSource, qfalse );
	}
	else{
		LoadMapFile( name, qfalse );
	}

	/* ydnar: decal setup */
	ProcessDecals();

	/* ydnar: cloned brush model entities */
	SetCloneModelNumbers();

	/* process world and submodels */
	ProcessModels();

	/* set light styles from targetted light entities */
	SetLightStyles();

	/* finish and write bsp */
	EndBSPFile();

	/* remove temp map source file if appropriate */
	if ( strlen( tempSource ) > 0 ) {
		remove( tempSource );
	}

	/* return to sender */
	return 0;
}
Пример #24
0
/* 
   If panning or note_to_use != -1, it will be used for all samples,
   instead of the sample-specific values in the instrument file. 

   For note_to_use, any value <0 or >127 will be forced to 0.
 
   For other parameters, 1 means yes, 0 means no, other values are
   undefined.

   TODO: do reverse loops right */
static InstrumentLayer *load_instrument(char *name, int font_type, int percussion,
				   int panning, int amp, int cfg_tuning, int note_to_use,
				   int strip_loop, int strip_envelope,
				   int strip_tail, int bank, int gm_num, int sf_ix)
{
  InstrumentLayer *lp, *lastlp, *headlp;
  Instrument *ip;
  FILE *fp;
  uint8 tmp[1024];
  int i,j,noluck=0;
#ifdef PATCH_EXT_LIST
  static char *patch_ext[] = PATCH_EXT_LIST;
#endif
  int sf2flag = 0;
  int right_samples = 0;
  int stereo_channels = 1, stereo_layer;
  int vlayer_list[19][4], vlayer, vlayer_count;

  if (!name) return 0;
  
  /* Open patch file */
  if ((fp=open_file(name, 1, OF_NORMAL)) == NULL)
    {
      noluck=1;
#ifdef PATCH_EXT_LIST
      /* Try with various extensions */
      for (i=0; patch_ext[i]; i++)
	{
	  if (strlen(name)+strlen(patch_ext[i])<1024)
	    {
              char path[1024];
	      strcpy(path, name);
	      strcat(path, patch_ext[i]);
	      if ((fp=open_file(path, 1, OF_NORMAL)) != NULL)
		{
		  noluck=0;
		  break;
		}
	    }
	}
#endif
    }
  
  if (noluck)
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
		"Instrument `%s' can't be found.", name);
      return 0;
    }
      
  /*ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s", current_filename);*/
  
  /* Read some headers and do cursory sanity checks. There are loads
     of magic offsets. This could be rewritten... */

  if ((239 != fread(tmp, 1, 239, fp)) ||
      (memcmp(tmp, "GF1PATCH110\0ID#000002", 22) &&
       memcmp(tmp, "GF1PATCH100\0ID#000002", 22))) /* don't know what the
						      differences are */
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: not an instrument", name);
      return 0;
    }

/* patch layout:
 * bytes:  info:		starts at offset:
 * 22	id (see above)		0
 * 60	copyright		22
 *  1	instruments		82
 *  1	voices			83
 *  1	channels		84
 *  2	number of waveforms	85
 *  2	master volume		87
 *  4	datasize		89
 * 36   reserved, but now:	93
 * 	7 "SF2EXT\0" id			93
 * 	1 right samples		       100
 *     28 reserved		       101
 *  2	instrument number	129
 * 16	instrument name		131
 *  4	instrument size		147
 *  1	number of layers	151
 * 40	reserved		152
 *  1	layer duplicate		192
 *  1	layer number		193
 *  4	layer size		194
 *  1	number of samples	198
 * 40	reserved		199
 * 				239
 * THEN, for each sample, see below
 */

  if (!memcmp(tmp + 93, "SF2EXT", 6))
    {
	    sf2flag = 1;
	    vlayer_count = tmp[152];
    }

  if (tmp[82] != 1 && tmp[82] != 0) /* instruments. To some patch makers, 
				       0 means 1 */
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
	   "Can't handle patches with %d instruments", tmp[82]);
      return 0;
    }

  if (tmp[151] != 1 && tmp[151] != 0) /* layers. What's a layer? */
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
	   "Can't handle instruments with %d layers", tmp[151]);
      return 0;
    }
  

  if (sf2flag && vlayer_count > 0) {
	for (i = 0; i < 9; i++)
	  for (j = 0; j < 4; j++)
	    vlayer_list[i][j] = tmp[153+i*4+j];
	for (i = 9; i < 19; i++)
	  for (j = 0; j < 4; j++)
	    vlayer_list[i][j] = tmp[199+(i-9)*4+j];
  }
  else {
	for (i = 0; i < 19; i++)
	  for (j = 0; j < 4; j++)
	    vlayer_list[i][j] = 0;
	vlayer_list[0][0] = 0;
	vlayer_list[0][1] = 127;
	vlayer_list[0][2] = tmp[198];
	vlayer_list[0][3] = 0;
	vlayer_count = 1;
  }

  lastlp = 0;

  for (vlayer = 0; vlayer < vlayer_count; vlayer++) {

  lp=(InstrumentLayer *)safe_malloc(sizeof(InstrumentLayer));
  lp->size = sizeof(InstrumentLayer);
  lp->lo = vlayer_list[vlayer][0];
  lp->hi = vlayer_list[vlayer][1];
  ip=(Instrument *)safe_malloc(sizeof(Instrument));
  lp->size += sizeof(Instrument);
  lp->instrument = ip;
  lp->next = 0;

  if (lastlp) lastlp->next = lp;
  else headlp = lp;

  lastlp = lp;

  if (sf2flag) ip->type = INST_SF2;
  else ip->type = INST_GUS;
  ip->samples = vlayer_list[vlayer][2];
  ip->sample = (Sample *)safe_malloc(sizeof(Sample) * ip->samples);
  lp->size += sizeof(Sample) * ip->samples;
  ip->left_samples = ip->samples;
  ip->left_sample = ip->sample;
  right_samples = vlayer_list[vlayer][3];
  ip->right_samples = right_samples;
  if (right_samples)
    {
      ip->right_sample = (Sample *)safe_malloc(sizeof(Sample) * right_samples);
      lp->size += sizeof(Sample) * right_samples;
      stereo_channels = 2;
    }
  else ip->right_sample = 0;
  ip->contents = 0;

  ctl->cmsg(CMSG_INFO, VERB_NOISY, "%s%s[%d,%d] %s(%d-%d layer %d of %d)",
	(percussion)? "   ":"", name,
	(percussion)? note_to_use : gm_num, bank,
	(right_samples)? "(2) " : "",
	lp->lo, lp->hi, vlayer+1, vlayer_count);

 for (stereo_layer = 0; stereo_layer < stereo_channels; stereo_layer++)
 {
  int sample_count;

  if (stereo_layer == 0) sample_count = ip->left_samples;
  else if (stereo_layer == 1) sample_count = ip->right_samples;

  for (i=0; i < sample_count; i++)
    {
      uint8 fractions;
      int32 tmplong;
      uint16 tmpshort;
      uint16 sample_volume;
      uint8 tmpchar;
      Sample *sp;
      uint8 sf2delay;

#define READ_CHAR(thing) \
      if (1 != fread(&tmpchar, 1, 1, fp)) goto fail; \
      thing = tmpchar;
#define READ_SHORT(thing) \
      if (1 != fread(&tmpshort, 2, 1, fp)) goto fail; \
      thing = LE_SHORT(tmpshort);
#define READ_LONG(thing) \
      if (1 != fread(&tmplong, 4, 1, fp)) goto fail; \
      thing = LE_LONG(tmplong);

/*
 *  7	sample name
 *  1	fractions
 *  4	length
 *  4	loop start
 *  4	loop end
 *  2	sample rate
 *  4	low frequency
 *  4	high frequency
 *  2	finetune
 *  1	panning
 *  6	envelope rates			|
 *  6	envelope offsets		|  18 bytes
 *  3	tremolo sweep, rate, depth	|
 *  3	vibrato sweep, rate, depth	|
 *  1	sample mode
 *  2	scale frequency
 *  2	scale factor
 *  2	sample volume (??)
 * 34	reserved
 * Now: 1	delay
 * 	33	reserved
 */
      skip(fp, 7); /* Skip the wave name */

      if (1 != fread(&fractions, 1, 1, fp))
	{
	fail:
	  ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d", i);
	  if (stereo_layer == 1)
	     {
	       for (j=0; j<i; j++)
	         free(ip->right_sample[j].data);
	       free(ip->right_sample);
	       i = ip->left_samples;
	     }
	  for (j=0; j<i; j++)
	    free(ip->left_sample[j].data);
	  free(ip->left_sample);
	  free(ip);
	  free(lp);
	  return 0;
	}

      if (stereo_layer == 0) sp=&(ip->left_sample[i]);
      else if (stereo_layer == 1) sp=&(ip->right_sample[i]);

      READ_LONG(sp->data_length);
      READ_LONG(sp->loop_start);
      READ_LONG(sp->loop_end);
      READ_SHORT(sp->sample_rate);
      READ_LONG(sp->low_freq);
      READ_LONG(sp->high_freq);
      READ_LONG(sp->root_freq);
      skip(fp, 2); /* Why have a "root frequency" and then "tuning"?? */
      
      READ_CHAR(tmp[0]);

      if (panning==-1)
	sp->panning = (tmp[0] * 8 + 4) & 0x7f;
      else
	sp->panning=(uint8)(panning & 0x7F);

      sp->resonance=0;
      sp->cutoff_freq=0;
      sp->reverberation=0;
      sp->chorusdepth=0;
      sp->exclusiveClass=0;
      sp->keyToModEnvHold=0;
      sp->keyToModEnvDecay=0;
      sp->keyToVolEnvHold=0;
      sp->keyToVolEnvDecay=0;

      if (cfg_tuning)
	{
	  double tune_factor = (double)(cfg_tuning)/1200.0;
	  tune_factor = pow(2.0, tune_factor);
	  sp->root_freq = (uint32)( tune_factor * (double)sp->root_freq );
	}

      /* envelope, tremolo, and vibrato */
      if (18 != fread(tmp, 1, 18, fp)) goto fail; 

      if (!tmp[13] || !tmp[14])
	{
	  sp->tremolo_sweep_increment=
	    sp->tremolo_phase_increment=sp->tremolo_depth=0;
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo");
	}
      else
	{
	  sp->tremolo_sweep_increment=convert_tremolo_sweep(tmp[12]);
	  sp->tremolo_phase_increment=convert_tremolo_rate(tmp[13]);
	  sp->tremolo_depth=tmp[14];
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
	       " * tremolo: sweep %d, phase %d, depth %d",
	       sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
	       sp->tremolo_depth);
	}

      if (!tmp[16] || !tmp[17])
	{
	  sp->vibrato_sweep_increment=
	    sp->vibrato_control_ratio=sp->vibrato_depth=0;
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato");
	}
      else
	{
	  sp->vibrato_control_ratio=convert_vibrato_rate(tmp[16]);
	  sp->vibrato_sweep_increment=
	    convert_vibrato_sweep(tmp[15], sp->vibrato_control_ratio);
	  sp->vibrato_depth=tmp[17];
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
	       " * vibrato: sweep %d, ctl %d, depth %d",
	       sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
	       sp->vibrato_depth);

	}

      READ_CHAR(sp->modes);
      READ_SHORT(sp->freq_center);
      READ_SHORT(sp->freq_scale);

      if (sf2flag)
        {
          READ_SHORT(sample_volume);
	  READ_CHAR(sf2delay);
          READ_CHAR(sp->exclusiveClass);
          skip(fp, 32);
	}
      else
        {
          skip(fp, 36);
        }

      /* Mark this as a fixed-pitch instrument if such a deed is desired. */
      if (note_to_use!=-1)
	sp->note_to_use=(uint8)(note_to_use);
      else
	sp->note_to_use=0;
      
      /* seashore.pat in the Midia patch set has no Sustain. I don't
         understand why, and fixing it by adding the Sustain flag to
         all looped patches probably breaks something else. We do it
         anyway. */
	 
      if (sp->modes & MODES_LOOPING) 
	sp->modes |= MODES_SUSTAIN;

      /* Strip any loops and envelopes we're permitted to */
      if ((strip_loop==1) && 
	  (sp->modes & (MODES_SUSTAIN | MODES_LOOPING | 
			MODES_PINGPONG | MODES_REVERSE)))
	{
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain");
	  sp->modes &=~(MODES_SUSTAIN | MODES_LOOPING | 
			MODES_PINGPONG | MODES_REVERSE);
	}

      if (strip_envelope==1)
	{
	  if (sp->modes & MODES_ENVELOPE)
	    ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
	  sp->modes &= ~MODES_ENVELOPE;
	}
      else if (strip_envelope != 0)
	{
	  /* Have to make a guess. */
	  if (!(sp->modes & (MODES_LOOPING | MODES_PINGPONG | MODES_REVERSE)))
	    {
	      /* No loop? Then what's there to sustain? No envelope needed
		 either... */
	      sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
			" - No loop, removing sustain and envelope");
	    }
	  else if (!memcmp(tmp, "??????", 6) || tmp[11] >= 100) 
	    {
	      /* Envelope rates all maxed out? Envelope end at a high "offset"?
		 That's a weird envelope. Take it out. */
	      sp->modes &= ~MODES_ENVELOPE;
	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
			" - Weirdness, removing envelope");
	    }
	  else if (!(sp->modes & MODES_SUSTAIN))
	    {
	      /* No sustain? Then no envelope.  I don't know if this is
		 justified, but patches without sustain usually don't need the
		 envelope either... at least the Gravis ones. They're mostly
		 drums.  I think. */
	      sp->modes &= ~MODES_ENVELOPE;
	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
			" - No sustain, removing envelope");
	    }
	}

      sp->attenuation = 0;

      for (j=ATTACK; j<DELAY; j++)
	{
	  sp->envelope_rate[j]=
	    (j<3)? convert_envelope_rate_attack(tmp[j], 11) : convert_envelope_rate(tmp[j]);
	  sp->envelope_offset[j]= 
	    convert_envelope_offset(tmp[6+j]);
	}
      if (sf2flag)
	{
	  if (sf2delay > 5) sf2delay = 5;
	  sp->envelope_rate[DELAY] = (int32)( (sf2delay*play_mode->rate) / 1000 );
	}
      else
	{
          sp->envelope_rate[DELAY]=0;
	}
      sp->envelope_offset[DELAY]=0;

      for (j=ATTACK; j<DELAY; j++)
	{
	  sp->modulation_rate[j]=sp->envelope_rate[j];
	  sp->modulation_offset[j]=sp->envelope_offset[j];
	}
      sp->modulation_rate[DELAY] = sp->modulation_offset[DELAY] = 0;
      sp->modEnvToFilterFc=0;
      sp->modEnvToPitch=0;
      sp->lfo_sweep_increment = 0;
      sp->lfo_phase_increment = 0;
      sp->modLfoToFilterFc = 0;
      sp->vibrato_delay = 0;

      /* Then read the sample data */
      if (sp->data_length/2 > MAX_SAMPLE_SIZE)
        {
	  goto fail;
	}
      sp->data = safe_malloc(sp->data_length + 1);
      lp->size += sp->data_length + 1;

      if (1 != fread(sp->data, sp->data_length, 1, fp))
	goto fail;
      
      if (!(sp->modes & MODES_16BIT)) /* convert to 16-bit data */
	{
	  int32 i=sp->data_length;
	  uint8 *cp=(uint8 *)(sp->data);
	  uint16 *tmp,*newdta;
	  tmp=newdta=safe_malloc(sp->data_length*2 + 2);
	  while (i--)
	    *tmp++ = (uint16)(*cp++) << 8;
	  cp=(uint8 *)(sp->data);
	  sp->data = (sample_t *)newdta;
	  free(cp);
	  sp->data_length *= 2;
	  sp->loop_start *= 2;
	  sp->loop_end *= 2;
	}
#ifndef LITTLE_ENDIAN
      else
	/* convert to machine byte order */
	{
	  int32 i=sp->data_length/2;
	  int16 *tmp=(int16 *)sp->data,s;
	  while (i--)
	    { 
	      s=LE_SHORT(*tmp);
	      *tmp++=s;
	    }
	}
#endif
      
      if (sp->modes & MODES_UNSIGNED) /* convert to signed data */
	{
	  int32 i=sp->data_length/2;
	  int16 *tmp=(int16 *)sp->data;
	  while (i--)
	    *tmp++ ^= 0x8000;
	}

      /* Reverse reverse loops and pass them off as normal loops */
      if (sp->modes & MODES_REVERSE)
	{
	  int32 t;
	  /* The GUS apparently plays reverse loops by reversing the
	     whole sample. We do the same because the GUS does not SUCK. */

	  ctl->cmsg(CMSG_WARNING, VERB_NORMAL, "Reverse loop in %s", name);
	  reverse_data((int16 *)sp->data, 0, sp->data_length/2);

	  t=sp->loop_start;
	  sp->loop_start=sp->data_length - sp->loop_end;
	  sp->loop_end=sp->data_length - t;

	  sp->modes &= ~MODES_REVERSE;
	  sp->modes |= MODES_LOOPING; /* just in case */
	}

      /* If necessary do some anti-aliasing filtering  */

      if (antialiasing_allowed)
	  antialiasing(sp,play_mode->rate);

#ifdef ADJUST_SAMPLE_VOLUMES
      if (amp!=-1)
	sp->volume=(FLOAT_T)((amp) / 100.0);
      else if (sf2flag)
	sp->volume=(FLOAT_T)((sample_volume) / 255.0);
      else
	{
	  /* Try to determine a volume scaling factor for the sample.
	     This is a very crude adjustment, but things sound more
	     balanced with it. Still, this should be a runtime option. */
	  uint32 i, numsamps=sp->data_length/2;
	  uint32 higher=0, highcount=0;
	  int16 maxamp=0,a;
	  int16 *tmp=(int16 *)sp->data;
	  i = numsamps;
	  while (i--)
	    {
	      a=*tmp++;
	      if (a<0) a=-a;
	      if (a>maxamp)
		maxamp=a;
	    }
	  tmp=(int16 *)sp->data;
	  i = numsamps;
	  while (i--)
	    {
	      a=*tmp++;
	      if (a<0) a=-a;
	      if (a > 3*maxamp/4)
		{
		   higher += a;
		   highcount++;
		}
	    }
	  if (highcount) higher /= highcount;
	  else higher = 10000;
	  sp->volume = (32768.0 * 0.875) /  (double)higher ;
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * volume comp: %f", sp->volume);
	}
#else
      if (amp!=-1)
	sp->volume=(double)(amp) / 100.0;
      else
	sp->volume=1.0;
#endif

      sp->data_length /= 2; /* These are in bytes. Convert into samples. */

      sp->loop_start /= 2;
      sp->loop_end /= 2;
      sp->data[sp->data_length] = sp->data[sp->data_length-1];

      /* Then fractional samples */
      sp->data_length <<= FRACTION_BITS;
      sp->loop_start <<= FRACTION_BITS;
      sp->loop_end <<= FRACTION_BITS;

    /* trim off zero data at end */
    {
	int ls = sp->loop_start>>FRACTION_BITS;
	int le = sp->loop_end>>FRACTION_BITS;
	int se = sp->data_length>>FRACTION_BITS;
	while (se > 1 && !sp->data[se-1]) se--;
	if (le > se) le = se;
	if (ls >= le) sp->modes &= ~MODES_LOOPING;
	sp->loop_end = le<<FRACTION_BITS;
	sp->data_length = se<<FRACTION_BITS;
    }

      /* Adjust for fractional loop points. This is a guess. Does anyone
	 know what "fractions" really stands for? */
      sp->loop_start |=
	(fractions & 0x0F) << (FRACTION_BITS-4);
      sp->loop_end |=
	((fractions>>4) & 0x0F) << (FRACTION_BITS-4);

      /* If this instrument will always be played on the same note,
	 and it's not looped, we can resample it now. */
      if (sp->note_to_use && !(sp->modes & MODES_LOOPING))
	pre_resample(sp);

#ifdef LOOKUP_HACK
      /* Squash the 16-bit data into 8 bits. */
      {
	uint8 *gulp,*ulp;
	int16 *swp;
	int l=sp->data_length >> FRACTION_BITS;
	gulp=ulp=safe_malloc(l+1);
	swp=(int16 *)sp->data;
	while(l--)
	  *ulp++ = (*swp++ >> 8) & 0xFF;
	free(sp->data);
	sp->data=(sample_t *)gulp;
      }
#endif
      
      if (strip_tail==1)
	{
	  /* Let's not really, just say we did. */
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Stripping tail");
	  sp->data_length = sp->loop_end;
	}
    } /* end of sample loop */
 } /* end of stereo layer loop */
 } /* end of vlayer loop */


  close_file(fp);
  return headlp;
}
Пример #25
0
/**
 * Send a file.
 *
 * Returns C<0> on success, C<-1> for error, C<-2> if the daemon
 * cancelled (we must read the error message).
 */
int
guestfs_int_send_file (guestfs_h *g, const char *filename)
{
  CLEANUP_FREE char *buf = safe_malloc (g, GUESTFS_MAX_CHUNK_SIZE);
  int fd, r = 0, err;

  g->user_cancel = 0;

  fd = open (filename, O_RDONLY|O_CLOEXEC);
  if (fd == -1) {
    perrorf (g, "open: %s", filename);
    send_file_cancellation (g);
    return -1;
  }

  guestfs_int_fadvise_sequential (fd);

  /* Send file in chunked encoding. */
  while (!g->user_cancel) {
    r = read (fd, buf, GUESTFS_MAX_CHUNK_SIZE);
    if (r == -1 && (errno == EINTR || errno == EAGAIN))
      continue;
    if (r <= 0) break;
    err = send_file_data (g, buf, r);
    if (err < 0) {
      if (err == -2)		/* daemon sent cancellation */
        send_file_cancellation (g);
      close (fd);
      return err;
    }
  }

  if (r == -1) {
    perrorf (g, "read: %s", filename);
    send_file_cancellation (g);
    close (fd);
    return -1;
  }

  if (g->user_cancel) {
    guestfs_int_error_errno (g, EINTR, _("operation cancelled by user"));
    send_file_cancellation (g);
    close (fd);
    return -1;
  }

  /* End of file, but before we send that, we need to close
   * the file and check for errors.
   */
  if (close (fd) == -1) {
    perrorf (g, "close: %s", filename);
    send_file_cancellation (g);
    return -1;
  }

  err = send_file_complete (g);
  if (err < 0) {
    if (err == -2)              /* daemon sent cancellation */
      send_file_cancellation (g);
    return err;
  }

  return 0;
}
Пример #26
0
void read_coverage_data (const char* data_file) 
{
  long time_stamp;
  long name_length;
  char *source_name;
  struct stat stat_buf;
  long data_size;
  long chunk_size;
  long first_line;
  long *data_points;
  long nb_procs;
  collection c;
  char *proc_name;
  long proc_count;
  long f = open (data_file, O_RDONLY, 0);    
  FILE* fs;

  if (verbose_mode) {
    fprintf (stderr, "Reading database file %s ...\n", data_file);
  }

  if (f < 0) {
    sprintf (error_message, "cannot read coverage file %s", data_file); 
    error (); }

  while (read (f, &chunk_size, sizeof (long)) != 0) {

    read (f, &time_stamp, sizeof (long));

    read (f, &name_length, sizeof (long));

    source_name = (char *) safe_malloc (name_length+1);
    read (f, source_name, name_length);
    read_string_tail (f, name_length);
    source_name[name_length] = 0;
    if (verbose_mode) { fprintf (stderr, "... %s\n", source_name); }

    fs = locate_and_open (source_name, "r");
    if (fs == NULL || fstat (fileno (fs), &stat_buf) == -1) {
      sprintf (error_message,
               "cannot obtain stats about %s", source_name);
      error ();
    } else {
      fclose (fs);
    }

    if (/*** stat_buf.st_mtime ***/ 0 != time_stamp) {
      sprintf (error_message, "wrong timestamp for %s", source_name);
      warning ();
    }

    read (f, &first_line, sizeof (long));

    read (f, &data_size, sizeof (long));
    data_points = (long *) safe_malloc (data_size * sizeof (long));
    read (f, data_points, data_size * sizeof (long));

    if ((c = find_collection (source_name)) != NULL) {
      if (c->time_stamp != time_stamp) {
        sprintf (error_message, 
                 "different timestamps for %s", source_name);
        warning (); }
      if (c->first_line != first_line) {
        sprintf (error_message, 
           "new and old data have different source lines for %s", source_name);
        warning (); }
      if (c->data_size != data_size) {
        sprintf (error_message, 
                 "new and old data of different sizes for %s", source_name);
        warning (); }
      { long i;
        for (i = 0; i < data_size; i++) {
          if (data_points[i] >= 0) {
            if (c->data_points[i] >= 0) {
              c->data_points[i] += data_points[i]; }
            else {
              c->data_points [i] = data_points[i]; }}}}
      free (source_name); 
      free (data_points); }
    else {
      c = (collection) safe_malloc (sizeof (collection_struct));
      c->file_name = source_name;
      c->time_stamp = time_stamp;
      c->data_points = data_points;
      c->first_line = first_line;
      c->data_size = data_size;
      c->next = collections;
      c->my_procs = NULL;
      c->nb_procs = 0;
      collections = c; }

    read (f, &nb_procs, sizeof (long));

    while (nb_procs-- > 0) {
      proc p;

      read (f, &name_length, sizeof(long));

      proc_name = (char *) safe_malloc (name_length+1);
      read (f, proc_name, name_length);
      read_string_tail (f, name_length);
      proc_name[name_length] = 0;

      read (f, &proc_count, sizeof (long));
      if ((p = find_proc (proc_name, c->my_procs)) != NULL) {
        p->count += proc_count; 
        free (proc_name); }
      else {
        p = (proc) safe_malloc (sizeof (proc_struct));
        p->proc_name = proc_name;
        p->next = c->my_procs;
        c->my_procs = p;
        c->nb_procs ++;
        p->count = proc_count; }}}
  close (f);
  database_loaded = TRUE;

  if (verbose_mode) {
    fprintf (stderr, "... done\n"); }
}
Пример #27
0
/**
 * This function reads a single message, file chunk, launch flag or
 * cancellation flag from the daemon.  If something was read, it
 * returns C<0>, otherwise C<-1>.
 *
 * Both C<size_rtn> and C<buf_rtn> must be passed by the caller as
 * non-NULL.
 *
 * C<*size_rtn> returns the size of the returned message or it may be
 * C<GUESTFS_LAUNCH_FLAG> or C<GUESTFS_CANCEL_FLAG>.
 *
 * C<*buf_rtn> is returned containing the message (if any) or will be
 * set to C<NULL>.  C<*buf_rtn> must be freed by the caller.
 *
 * This checks for EOF (appliance died) and passes that up through the
 * child_cleanup function above.
 *
 * Log message, progress messages are handled transparently here.
 */
static int
recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
{
  char lenbuf[4];
  ssize_t n;
  XDR xdr;
  size_t message_size;

  *size_rtn = 0;
  *buf_rtn = NULL;

  /* RHBZ#914931: Along some (rare) paths, we might have closed the
   * socket connection just before this function is called, so just
   * return an error if this happens.
   */
  if (!g->conn) {
    guestfs_int_unexpected_close_error (g);
    return -1;
  }

  /* Read the 4 byte size / flag. */
  n = g->conn->ops->read_data (g, g->conn, lenbuf, 4);
  if (n == -1)
    return -1;
  if (n == 0) {
    guestfs_int_unexpected_close_error (g);
    child_cleanup (g);
    return -1;
  }

  xdrmem_create (&xdr, lenbuf, 4, XDR_DECODE);
  xdr_uint32_t (&xdr, size_rtn);
  xdr_destroy (&xdr);

  if (*size_rtn == GUESTFS_LAUNCH_FLAG) {
    if (g->state != LAUNCHING)
      error (g, _("received magic signature from guestfsd, but in state %d"),
             (int) g->state);
    else {
      g->state = READY;
      guestfs_int_call_callbacks_void (g, GUESTFS_EVENT_LAUNCH_DONE);
    }
    debug (g, "recv_from_daemon: received GUESTFS_LAUNCH_FLAG");
    return 0;
  }
  else if (*size_rtn == GUESTFS_CANCEL_FLAG) {
    debug (g, "recv_from_daemon: received GUESTFS_CANCEL_FLAG");
    return 0;
  }
  else if (*size_rtn == GUESTFS_PROGRESS_FLAG)
    /*FALLTHROUGH*/;
  else if (*size_rtn > GUESTFS_MESSAGE_MAX) {
    /* If this happens, it's pretty bad and we've probably lost
     * synchronization.
     */
    error (g, _("message length (%u) > maximum possible size (%d)"),
           (unsigned) *size_rtn, GUESTFS_MESSAGE_MAX);
    return -1;
  }

  /* Calculate the message size. */
  message_size =
    *size_rtn != GUESTFS_PROGRESS_FLAG ? *size_rtn : PROGRESS_MESSAGE_SIZE;

  /* Allocate the complete buffer, size now known. */
  *buf_rtn = safe_malloc (g, message_size);

  /* Read the message. */
  n = g->conn->ops->read_data (g, g->conn, *buf_rtn, message_size);
  if (n == -1) {
    free (*buf_rtn);
    *buf_rtn = NULL;
    return -1;
  }
  if (n == 0) {
    guestfs_int_unexpected_close_error (g);
    child_cleanup (g);
    free (*buf_rtn);
    *buf_rtn = NULL;
    return -1;
  }

  /* ... it's a normal message (not progress/launch/cancel) so display
   * it if we're debugging.
   */
#ifdef ENABLE_PACKET_DUMP
  if (g->verbose) {
    ssize_t i, j;

    for (i = 0; i < n; i += 16) {
      printf ("%04zx: ", i);
      for (j = i; j < MIN (i+16, n); ++j)
        printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
      for (; j < i+16; ++j)
        printf ("   ");
      printf ("|");
      for (j = i; j < MIN (i+16, n); ++j)
        if (c_isprint ((*(char **)buf_rtn)[j]))
          printf ("%c", (*(char **)buf_rtn)[j]);
        else
          printf (".");
      for (; j < i+16; ++j)
        printf (" ");
      printf ("|\n");
    }
  }
#endif

  return 0;
}
Пример #28
0
/* 
   If panning or note_to_use != -1, it will be used for all samples,
   instead of the sample-specific values in the instrument file. 

   For note_to_use, any value <0 or >127 will be forced to 0.
 
   For other parameters, 1 means yes, 0 means no, other values are
   undefined.

   TODO: do reverse loops right */
static Instrument *load_instrument(char *name, int percussion,
				   int panning, int amp, int note_to_use,
				   int strip_loop, int strip_envelope,
				   int strip_tail)
{
  Instrument *ip;
  Sample *sp;
  FILE *fp;
  uint8 tmp[1024];
  int i,j,noluck=0;
#ifdef PATCH_EXT_LIST
  static char *patch_ext[] = PATCH_EXT_LIST;
#endif

  if (!name) return 0;
    
  /* Open patch file */
  if ((fp=open_file(name, 1, OF_NORMAL)) == NULL)
    {
      noluck=1;
#ifdef PATCH_EXT_LIST
      /* Try with various extensions */
      for (i=0; patch_ext[i]; i++)
	{
	  if (strlen(name)+strlen(patch_ext[i])<1024)
	    {
        char path[1024];
        strcpy(path,DEFAULT_PATH);
		#ifdef __linux__
		strcat(path,"/");
		#else
        strcat(path,"\\");
		#endif
	    strcat(path, name);
	    strcat(path, patch_ext[i]);
        if ((fp=open_file(path, 1, OF_NORMAL)) != NULL)
		{
      noluck=0;
		  break;
		}
	    }
	}
#endif
    }
  
  if (noluck)
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
		"Instrument `%s' can't be found.", name);
      return 0;
    }
      
  ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s", current_filename);
  
  /* Read some headers and do cursory sanity checks. There are loads
     of magic offsets. This could be rewritten... */

  if ((239 != fread(tmp, 1, 239, fp)) ||
      (memcmp(tmp, "GF1PATCH110\0ID#000002", 22) &&
       memcmp(tmp, "GF1PATCH100\0ID#000002", 22))) /* don't know what the
						      differences are */
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: not an instrument", name);
      return 0;
    }
  
  if (tmp[82] != 1 && tmp[82] != 0) /* instruments. To some patch makers, 
				       0 means 1 */
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
	   "Can't handle patches with %d instruments", tmp[82]);
      return 0;
    }

  if (tmp[151] != 1 && tmp[151] != 0) /* layers. What's a layer? */
    {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
	   "Can't handle instruments with %d layers", tmp[151]);
      return 0;
    }
  
  ip=safe_malloc(sizeof(Instrument));
  ip->samples = tmp[198];
  ip->sample = safe_malloc(sizeof(Sample) * ip->samples);
  for (i=0; i<ip->samples; i++)
    {

      uint8 fractions;
      int32 tmplong;
      uint16 tmpshort;
      uint8 tmpchar;

#define READ_CHAR(thing) \
      if (1 != fread(&tmpchar, 1, 1, fp)) goto fail; \
      thing = tmpchar;
#define READ_SHORT(thing) \
      if (1 != fread(&tmpshort, 2, 1, fp)) goto fail; \
      thing = LE_SHORT(tmpshort);
#define READ_LONG(thing) \
      if (1 != fread(&tmplong, 4, 1, fp)) goto fail; \
      thing = LE_LONG(tmplong);

      skip(fp, 7); /* Skip the wave name */

      if (1 != fread(&fractions, 1, 1, fp))
	{
	fail:
	  ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d", i);
	  for (j=0; j<i; j++)
	    free(ip->sample[j].data);
	  free(ip->sample);
	  free(ip);
	  return 0;
	}

      sp=&(ip->sample[i]);
      
      READ_LONG(sp->data_length);
      READ_LONG(sp->loop_start);
      READ_LONG(sp->loop_end);
      READ_SHORT(sp->sample_rate);
      READ_LONG(sp->low_freq);
      READ_LONG(sp->high_freq);
      READ_LONG(sp->root_freq);
      skip(fp, 2); /* Why have a "root frequency" and then "tuning"?? */
      
      READ_CHAR(tmp[0]);

      if (panning==-1)
	sp->panning = (tmp[0] * 8 + 4) & 0x7f;
      else
	sp->panning=(uint8)(panning & 0x7F);

      /* envelope, tremolo, and vibrato */
      if (18 != fread(tmp, 1, 18, fp)) goto fail; 

      if (!tmp[13] || !tmp[14])
	{
	  sp->tremolo_sweep_increment=
	    sp->tremolo_phase_increment=sp->tremolo_depth=0;
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo");
	}
      else
	{
	  sp->tremolo_sweep_increment=convert_tremolo_sweep(tmp[12]);
	  sp->tremolo_phase_increment=convert_tremolo_rate(tmp[13]);
	  sp->tremolo_depth=tmp[14];
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
	       " * tremolo: sweep %d, phase %d, depth %d",
	       sp->tremolo_sweep_increment, sp->tremolo_phase_increment,
	       sp->tremolo_depth);
	}

      if (!tmp[16] || !tmp[17])
	{
	  sp->vibrato_sweep_increment=
	    sp->vibrato_control_ratio=sp->vibrato_depth=0;
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato");
	}
      else
	{
	  sp->vibrato_control_ratio=convert_vibrato_rate(tmp[16]);
	  sp->vibrato_sweep_increment=
	    convert_vibrato_sweep(tmp[15], sp->vibrato_control_ratio);
	  sp->vibrato_depth=tmp[17];
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG,
	       " * vibrato: sweep %d, ctl %d, depth %d",
	       sp->vibrato_sweep_increment, sp->vibrato_control_ratio,
	       sp->vibrato_depth);

	}

      READ_CHAR(sp->modes);

      skip(fp, 40); /* skip the useless scale frequency, scale factor
		       (what's it mean?), and reserved space */

      /* Mark this as a fixed-pitch instrument if such a deed is desired. */
      if (note_to_use!=-1)
	sp->note_to_use=(uint8)(note_to_use);
      else
	sp->note_to_use=0;
      
      /* seashore.pat in the Midia patch set has no Sustain. I don't
         understand why, and fixing it by adding the Sustain flag to
         all looped patches probably breaks something else. We do it
         anyway. */
	 
      if (sp->modes & MODES_LOOPING) 
	sp->modes |= MODES_SUSTAIN;

      /* Strip any loops and envelopes we're permitted to */
      if ((strip_loop==1) && 
	  (sp->modes & (MODES_SUSTAIN | MODES_LOOPING | 
			MODES_PINGPONG | MODES_REVERSE)))
	{
	  ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain");
	  sp->modes &=~(MODES_SUSTAIN | MODES_LOOPING | 
			MODES_PINGPONG | MODES_REVERSE);
	}

      if (strip_envelope==1)
	{
	  if (sp->modes & MODES_ENVELOPE)
	    ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
	  sp->modes &= ~MODES_ENVELOPE;
	}
      else if (strip_envelope != 0)
	{
	  /* Have to make a guess. */
	  if (!(sp->modes & (MODES_LOOPING | MODES_PINGPONG | MODES_REVERSE)))
	    {
	      /* No loop? Then what's there to sustain? No envelope needed
		 either... */
	      sp->modes &= ~(MODES_SUSTAIN|MODES_ENVELOPE);
	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
			" - No loop, removing sustain and envelope");
	    }
	  else if (!memcmp(tmp, "??????", 6) || tmp[11] >= 100) 
	    {
	      /* Envelope rates all maxed out? Envelope end at a high "offset"?
		 That's a weird envelope. Take it out. */
	      sp->modes &= ~MODES_ENVELOPE;
	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
			" - Weirdness, removing envelope");
	    }
	  else if (!(sp->modes & MODES_SUSTAIN))
	    {
	      /* No sustain? Then no envelope.  I don't know if this is
		 justified, but patches without sustain usually don't need the
		 envelope either... at least the Gravis ones. They're mostly
		 drums.  I think. */
	      sp->modes &= ~MODES_ENVELOPE;
	      ctl->cmsg(CMSG_INFO, VERB_DEBUG, 
			" - No sustain, removing envelope");
	    }
	}

      for (j=0; j<6; j++)
	{
	  sp->envelope_rate[j]=
	    convert_envelope_rate(tmp[j]);
	  sp->envelope_offset[j]= 
	    convert_envelope_offset(tmp[6+j]);
	}

      /* Then read the sample data */
      sp->data = safe_malloc(sp->data_length);
      if (1 != fread(sp->data, sp->data_length, 1, fp))
	goto fail;
      
      if (!(sp->modes & MODES_16BIT)) /* convert to 16-bit data */
	{
	  int32 i=sp->data_length;
	  uint8 *cp=(uint8 *)(sp->data);
	  uint16 *tmp,*new;
	  tmp=new=safe_malloc(sp->data_length*2);
	  while (i--)
	    *tmp++ = (uint16)(*cp++) << 8;
	  cp=(uint8 *)(sp->data);
	  sp->data = (sample_t *)new;
	  free(cp);
	  sp->data_length *= 2;
	  sp->loop_start *= 2;
	  sp->loop_end *= 2;
	}
#ifndef LITTLE_ENDIAN
      else
	/* convert to machine byte order */
	{
Пример #29
0
Файл: output.c Проект: 1c0n/xbmc
/* mode
  0,1: Default mode.
  2: Remove the directory path of input_filename, then add output_dir.
  3: Replace directory separator characters ('/','\',':') with '_', then add output_dir.
 */
char *create_auto_output_name(const char *input_filename, char *ext_str, char *output_dir, int mode)
{
  char *output_filename;
  char *ext, *p;
  int32 dir_len = 0;
  char ext_str_tmp[65];

  output_filename = (char *)safe_malloc((output_dir?strlen(output_dir):0) + strlen(input_filename) + 6);
  if(output_filename==NULL)
    return NULL;
  output_filename[0] = '\0';
  if(output_dir!=NULL && (mode==2 || mode==3)) {
    strcat(output_filename,output_dir);
    dir_len = strlen(output_filename);
#ifndef __W32__
    if(dir_len>0 && output_filename[dir_len-1]!=PATH_SEP){
#else
      if(dir_len>0 && output_filename[dir_len-1]!='/' && output_filename[dir_len-1]!='\\' && output_filename[dir_len-1]!=':'){
#endif
	strcat(output_filename,PATH_STRING);
	dir_len++;
      }
    }
    strcat(output_filename, input_filename);

    if((ext = strrchr(output_filename, '.')) == NULL)
      ext = output_filename + strlen(output_filename);
    else {
      /* strip ".gz" */
      if(strcasecmp(ext, ".gz") == 0) {
	*ext = '\0';
	if((ext = strrchr(output_filename, '.')) == NULL)
	  ext = output_filename + strlen(output_filename);
      }
    }

    /* replace '\' , '/' or PATH_SEP between '#' and ext */
    p = strrchr(output_filename,'#');
    if(p!=NULL){
      char *p1;
#ifdef _mbsrchr
#define STRCHR(a,b) _mbschr(a,b)
#else
#define STRCHR(a,b) strchr(a,b)
#endif
#ifndef __W32__
      p1 = p + 1;
      while((p1 = STRCHR(p1,PATH_SEP))!=NULL && p1<ext){
        *p1 = '_';
	p1++;
      }
#else
      p1 = p + 1;
      while((p1 = STRCHR(p1,'\\'))!=NULL && p1<ext){
      	*p1 = '_';
	p1++;
      }
      p1 = p;
      while((p1 = STRCHR(p1,'/'))!=NULL && p1<ext){
	*p1 = '_';
	p1++;
      }
#endif
#undef STRCHR
    }

    /* replace '.' and '#' before ext */
    for(p = output_filename; p < ext; p++)
#ifndef __W32__
      if(*p == '.' || *p == '#')
#else
	if(*p == '#')
#endif
	  *p = '_';

    if(mode==2){
      char *p1,*p2,*p3;
#ifndef __W32__
      p = strrchr(output_filename+dir_len,PATH_SEP);
#else
#ifdef _mbsrchr
#define STRRCHR _mbsrchr
#else
#define STRRCHR strrchr
#endif
      p1 = STRRCHR(output_filename+dir_len,'/');
      p2 = STRRCHR(output_filename+dir_len,'\\');
      p3 = STRRCHR(output_filename+dir_len,':');
#undef STRRCHR
      p1>p2 ? (p1>p3 ? (p = p1) : (p = p3)) : (p2>p3 ? (p = p2) : (p = p3));
#endif
      if(p!=NULL){
	for(p1=output_filename+dir_len,p2=p+1; *p2; p1++,p2++)
	  *p1 = *p2;
	*p1 = '\0';
      }
    }

    if(mode==3){
      for(p=output_filename+dir_len; *p; p++)
#ifndef __W32__
	if(*p==PATH_SEP)
#else
	  if(*p=='/' || *p=='\\' || *p==':')
#endif
	    *p = '_';
    }

    if((ext = strrchr(output_filename, '.')) == NULL)
      ext = output_filename + strlen(output_filename);
    if(*ext){
      strncpy(ext_str_tmp,ext_str,64);
      ext_str_tmp[64]=0;
      if(isupper(*(ext + 1))){
	for(p=ext_str_tmp;*p;p++)
	  *p = toupper(*p);
	*p = '\0';
      } else {
	for(p=ext_str_tmp;*p;p++)
	  *p = tolower(*p);
	*p = '\0';
      }
      strcpy(ext+1,ext_str_tmp);
    }
    return output_filename;
}
Пример #30
0
static void
txdb_process_tx_entry(struct txdb      *txdb,
                      const uint256    *txHash,
                      const uint256    *blkHash,
                      const btc_msg_tx *tx,
                      bool             *relevant)
{
    struct txo_entry *txo_entry;
    char hashStr[80];
    uint32 i;
    bool s;

    ASSERT(txdb);
    ASSERT(*relevant == 0);

    uint256_snprintf_reverse(hashStr, sizeof hashStr, txHash);
    Log(LGPFX" processing  %s\n", hashStr);

    /*
     * Look at all the tx referred to by the inputs. If any of these match
     * a txo for the wallet keys, we have a debit.
     */
    for (i = 0; i < tx->in_count; i++) {
        const btc_msg_tx_in *txi = tx->tx_in + i;
        /*
         * Look to see if the txi refers to one of our coins (a known txo). If
         * so, we need to mark it as spent.
         */
        txo_entry = txdb_lookup_txo(&txi->prevTxHash, txi->prevTxOutIdx);
        if (txo_entry == NULL) {
            continue;
        }

        ASSERT(txo_entry->spent == 0);
        txo_entry->spent = 1;
        *relevant = 1;
    }

    /*
     * Analyze all the txo to see if any credit our addresses.
     */
    for (i = 0; i < tx->out_count; i++) {
        char key[32 + 4]; // txHash + txo_idx
        const btc_msg_tx_out *txo = tx->tx_out + i;
        uint160 pub_key;

        if (script_parse_pubkey_hash(txo->scriptPubKey, txo->scriptLength, &pub_key)
                || !wallet_is_pubkey_hash160_mine(btc->wallet, &pub_key)) {
            continue;
        }
        *relevant = 1;

        memcpy(key,  txHash, sizeof(uint256));
        memcpy(key + 32, &i, sizeof(uint32));

        txo_entry = safe_malloc(sizeof *txo_entry);
        txo_entry->spent     = 0;
        txo_entry->value     = txo->value;
        txo_entry->btc_addr  = b58_pubkey_from_uint160(&pub_key);
        txo_entry->outIdx    = i;
        txo_entry->spendable = wallet_is_pubkey_spendable(btc->wallet, &pub_key);
        memcpy(&txo_entry->txHash, txHash,  sizeof *txHash);
        if (blkHash) {
            memcpy(&txo_entry->blkHash, blkHash, sizeof *blkHash);
        } else {
            memset(&txo_entry->blkHash, 0, sizeof txo_entry->blkHash);
        }

        s = hashtable_insert(txdb->hash_txo, key, sizeof key, txo_entry);
        ASSERT(s);
    }
}