示例#1
0
static void
afuser_dd_queue(LogPipe *s, LogMessage *msg, const LogPathOptions *path_options, gpointer user_data)
{
  AFUserDestDriver *self = (AFUserDestDriver *) s;
  gchar buf[8192];
#ifdef HAVE_UTMPX_H
  struct utmpx *ut;
#else
  struct utmp *ut;
#endif
  GString *timestamp;
  time_t now;
  
  now = msg->timestamps[LM_TS_RECVD].tv_sec;
  if (self->disable_until && self->disable_until > now)
    goto finish;
  
  timestamp = g_string_sized_new(0);
  log_stamp_format(&msg->timestamps[LM_TS_STAMP], timestamp, TS_FMT_FULL, -1, 0);
  g_snprintf(buf, sizeof(buf), "%s %s %s\n",
             timestamp->str,
             log_msg_get_value(msg, LM_V_HOST, NULL),
             log_msg_get_value(msg, LM_V_MESSAGE, NULL));
  g_string_free(timestamp, TRUE);
  
  /* NOTE: there's a private implementations of getutent in utils.c on Systems which do not provide one. */
#ifdef HAVE_GETUTXENT
  while ((ut = getutxent()))
#else
  while ((ut = getutent()))
#endif
    {
#if HAVE_MODERN_UTMP
      if (ut->ut_type == USER_PROCESS &&
          ((self->username->len == 1 &&
            self->username->str[0] == '*') ||
           (self->username->len <= sizeof(ut->ut_user) &&
            memcmp(self->username->str, ut->ut_user, self->username->len) == 0))) 
#else
      if ((self->username->len == 1 &&
           self->username->str[0] == '*') ||
          (self->username->len <= sizeof(ut->ut_name) &&
           memcmp(self->username->str, ut->ut_name, self->username->len) == 0)) 
#endif
        {
          gchar line[128];
          gchar *p = line;
          int fd;

          if (ut->ut_line[0] != '/')
            {
              strcpy(line, "/dev/");
              p = line + 5;
            }
          else
            line[0] = 0;
          strncpy(p, ut->ut_line, sizeof(line) - (p - line));
          fd = open(line, O_NOCTTY | O_APPEND | O_WRONLY | O_NONBLOCK);
          if (fd != -1) 
            {
              alarm_set(10);
              if (write(fd, buf, strlen(buf)) < 0 && errno == EINTR && alarm_has_fired())
                {
                  msg_notice("Writing to the user terminal has blocked for 10 seconds, disabling for 10 minutes",
                            evt_tag_str("user", self->username->str),
                            NULL);
                  self->disable_until = now + 600;
                }
              alarm_cancel();
              close(fd);
            }
        }
    }
#if HAVE_UTMPX_H
  endutxent();
#else
  endutent();
#endif
finish:
  log_msg_ack(msg, path_options);
  log_msg_unref(msg);
}
示例#2
0
int
main(int argc, char *argv[])
{
  GString            *comp_info_str;
  GString            *runtime_info_str;
  int                 opt;
DIAG_OFF(cast-qual)
  static const struct option long_options[] = {
      {(char *)"help", no_argument, NULL, 'h'},
      {(char *)"version", no_argument, NULL, 'V'},
      {0, 0, 0, 0 }
  };
DIAG_ON(cast-qual)
  gboolean            do_append          = FALSE;
  gboolean            verbose            = FALSE;
  int                 in_file_count      = 0;
  guint               snaplen            = 0;
#ifdef PCAP_NG_DEFAULT
  int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
#else
  int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
#endif
  int                 frame_type         = -2;
  int                 out_fd;
  merge_in_file_t    *in_files           = NULL, *in_file;
  int                 i;
  struct wtap_pkthdr *phdr, snap_phdr;
  wtap_dumper        *pdh;
  int                 open_err, read_err = 0, write_err, close_err;
  gchar              *err_info, *write_err_info = NULL;
  int                 err_fileno;
  char               *out_filename       = NULL;
  gboolean            got_read_error     = FALSE, got_write_error = FALSE;
  int                 count;

  cmdarg_err_init(mergecap_cmdarg_err, mergecap_cmdarg_err_cont);

#ifdef _WIN32
  arg_list_utf_16to8(argc, argv);
  create_app_running_mutex();
#endif /* _WIN32 */

  /* Get the compile-time version information string */
  comp_info_str = get_compiled_version_info(NULL, get_mergecap_compiled_info);

  /* Get the run-time version information string */
  runtime_info_str = get_runtime_version_info(get_mergecap_runtime_info);

  /* Add it to the information to be reported on a crash. */
  ws_add_crash_info("Mergecap (Wireshark) %s\n"
       "\n"
       "%s"
       "\n"
       "%s",
    get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);

  /* Process the options first */
  while ((opt = getopt_long(argc, argv, "aF:hs:T:vVw:", long_options, NULL)) != -1) {

    switch (opt) {
    case 'a':
      do_append = !do_append;
      break;

    case 'F':
      file_type = wtap_short_string_to_file_type_subtype(optarg);
      if (file_type < 0) {
        fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
                optarg);
        list_capture_types();
        exit(1);
      }
      break;

    case 'h':
      printf("Mergecap (Wireshark) %s\n"
             "Merge two or more capture files into one.\n"
             "See http://www.wireshark.org for more information.\n",
             get_ws_vcs_version_info());
      print_usage(stdout);
      exit(0);
      break;

    case 's':
      snaplen = get_positive_int(optarg, "snapshot length");
      break;

    case 'T':
      frame_type = wtap_short_string_to_encap(optarg);
      if (frame_type < 0) {
        fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
                optarg);
        list_encap_types();
        exit(1);
      }
      break;

    case 'v':
      verbose = TRUE;
      break;

    case 'V':
      show_version("Mergecap (Wireshark)", comp_info_str, runtime_info_str);
      g_string_free(comp_info_str, TRUE);
      g_string_free(runtime_info_str, TRUE);
      exit(0);
      break;

    case 'w':
      out_filename = optarg;
      break;

    case '?':              /* Bad options if GNU getopt */
      switch(optopt) {
      case'F':
        list_capture_types();
        break;
      case'T':
        list_encap_types();
        break;
      default:
        print_usage(stderr);
      }
      exit(1);
      break;
    }
  }

  /* check for proper args; at a minimum, must have an output
   * filename and one input file
   */
  in_file_count = argc - optind;
  if (!out_filename) {
    fprintf(stderr, "mergecap: an output filename must be set with -w\n");
    fprintf(stderr, "          run with -h for help\n");
    return 1;
  }
  if (in_file_count < 1) {
    fprintf(stderr, "mergecap: No input files were specified\n");
    return 1;
  }

  /* open the input files */
  if (!merge_open_in_files(in_file_count, &argv[optind], &in_files,
                           &open_err, &err_info, &err_fileno)) {
    fprintf(stderr, "mergecap: Can't open %s: %s\n", argv[optind + err_fileno],
            wtap_strerror(open_err));
    if (err_info != NULL) {
      fprintf(stderr, "(%s)\n", err_info);
      g_free(err_info);
    }
    return 2;
  }

  if (verbose) {
    for (i = 0; i < in_file_count; i++)
      fprintf(stderr, "mergecap: %s is type %s.\n", argv[optind + i],
              wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
  }

  if (snaplen == 0) {
    /*
     * Snapshot length not specified - default to the maximum of the
     * snapshot lengths of the input files.
     */
    snaplen = merge_max_snapshot_length(in_file_count, in_files);
  }

  /* set the outfile frame type */
  if (frame_type == -2) {
    /*
     * Default to the appropriate frame type for the input files.
     */
    frame_type = merge_select_frame_type(in_file_count, in_files);
    if (verbose) {
      if (frame_type == WTAP_ENCAP_PER_PACKET) {
        /*
         * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
         */
        int first_frame_type, this_frame_type;

        first_frame_type = wtap_file_encap(in_files[0].wth);
        for (i = 1; i < in_file_count; i++) {
          this_frame_type = wtap_file_encap(in_files[i].wth);
          if (first_frame_type != this_frame_type) {
            fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
            fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
            fprintf(stderr, "          %s had type %s (%s)\n",
                    in_files[0].filename,
                    wtap_encap_string(first_frame_type),
                    wtap_encap_short_string(first_frame_type));
            fprintf(stderr, "          %s had type %s (%s)\n",
                    in_files[i].filename,
                    wtap_encap_string(this_frame_type),
                    wtap_encap_short_string(this_frame_type));
            break;
          }
        }
      }
      fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
              wtap_encap_string(frame_type),
              wtap_encap_short_string(frame_type));
    }
  }

  /* open the outfile */
  if (strncmp(out_filename, "-", 2) == 0) {
    /* use stdout as the outfile */
    out_fd = 1 /*stdout*/;
  } else {
    /* open the outfile */
    out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
    if (out_fd == -1) {
      fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
              out_filename, g_strerror(errno));
      exit(1);
    }
  }

  /* prepare the outfile */
  if(file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG ){
    wtapng_section_t *shb_hdr;
    GString *comment_gstr;

    shb_hdr = g_new(wtapng_section_t,1);
    comment_gstr = g_string_new("File created by merging: \n");

    for (i = 0; i < in_file_count; i++) {
      g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
    }
    shb_hdr->section_length = -1;
    /* options */
    shb_hdr->opt_comment   = comment_gstr->str; /* NULL if not available */
    shb_hdr->shb_hardware  = NULL;              /* NULL if not available, UTF-8 string containing the description of the hardware used to create this section. */
    shb_hdr->shb_os        = NULL;              /* NULL if not available, UTF-8 string containing the name of the operating system used to create this section. */
    shb_hdr->shb_user_appl = g_strdup("mergecap"); /* NULL if not available, UTF-8 string containing the name of the application used to create this section. */

    pdh = wtap_dump_fdopen_ng(out_fd, file_type, frame_type, snaplen,
                              FALSE /* compressed */, shb_hdr, NULL /* wtapng_iface_descriptions_t *idb_inf */, &open_err);
    g_string_free(comment_gstr, TRUE);
  } else {
    pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, &open_err);
  }
  if (pdh == NULL) {
    merge_close_in_files(in_file_count, in_files);
    g_free(in_files);
    fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
            wtap_strerror(open_err));
    exit(1);
  }

  /* do the merge (or append) */
  count = 1;
  for (;;) {
    if (do_append)
      in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
                                         &err_info);
    else
      in_file = merge_read_packet(in_file_count, in_files, &read_err,
                                  &err_info);
    if (in_file == NULL) {
      /* EOF */
      break;
    }

    if (read_err != 0) {
      /* I/O error reading from in_file */
      got_read_error = TRUE;
      break;
    }

    if (verbose)
      fprintf(stderr, "Record: %d\n", count++);

    /* We simply write it, perhaps after truncating it; we could do other
     * things, like modify it. */
    phdr = wtap_phdr(in_file->wth);
    if (snaplen != 0 && phdr->caplen > snaplen) {
      snap_phdr = *phdr;
      snap_phdr.caplen = snaplen;
      phdr = &snap_phdr;
    }

    if (!wtap_dump(pdh, phdr, wtap_buf_ptr(in_file->wth), &write_err, &write_err_info)) {
      got_write_error = TRUE;
      break;
    }
  }

  merge_close_in_files(in_file_count, in_files);
  if (!got_write_error) {
    if (!wtap_dump_close(pdh, &write_err))
      got_write_error = TRUE;
  } else {
    /*
     * We already got a write error; no need to report another
     * write error on close.
     *
     * Don't overwrite the earlier write error.
     */
    (void)wtap_dump_close(pdh, &close_err);
  }

  if (got_read_error) {
    /*
     * Find the file on which we got the error, and report the error.
     */
    for (i = 0; i < in_file_count; i++) {
      if (in_files[i].state == GOT_ERROR) {
        fprintf(stderr, "mergecap: Error reading %s: %s\n",
                in_files[i].filename, wtap_strerror(read_err));
        if (err_info != NULL) {
          fprintf(stderr, "(%s)\n", err_info);
          g_free(err_info);
        }
      }
    }
  }

  if (got_write_error) {
    switch (write_err) {

    case WTAP_ERR_UNWRITABLE_ENCAP:
      /*
       * This is a problem with the particular frame we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the frame number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    case WTAP_ERR_PACKET_TOO_LARGE:
      /*
       * This is a problem with the particular frame we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the frame number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Frame %u of \"%s\" is too large for a \"%s\" file.\n",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    case WTAP_ERR_UNWRITABLE_REC_TYPE:
      /*
       * This is a problem with the particular record we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the record number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    case WTAP_ERR_UNWRITABLE_REC_DATA:
      /*
       * This is a problem with the particular record we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the record number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type),
              write_err_info != NULL ? write_err_info : "no information supplied");
      g_free(write_err_info);
      break;

    default:
      fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
              wtap_strerror(write_err));
      break;
    }
  }

  g_free(in_files);

  return (!got_read_error && !got_write_error) ? 0 : 2;
}
示例#3
0
INIFile * open_ini_file (VFSFile * file)
{
    GHashTable *ini_file = NULL;
    GHashTable *section = NULL;
    GString *section_name, *key_name, *value;
    gpointer section_hash, key_hash;
    gsize off = 0;

    gint64 filesize = vfs_fsize (file);
    if (filesize < 1)
        return NULL;

    gchar * buffer = g_malloc (filesize);
    filesize = vfs_fread (buffer, 1, filesize, file);

    section_name = g_string_new("");
    key_name = g_string_new(NULL);
    value = g_string_new(NULL);

    ini_file =
        g_hash_table_new_full(NULL, NULL, NULL, close_ini_file_free_section);
    section =
        g_hash_table_new_full(NULL, NULL, NULL, close_ini_file_free_value);
    /* make a nameless section which should store all entries that are not
     * embedded in a section */
    section_hash = GINT_TO_POINTER(g_string_hash(section_name));
    g_hash_table_insert(ini_file, section_hash, section);

    while (off < filesize)
    {
        /* ignore the following characters */
        if (buffer[off] == '\r' || buffer[off] == '\n' || buffer[off] == ' '
            || buffer[off] == '\t')
        {
            if (buffer[off] == '\n')
            {
                g_string_free(key_name, TRUE);
                g_string_free(value, TRUE);
                key_name = g_string_new(NULL);
                value = g_string_new(NULL);
            }

            off++;
            continue;
        }

        /* if we encounter a possible section statement */
        if (buffer[off] == '[')
        {
            g_string_free(section_name, TRUE);
            section_name = g_string_new(NULL);
            off++;

            if (off >= filesize)
                goto return_sequence;

            while (buffer[off] != ']')
            {
                /* if the section statement has not been closed before a
                 * linebreak */
                if (buffer[off] == '\n')
                    break;

                g_string_append_c(section_name, buffer[off]);
                off++;
                if (off >= filesize)
                    goto return_sequence;
            }
            if (buffer[off] == '\n')
                continue;
            if (buffer[off] == ']')
            {
                off++;
                if (off >= filesize)
                    goto return_sequence;

                strip_lower_string(section_name);
                section_hash = GINT_TO_POINTER(g_string_hash(section_name));

                /* if this section already exists, we don't make a new one,
                 * but reuse the old one */
                if (g_hash_table_lookup(ini_file, section_hash) != NULL)
                    section = g_hash_table_lookup(ini_file, section_hash);
                else
                {
                    section =
                        g_hash_table_new_full(NULL, NULL, NULL,
                                              close_ini_file_free_value);
                    g_hash_table_insert(ini_file, section_hash, section);
                }

                continue;
            }
        }

        if (buffer[off] == '=')
        {
            off++;
            if (off >= filesize)
                goto return_sequence;

            while (buffer[off] != '\n' && buffer[off] != '\r')
            {
                g_string_append_c(value, buffer[off]);
                off++;
                if (off >= filesize)
                    break;
            }

            strip_lower_string(key_name);
            key_hash = GINT_TO_POINTER(g_string_hash(key_name));
            strip_string(value);

            if (key_name->len > 0 && value->len > 0)
                g_hash_table_insert(section, key_hash, g_strdup(value->str));
        }
        else
        {
            g_string_append_c(key_name, buffer[off]);
            off++;
            if (off >= filesize)
                goto return_sequence;
        }
    }

  return_sequence:
    g_string_free(section_name, TRUE);
    g_string_free(key_name, TRUE);
    g_string_free(value, TRUE);
    g_free(buffer);
    return ini_file;
}
示例#4
0
int
main (int argc, char **argv)
{
  static int want_my_version = 0;
  static int want_version = 0;
  static int want_libs = 0;
  static int want_cflags = 0;
  static int want_l_libs = 0;
  static int want_L_libs = 0;
  static int want_other_libs = 0;
  static int want_I_cflags = 0;
  static int want_other_cflags = 0;
  static int want_list = 0;
  static int want_static_lib_list = ENABLE_INDIRECT_DEPS;
  static int want_short_errors = 0;
  static int want_uninstalled = 0;
  static char *variable_name = NULL;
  static int want_exists = 0;
  static int want_provides = 0;
  static int want_requires = 0;
  static int want_requires_private = 0;
  static char *required_atleast_version = NULL;
  static char *required_exact_version = NULL;
  static char *required_max_version = NULL;
  static char *required_pkgconfig_version = NULL;
  static int want_silence_errors = 0;
  static int want_variable_list = 0;
  GString *str;
  GSList *packages = NULL;
  char *search_path;
  char *pcbuilddir;
  gboolean need_newline;
  FILE *log = NULL;
  GError *error = NULL;
  GOptionContext *opt_context;

  GOptionEntry options_table[] = {
    { "version", 0, 0, G_OPTION_ARG_NONE, &want_my_version,
      "output version of pkg-config", NULL },
    { "modversion", 0, 0, G_OPTION_ARG_NONE, &want_version,
      "output version for package", NULL },
    { "atleast-pkgconfig-version", 0, 0, G_OPTION_ARG_STRING,
      &required_pkgconfig_version,
      "require given version of pkg-config", "VERSION" },
    { "libs", 0, 0, G_OPTION_ARG_NONE, &want_libs,
      "output all linker flags", NULL },
    { "static", 0, 0, G_OPTION_ARG_NONE, &want_static_lib_list,
      "output linker flags for static linking", NULL },
    { "short-errors", 0, 0, G_OPTION_ARG_NONE, &want_short_errors,
      "print short errors", NULL },
    { "libs-only-l", 0, 0, G_OPTION_ARG_NONE, &want_l_libs,
      "output -l flags", NULL },
    { "libs-only-other", 0, 0, G_OPTION_ARG_NONE, &want_other_libs,
      "output other libs (e.g. -pthread)", NULL },
    { "libs-only-L", 0, 0, G_OPTION_ARG_NONE, &want_L_libs,
      "output -L flags", NULL },
    { "cflags", 0, 0, G_OPTION_ARG_NONE, &want_cflags,
      "output all pre-processor and compiler flags", NULL },
    { "cflags-only-I", 0, 0, G_OPTION_ARG_NONE, &want_I_cflags,
      "output -I flags", NULL },
    { "cflags-only-other", 0, 0, G_OPTION_ARG_NONE, &want_other_cflags,
      "output cflags not covered by the cflags-only-I option", NULL },
    { "variable", 0, 0, G_OPTION_ARG_STRING, &variable_name,
      "get the value of variable named NAME", "NAME" },
    { "define-variable", 0, 0, G_OPTION_ARG_CALLBACK, &define_variable_cb,
      "set variable NAME to VALUE", "NAME=VALUE" },
    { "exists", 0, 0, G_OPTION_ARG_NONE, &want_exists,
      "return 0 if the module(s) exist", NULL },
    { "print-variables", 0, 0, G_OPTION_ARG_NONE, &want_variable_list,
      "output list of variables defined by the module", NULL },
    { "uninstalled", 0, 0, G_OPTION_ARG_NONE, &want_uninstalled,
      "return 0 if the uninstalled version of one or more module(s) "
      "or their dependencies will be used", NULL },
    { "atleast-version", 0, 0, G_OPTION_ARG_STRING, &required_atleast_version,
      "return 0 if the module is at least version VERSION", "VERSION" },
    { "exact-version", 0, 0, G_OPTION_ARG_STRING, &required_exact_version,
      "return 0 if the module is at exactly version VERSION", "VERSION" },
    { "max-version", 0, 0, G_OPTION_ARG_STRING, &required_max_version,
      "return 0 if the module is at no newer than version VERSION", "VERSION" },
    { "list-all", 0, 0, G_OPTION_ARG_NONE, &want_list,
      "list all known packages", NULL },
    { "debug", 0, 0, G_OPTION_ARG_NONE, &want_debug_spew,
      "show verbose debug information", NULL },
    { "print-errors", 0, 0, G_OPTION_ARG_NONE, &want_verbose_errors,
      "show verbose information about missing or conflicting packages,"
      "default if --cflags or --libs given on the command line", NULL },
    { "silence-errors", 0, 0, G_OPTION_ARG_NONE, &want_silence_errors,
      "be silent about errors (default unless --cflags or --libs"
      "given on the command line)", NULL },
    { "errors-to-stdout", 0, 0, G_OPTION_ARG_NONE, &want_stdout_errors,
      "print errors from --print-errors to stdout not stderr", NULL },
    { "print-provides", 0, 0, G_OPTION_ARG_NONE, &want_provides,
      "print which packages the package provides", NULL },
    { "print-requires", 0, 0, G_OPTION_ARG_NONE, &want_requires,
      "print which packages the package requires", NULL },
    { "print-requires-private", 0, 0, G_OPTION_ARG_NONE, &want_requires_private,
      "print which packages the package requires for static linking", NULL },
#ifdef G_OS_WIN32
    { "dont-define-prefix", 0, 0, G_OPTION_ARG_NONE, &dont_define_prefix,
      "don't try to override the value of prefix for each .pc file found with "
      "a guesstimated value based on the location of the .pc file", NULL },
    { "prefix-variable", 0, 0, G_OPTION_ARG_STRING, &prefix_variable,
      "set the name of the variable that pkg-config automatically sets",
      "PREFIX" },
    { "msvc-syntax", 0, 0, G_OPTION_ARG_NONE, &msvc_syntax,
      "output -l and -L flags for the Microsoft compiler (cl)", NULL },
#endif
    { NULL, 0, 0, 0, NULL, NULL, NULL }
  };

  /* This is here so that we get debug spew from the start,
   * during arg parsing
   */
  if (getenv ("PKG_CONFIG_DEBUG_SPEW"))
    {
      want_debug_spew = TRUE;
      want_verbose_errors = TRUE;
      want_silence_errors = FALSE;
      debug_spew ("PKG_CONFIG_DEBUG_SPEW variable enabling debug spew\n");
    }


  /* Get the built-in search path */
  init_pc_path ();
  if (pkg_config_pc_path == NULL)
    {
      /* Even when we override the built-in search path, we still use it later
       * to add pc_path to the virtual pkg-config package.
       */
      verbose_error ("Failed to get default search path\n");
      exit (1);
    }

  search_path = getenv ("PKG_CONFIG_PATH");
  if (search_path) 
    {
      add_search_dirs(search_path, G_SEARCHPATH_SEPARATOR_S);
    }
  if (getenv("PKG_CONFIG_LIBDIR") != NULL) 
    {
      add_search_dirs(getenv("PKG_CONFIG_LIBDIR"), G_SEARCHPATH_SEPARATOR_S);
    }
  else
    {
      add_search_dirs(pkg_config_pc_path, G_SEARCHPATH_SEPARATOR_S);
    }

  pcsysrootdir = getenv ("PKG_CONFIG_SYSROOT_DIR");
  if (pcsysrootdir)
    {
      define_global_variable ("pc_sysrootdir", pcsysrootdir);
    }
  else
    {
      define_global_variable ("pc_sysrootdir", "/");
    }

  pcbuilddir = getenv ("PKG_CONFIG_TOP_BUILD_DIR");
  if (pcbuilddir)
    {
      define_global_variable ("pc_top_builddir", pcbuilddir);
    }
  else
    {
      /* Default appropriate for automake */
      define_global_variable ("pc_top_builddir", "$(top_builddir)");
    }

  if (getenv ("PKG_CONFIG_DISABLE_UNINSTALLED"))
    {
      debug_spew ("disabling auto-preference for uninstalled packages\n");
      disable_uninstalled = TRUE;
    }

  /* Parse options */
  opt_context = g_option_context_new (NULL);
  g_option_context_add_main_entries (opt_context, options_table, NULL);
  if (!g_option_context_parse(opt_context, &argc, &argv, &error))
    {
      fprintf (stderr, "%s\n", error->message);
      return 1;
    }


  /* Error printing is determined as follows:
   *     - for --cflags, --libs, etc. it's on by default
   *       and --silence-errors can turn it off
   *     - for --exists, --max-version, etc. and no options
   *       at all, it's off by default and --print-errors
   *       will turn it on
   */

  if (want_my_version ||
      want_version ||
      want_libs ||
      want_cflags ||
      want_l_libs ||
      want_L_libs ||
      want_other_libs ||
      want_I_cflags ||
      want_other_cflags ||
      want_list ||
      want_variable_list)
    {
      debug_spew ("Error printing enabled by default due to use of --version, --libs, --cflags, --libs-only-l, --libs-only-L, --libs-only-other, --cflags-only-I, --cflags-only-other or --list. Value of --silence-errors: %d\n", want_silence_errors);

      if (want_silence_errors && getenv ("PKG_CONFIG_DEBUG_SPEW") == NULL)
        want_verbose_errors = FALSE;
      else
        want_verbose_errors = TRUE;
    }
  else
    {
      debug_spew ("Error printing disabled by default, value of --print-errors: %d\n",
                  want_verbose_errors);

      /* Leave want_verbose_errors unchanged, reflecting --print-errors */
    }

  if (want_verbose_errors)
    debug_spew ("Error printing enabled\n");
  else
    debug_spew ("Error printing disabled\n");

  if (want_static_lib_list)
    enable_private_libs();
  else
    disable_private_libs();

  /* honor Requires.private if any Cflags are requested or any static
   * libs are requested */

  if (want_I_cflags || want_other_cflags || want_cflags ||
      want_requires_private || want_exists ||
      (want_static_lib_list && (want_libs || want_l_libs || want_L_libs)))
    enable_requires_private();

  /* ignore Requires if no Cflags or Libs are requested */

  if (!want_I_cflags && !want_other_cflags && !want_cflags &&
      !want_libs && !want_l_libs && !want_L_libs && !want_requires &&
      !want_exists)
    disable_requires();

  if (want_my_version)
    {
      printf ("%s\n", VERSION);
      return 0;
    }

  if (required_pkgconfig_version)
    {
      if (compare_versions (VERSION, required_pkgconfig_version) >= 0)
        return 0;
      else
        return 1;
    }

  package_init ();

  if (want_list)
    {
      print_package_list ();
      return 0;
    }

  /* Collect packages from remaining args */
  str = g_string_new ("");
  while (argc > 1)
    {
      argc--;
      argv++;

      g_string_append (str, *argv);
      g_string_append (str, " ");
    }

  g_option_context_free (opt_context);

  g_strstrip (str->str);

  if (getenv("PKG_CONFIG_LOG") != NULL)
    {
      log = fopen (getenv ("PKG_CONFIG_LOG"), "a");
      if (log == NULL)
	{
	  fprintf (stderr, "Cannot open log file: %s\n",
		   getenv ("PKG_CONFIG_LOG"));
	  exit (1);
	}
    }

  {
    gboolean failed = FALSE;
    GSList *reqs;
    GSList *iter;

    reqs = parse_module_list (NULL, str->str,
                              "(command line arguments)");

    iter = reqs;

    while (iter != NULL)
      {
        Package *req;
        RequiredVersion *ver = iter->data;

	/* override requested versions with cmdline options */
	if (required_exact_version)
	  {
	    g_free (ver->version);
	    ver->comparison = EQUAL;
	    ver->version = g_strdup (required_exact_version);
	  }
	else if (required_atleast_version)
	  {
	    g_free (ver->version);
	    ver->comparison = GREATER_THAN_EQUAL;
	    ver->version = g_strdup (required_atleast_version);
	  }
	else if (required_max_version)
	  {
	    g_free (ver->version);
	    ver->comparison = LESS_THAN_EQUAL;
	    ver->version = g_strdup (required_max_version);
	  }

        if (want_short_errors)
          req = get_package_quiet (ver->name);
        else
          req = get_package (ver->name);

	if (log != NULL)
	  {
	    if (req == NULL)
	      fprintf (log, "%s NOT-FOUND", ver->name);
	    else
	      fprintf (log, "%s %s %s", ver->name,
		       comparison_to_str (ver->comparison),
		       (ver->version == NULL) ? "(null)" : ver->version);
	    fprintf (log, "\n");
	  }

        if (req == NULL)
          {
            failed = TRUE;
            verbose_error ("No package '%s' found\n", ver->name);
            goto nextiter;
          }

        if (!version_test (ver->comparison, req->version, ver->version))
          {
            failed = TRUE;
            verbose_error ("Requested '%s %s %s' but version of %s is %s\n",
                           ver->name,
                           comparison_to_str (ver->comparison),
                           ver->version,
                           req->name,
                           req->version);

	    if (req->url)
	      verbose_error ("You may find new versions of %s at %s\n",
			     req->name, req->url);

            goto nextiter;
          }

        packages = g_slist_prepend (packages, req);

      nextiter:
        iter = g_slist_next (iter);
      }

    if (log != NULL)
      {
	fclose (log);
      }

    if (failed) {
      return 1;
    }

  if (want_variable_list)
    {
      GSList *tmp;
      tmp = packages;
      while (tmp != NULL)
        {
          Package *pkg = tmp->data;
          g_hash_table_foreach(pkg->vars,
                               &print_hashtable_key,
                               NULL);
          tmp = g_slist_next (tmp);
          if (tmp) printf ("\n");
        }
      need_newline = FALSE;
    }

  }

  g_string_free (str, TRUE);

  packages = g_slist_reverse (packages);

  if (packages == NULL)
    {
      fprintf (stderr, "Must specify package names on the command line\n");

      exit (1);
    }

  if (want_exists)
    return 0; /* if we got here, all the packages existed. */

  if (want_uninstalled)
    {
      /* See if > 0 pkgs (including dependencies recursively) were uninstalled */
      GSList *tmp;
      tmp = packages;
      while (tmp != NULL)
        {
          Package *pkg = tmp->data;

          if (pkg_uninstalled (pkg))
            return 0;

          tmp = g_slist_next (tmp);
        }

      return 1;
    }

  if (want_version)
    {
      GSList *tmp;
      tmp = packages;
      while (tmp != NULL)
        {
          Package *pkg = tmp->data;

          printf ("%s\n", pkg->version);

          tmp = g_slist_next (tmp);
        }
    }

 if (want_provides)
   {
     GSList *tmp;
     tmp = packages;
     while (tmp != NULL)
       {
         Package *pkg = tmp->data;
         char *key;
         key = pkg->key;
         while (*key == '/')
           key++;
         if (strlen(key) > 0)
           printf ("%s = %s\n", key, pkg->version);
         tmp = g_slist_next (tmp);
       }
   }

  if (want_requires)
    {
      GSList *pkgtmp;
      for (pkgtmp = packages; pkgtmp != NULL; pkgtmp = g_slist_next (pkgtmp))
        {
          Package *pkg = pkgtmp->data;
          GSList *reqtmp;

          /* process Requires: */
          for (reqtmp = pkg->requires; reqtmp != NULL; reqtmp = g_slist_next (reqtmp))
            {
              Package *deppkg = reqtmp->data;
              RequiredVersion *req;
              req = g_hash_table_lookup(pkg->required_versions, deppkg->key);
              if ((req == NULL) || (req->comparison == ALWAYS_MATCH))
                printf ("%s\n", deppkg->key);
              else
                printf ("%s %s %s\n", deppkg->key,
                  comparison_to_str(req->comparison),
                  req->version);
            }
        }
    }
  if (want_requires_private)
    {
      GSList *pkgtmp;
      for (pkgtmp = packages; pkgtmp != NULL; pkgtmp = g_slist_next (pkgtmp))
        {
          Package *pkg = pkgtmp->data;
          GSList *reqtmp;
          /* process Requires.private: */
          for (reqtmp = pkg->requires_private; reqtmp != NULL; reqtmp = g_slist_next (reqtmp))
            {

              Package *deppkg = reqtmp->data;
              RequiredVersion *req;

              if (g_slist_find (pkg->requires, reqtmp->data))
                continue;

              req = g_hash_table_lookup(pkg->required_versions, deppkg->key);
              if ((req == NULL) || (req->comparison == ALWAYS_MATCH))
                printf ("%s\n", deppkg->key);
              else
                printf ("%s %s %s\n", deppkg->key,
                  comparison_to_str(req->comparison),
                  req->version);
            }
        }
    }
  
  /* Print all flags; then print a newline at the end. */
  need_newline = FALSE;

  if (variable_name)
    {
      char *str = packages_get_var (packages, variable_name);
      printf ("%s", str);
      g_free (str);
      need_newline = TRUE;
    }

  if (want_I_cflags)
    {
      char *str = packages_get_I_cflags (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }
  else if (want_other_cflags)
    {
      char *str = packages_get_other_cflags (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }
  else if (want_cflags)
    {
      char *str = packages_get_all_cflags (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }

  if (want_l_libs)
    {
      char *str = packages_get_l_libs (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }
  else if (want_L_libs)
    {
      char *str = packages_get_L_libs (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }
  else if (want_other_libs)
    {
      char *str = packages_get_other_libs (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }
  else if (want_libs)
    {
      char *str = packages_get_all_libs (packages);
      printf ("%s ", str);
      g_free (str);
      need_newline = TRUE;
    }

  if (need_newline)
    printf ("\n");

  return 0;
}
static gboolean
parseLine (CSVImporter *gci,
           EContact *contact,
           gchar *buf)
{
	const gchar *pptr = buf, *field_text;
	gchar *do_free = NULL;
	GString *value;
	gint ii = 0, idx;
	gint flags = 0;
	gint contact_field;
	EContactAddress *home_address = NULL, *work_address = NULL, *other_address = NULL;
	EContactDate *bday = NULL;
	GString *home_street, *work_street, *other_street;
	home_street = g_string_new ("");
	work_street = g_string_new ("");
	other_street = g_string_new ("");
	home_address = g_new0 (EContactAddress, 1);
	work_address = g_new0 (EContactAddress, 1);
	other_address = g_new0 (EContactAddress, 1);
	bday = g_new0 (EContactDate, 1);

	if (!g_utf8_validate (pptr, -1, NULL)) {
		do_free = g_convert (pptr, -1, "UTF-8", "ISO-8859-1", NULL, NULL, NULL);
		pptr = do_free;
	}

	while (value = parseNextValue (&pptr), value != NULL) {
		contact_field = NOMAP;
		flags = FLAG_INVALID;
		field_text = NULL;

		idx = ii;
		if (gci->fields_map) {
			gpointer found;

			found = g_hash_table_lookup (
				gci->fields_map, GINT_TO_POINTER (idx));

			if (found == NULL) {
				g_warning ("%s: No map for index %d, skipping it", G_STRFUNC, idx);
				idx = -1;
			} else {
				idx = GPOINTER_TO_INT (found) - 1;
			}
		}

		if (importer == OUTLOOK_IMPORTER) {
			if (idx >= 0 && idx < G_N_ELEMENTS (csv_fields_outlook)) {
				contact_field = csv_fields_outlook[idx].contact_field;
				flags = csv_fields_outlook[idx].flags;
				field_text = csv_fields_outlook[idx].csv_attribute;
			}
		}
		else if (importer == MOZILLA_IMPORTER) {
			if (idx >= 0 && idx < G_N_ELEMENTS (csv_fields_mozilla)) {
				contact_field = csv_fields_mozilla[idx].contact_field;
				flags = csv_fields_mozilla[idx].flags;
				field_text = csv_fields_mozilla[idx].csv_attribute;
			}
		}
		else {
			if (idx >= 0 && idx < G_N_ELEMENTS (csv_fields_evolution)) {
				contact_field = csv_fields_evolution[idx].contact_field;
				flags = csv_fields_evolution[idx].flags;
				field_text = csv_fields_evolution[idx].csv_attribute;
			}
		}

		if (*value->str) {
			if (contact_field != NOMAP) {
				if (importer == OUTLOOK_IMPORTER || importer == MOZILLA_IMPORTER) {
					e_contact_set (contact, contact_field, value->str);
				} else {
					if (contact_field == E_CONTACT_WANTS_HTML)
						e_contact_set (
							contact, contact_field,
							GINT_TO_POINTER (
							g_ascii_strcasecmp (
							value->str, "TRUE") == 0));
					else
						e_contact_set (contact, contact_field, value->str);
				}
			}
			else {
				switch (flags) {

				case FLAG_HOME_ADDRESS | FLAG_STREET:
					if (strlen (home_street->str) != 0) {
						home_street = g_string_append (home_street, ",\n");
					}
					home_street = g_string_append (home_street, value->str);
					break;
				case FLAG_HOME_ADDRESS | FLAG_CITY:
					home_address->locality = g_strdup (value->str);
					break;
				case FLAG_HOME_ADDRESS | FLAG_STATE:
					home_address->region = g_strdup (value->str);
					break;
				case FLAG_HOME_ADDRESS | FLAG_POSTAL_CODE:
					home_address->code = g_strdup (value->str);
					break;
				case FLAG_HOME_ADDRESS | FLAG_POBOX:
					home_address->po = g_strdup (value->str);
					break;
				case FLAG_HOME_ADDRESS | FLAG_COUNTRY:
					home_address->country = g_strdup (value->str);
					break;

				case FLAG_WORK_ADDRESS | FLAG_STREET:
					if (strlen (work_street->str) != 0) {
						work_street = g_string_append (work_street, ",\n");
					}
					work_street = g_string_append (work_street, value->str);
					break;
				case FLAG_WORK_ADDRESS | FLAG_CITY:
					work_address->locality = g_strdup (value->str);
					break;
				case FLAG_WORK_ADDRESS | FLAG_STATE:
					work_address->region = g_strdup (value->str);
					break;
				case FLAG_WORK_ADDRESS | FLAG_POSTAL_CODE:
					work_address->code = g_strdup (value->str);
					break;
				case FLAG_WORK_ADDRESS | FLAG_POBOX:
					work_address->po = g_strdup (value->str);
					break;
				case FLAG_WORK_ADDRESS | FLAG_COUNTRY:
					work_address->country = g_strdup (value->str);
					break;

				case FLAG_OTHER_ADDRESS | FLAG_STREET:
					if (strlen (other_street->str) != 0) {
						other_street = g_string_append (other_street, ",\n");
					}
					other_street = g_string_append (other_street, value->str);
					break;
				case FLAG_OTHER_ADDRESS | FLAG_CITY:
					other_address->locality = g_strdup (value->str);
					break;
				case FLAG_OTHER_ADDRESS | FLAG_STATE:
					other_address->region = g_strdup (value->str);
					break;
				case FLAG_OTHER_ADDRESS | FLAG_POSTAL_CODE:
					other_address->code = g_strdup (value->str);
					break;
				case FLAG_OTHER_ADDRESS | FLAG_POBOX:
					other_address->po = g_strdup (value->str);
					break;
				case FLAG_OTHER_ADDRESS | FLAG_COUNTRY:
					other_address->country = g_strdup (value->str);
					break;

				case FLAG_DATE_BDAY:
					e_contact_set (
						contact,
						E_CONTACT_BIRTH_DATE,
						date_from_string (value->str));
					break;

				case FLAG_DATE_ANNIVERSARY:
					e_contact_set (
						contact,
						E_CONTACT_ANNIVERSARY,
						date_from_string (value->str));
					break;

				case FLAG_BIRTH_DAY:
					bday->day = atoi (value->str);
					break;
				case FLAG_BIRTH_YEAR:
					bday->year = atoi (value->str);
					break;
				case FLAG_BIRTH_MONTH:
					bday->month = atoi (value->str);
					break;

				case FLAG_INVALID:
					break;

				default:
					add_to_notes (contact, field_text, value->str);

				}
			}
		}
		ii++;
		g_string_free (value, TRUE);
	}
	if (strlen (home_street->str) != 0)
		home_address->street = g_strdup (home_street->str);
	if (strlen (work_street->str) != 0)
		work_address->street = g_strdup (work_street->str);
	if (strlen (other_street->str) != 0)
		other_address->street = g_strdup (other_street->str);
	g_string_free (home_street, TRUE);
	g_string_free (work_street, TRUE);
	g_string_free (other_street, TRUE);

	if (home_address->locality || home_address->country ||
	   home_address->code || home_address->region || home_address->street)
		e_contact_set (contact, E_CONTACT_ADDRESS_HOME, home_address);
	if (work_address->locality || work_address->country ||
	   work_address->code || work_address->region || work_address->street)
		e_contact_set (contact, E_CONTACT_ADDRESS_WORK, work_address);
	if (other_address->locality || other_address->country ||
	   other_address->code || other_address->region || other_address->street)
		e_contact_set (contact, E_CONTACT_ADDRESS_OTHER, other_address);

	if (importer != OUTLOOK_IMPORTER) {
		if (bday->day || bday->year || bday->month)
			e_contact_set (contact, E_CONTACT_BIRTH_DATE, bday);
	}

	g_free (do_free);

	return TRUE;
}
示例#6
0
/*!
 * Read a QMP message.
 *
 * \param socket \c GSocket to use.
 * \param expected_count Number of messages to try to receive.
 * \param[out] msgs List of received messages (which are of
 *   type \c GString).
 * \param[out] count Number of messages saved in \p msgs.
 * \return \c true on success, else \c false.
 */
static gboolean
clr_oci_qmp_msg_recv (GSocket *socket,
		gsize expected_count,
		GSList **msgs,
		gsize *count)
{
	gboolean     ret = false;
	gchar        buffer[CLR_OCI_NET_BUF_SIZE];
	gsize        total = 0;
	gssize       bytes;
	gssize       msg_len;
	GError      *error = NULL;
	GString     *msg = NULL;
	GString     *received = NULL;
	gchar       *p;

	g_assert (socket);
	g_assert (expected_count);
	g_assert (msgs);
	g_assert (count);

	g_debug ("client expects %lu message%s",
			expected_count,
			expected_count == 1 ? "" : "s");

	do {
		/* reset */
		memset (buffer, '\0', CLR_OCI_NET_BUF_SIZE);

		/* read a chunk */
		bytes = g_socket_receive (socket, buffer, CLR_OCI_NET_BUF_SIZE,
				NULL, &error);

		if (bytes <= 0) {
			g_critical ("client failed to receive: %s",
					error->message);
			g_error_free (error);
			goto out;
		}

		/* save the chunk */
		if (! received) {
			received = g_string_new_len (buffer, bytes);
		} else {
			g_string_append_len (received, buffer, bytes);
		}

		total += (gsize)bytes;

		while (true) {
			if (! received->len) {
				/* All the data read so far has been consumed */
				break;
			}

			/* Check for end of message marker to determine if a
			 * complete message has been received yet.
			 */
			p = g_strstr_len (received->str, (gssize)total,
					CLR_OCI_MSG_SEPARATOR);
			if (! p) {
				/* No complete message to operate on */
				break;
			}

			/* We now have (*atleast* !!) one complete message to handle */

			/* Calculate the length of the message */
			msg_len = p - received->str;

			/* Save the message */
			msg = g_string_new_len (received->str, msg_len);

			/* Add the the complete message to the list */
			*msgs = g_slist_append (*msgs, msg);
			(*count)++;

			g_debug ("client read message %lu '%s' (len=%lu)",
					(unsigned long int)*count,
					msg->str,
					msg->len);

			/* Remove the handled data
			 * (including the message separator).
			 */
			g_string_erase (received, 0,
					(gssize)
					((gsize)msg_len + sizeof (CLR_OCI_MSG_SEPARATOR)-1));

			/* Get ready to potentially receive a new
			 * message (caller is responsible for freeing the list).
			 */
			msg = NULL;
		}

		if (*count == expected_count) {
			g_debug ("found expected number of messages (%lu)",
					(unsigned long int)expected_count);
			break;
		}
	} while (true);

	/* All complete messages should have been added to the list */
	g_assert (! msg);

	/* All received data should have been handled */
	g_assert (! received->len);

	/* clean up */
	g_string_free (received, true);

	g_debug ("client received %lu message%s "
			"(expected %lu) in %lu bytes",
			(unsigned long int)*count,
			*count == 1 ? "" : "s",
			(unsigned long int)expected_count,
			(unsigned long int)total);

	ret = *count == expected_count;

out:
	return ret;
}
示例#7
0
END_TEST

START_TEST(test_imap_get_envelope)
{
	DbmailMessage *message;
	char *result, *expect;
	GString *s;
	
	expect = g_new0(char, 1024);
	
	/* text/plain */
	message = dbmail_message_new();
	s = g_string_new(rfc822);
	message = dbmail_message_init_with_string(message, s);
	g_string_free(s,TRUE);
	result = imap_get_envelope(GMIME_MESSAGE(message->content));
	strncpy(expect,"(\"Thu, 01 Jan 1970 00:00:00 +0000\" \"dbmail test message\" ((NIL NIL \"somewher\" \"foo.org\")) ((NIL NIL \"somewher\" \"foo.org\")) ((NIL NIL \"somewher\" \"foo.org\")) ((NIL NIL \"testuser\" \"foo.org\")) NIL NIL NIL NIL)",1024);
	fail_unless(strncasecmp(result,expect,1024)==0, "imap_get_envelope failed\n[%s] !=\n[%s]\n", result,expect);

	dbmail_message_free(message);
	g_free(result);
	result = NULL;

	/* bare bones message */
	message = dbmail_message_new();
	s = g_string_new(simple);
	message = dbmail_message_init_with_string(message, s);
	g_string_free(s,TRUE);
	result = imap_get_envelope(GMIME_MESSAGE(message->content));

	strncpy(expect,"(\"Thu, 01 Jan 1970 00:00:00 +0000\" \"dbmail test message\" NIL NIL NIL NIL NIL NIL NIL NIL)", 1024);
	fail_unless(strncasecmp(result,expect,1024)==0, "imap_get_envelope failed\n[%s] !=\n[%s]\n", result,expect);

	dbmail_message_free(message);
	g_free(result);
	result = NULL;

	/* bare bones message with group addresses*/
	message = dbmail_message_new();
	s = g_string_new(simple_groups);
	message = dbmail_message_init_with_string(message, s);
	g_string_free(s,true);
	result = imap_get_envelope(GMIME_MESSAGE(message->content));

	strncpy(expect,"(\"Thu, 15 feb 2007 01:02:03 +0200\" NIL ((\"Real Name\" NIL \"user\" \"domain\")) ((\"Real Name\" NIL \"user\" \"domain\")) ((\"Real Name\" NIL \"user\" \"domain\")) ((NIL NIL \"group\" NIL)(NIL NIL \"g1\" \"d1.org\")(NIL NIL \"g2\" \"d2.org\")(NIL NIL NIL NIL)(NIL NIL \"group2\" NIL)(NIL NIL \"g3\" \"d3.org\")(NIL NIL NIL NIL)) NIL NIL NIL NIL)", 1024);

	fail_unless(strncasecmp(result,expect,1024)==0, "imap_get_envelope failed\n[%s] !=\n[%s]\n", result,expect);

	dbmail_message_free(message);
	g_free(result);
	result = NULL;

	/* bare message with broken From address*/
	message = dbmail_message_new();
	s = g_string_new(broken_message3);
	message = dbmail_message_init_with_string(message, s);
	g_string_free(s,true);
	result = imap_get_envelope(GMIME_MESSAGE(message->content));

	strncpy(expect,"(\"Fri, 11 Sep 2009 17:42:32 +0100\" \"Re: Anexo II para RO\" ((NIL NIL \"=?iso-8859-1?Q?Bombeiros_Vol._Mort=E1gua?=\" NIL)) ((NIL NIL \"=?iso-8859-1?Q?Bombeiros_Vol._Mort=E1gua?=\" NIL)) ((NIL NIL \"=?iso-8859-1?Q?Bombeiros_Vol._Mort=E1gua?=\" NIL)) ((\"Foo Bar\" NIL \"foo\" \"bar.pt\")) NIL NIL NIL \"<002001ca32fe$dc7668b0$9600000a@ricardo>\")",1024);

	fail_unless(strncasecmp(result,expect,1024)==0, "imap_get_envelope failed\n[%s] !=\n[%s]\n", result,expect);

	dbmail_message_free(message);
	g_free(result);
	result = NULL;


	//
	g_free(expect);
	expect = NULL;
}
示例#8
0
文件: help.c 项目: glshort/MapReady
static void help_viewer_thread(GString *hh, gpointer user_data)
{
    asfSystem(hh->str);
    g_string_free(hh, TRUE);
}
示例#9
0
gboolean
log_macro_expand(GString *result, gint id, gboolean escape, const LogTemplateOptions *opts, gint tz, gint32 seq_num, const gchar *context_id, LogMessage *msg)
{
  switch (id)
    {
    case M_FACILITY:
      {
        /* facility */
        const char *n;

        n = syslog_name_lookup_name_by_value(msg->pri & LOG_FACMASK, sl_facilities);
        if (n)
          {
            g_string_append(result, n);
          }
        else
          {
            format_uint32_padded(result, 0, 0, 16, (msg->pri & LOG_FACMASK) >> 3);
          }
        break;
      }
    case M_FACILITY_NUM:
      {
        format_uint32_padded(result, 0, 0, 10, (msg->pri & LOG_FACMASK) >> 3);
        break;
      }
    case M_LEVEL:
      {
        /* level */
        const char *n;

        n = syslog_name_lookup_name_by_value(msg->pri & LOG_PRIMASK, sl_levels);
        if (n)
          {
            g_string_append(result, n);
          }
        else
          {
            format_uint32_padded(result, 0, 0, 10, msg->pri & LOG_PRIMASK);
          }

        break;
      }
    case M_LEVEL_NUM:
      {
        format_uint32_padded(result, 0, 0, 10, msg->pri & LOG_PRIMASK);
        break;
      }
    case M_TAG:
      {
        format_uint32_padded(result, 2, '0', 16, msg->pri);
        break;
      }
    case M_TAGS:
      {
        log_msg_print_tags(msg, result);
        break;
      }
    case M_BSDTAG:
      {
        format_uint32_padded(result, 0, 0, 10, (msg->pri & LOG_PRIMASK));
        g_string_append_c(result, (((msg->pri & LOG_FACMASK) >> 3) + 'A'));
        break;
      }
    case M_PRI:
      {
        format_uint32_padded(result, 0, 0, 10, msg->pri);
        break;
      }
    case M_HOST:
      {
        if (msg->flags & LF_CHAINED_HOSTNAME)
          {
            /* host */
            const gchar *p1, *p2;
            int remaining, length;
            gssize host_len;
            const gchar *host = log_msg_get_value(msg, LM_V_HOST, &host_len);

            p1 = memchr(host, '@', host_len);

            if (p1)
              p1++;
            else
              p1 = host;
            remaining = host_len - (p1 - host);
            p2 = memchr(p1, '/', remaining);
            length = p2 ? p2 - p1
              : host_len - (p1 - host);

            result_append(result, p1, length, escape);
          }
        else
          {
            result_append_value(result, msg, LM_V_HOST, escape);
          }
        break;
      }
    case M_SDATA:
      if (escape)
        {
          GString *sdstr = g_string_sized_new(0);

          log_msg_append_format_sdata(msg, sdstr, seq_num);
          result_append(result, sdstr->str, sdstr->len, TRUE);
          g_string_free(sdstr, TRUE);
        }
      else
        {
          log_msg_append_format_sdata(msg, result, seq_num);
        }
      break;
    case M_MSGHDR:
      if ((msg->flags & LF_LEGACY_MSGHDR))
        {
          /* fast path for now, as most messages come from legacy devices */

          result_append_value(result, msg, LM_V_LEGACY_MSGHDR, escape);
        }
      else
        {
          /* message, complete with program name and pid */
          gssize len;

          len = result->len;
          result_append_value(result, msg, LM_V_PROGRAM, escape);
          if (len != result->len)
            {
              const gchar *pid = log_msg_get_value(msg, LM_V_PID, &len);
              if (len > 0)
                {
                  result_append(result, "[", 1, FALSE);
                  result_append(result, pid, len, escape);
                  result_append(result, "]", 1, FALSE);
                }
              result_append(result, ": ", 2, FALSE);
            }
        }
      break;
    case M_MESSAGE:
      if (cfg_is_config_version_older(configuration, 0x0300))
        log_macro_expand(result, M_MSGHDR, escape, opts, tz, seq_num, context_id, msg);
      result_append_value(result, msg, LM_V_MESSAGE, escape);
      break;
    case M_SOURCE_IP:
      {
        gchar *ip;

        if (msg->saddr && (g_sockaddr_inet_check(msg->saddr) ||
#if ENABLE_IPV6
            g_sockaddr_inet6_check(msg->saddr))
#else
            0)
#endif
           )
          {
            gchar buf[MAX_SOCKADDR_STRING];

            g_sockaddr_format(msg->saddr, buf, sizeof(buf), GSA_ADDRESS_ONLY);
            ip = buf;
          }
        else
          {
            ip = "127.0.0.1";
          }
        result_append(result, ip, strlen(ip), escape);
        break;
      }
    case M_SEQNUM:
      {
        if (seq_num)
          {
            format_uint32_padded(result, 0, 0, 10, seq_num);
          }
        break;
      }
    case M_CONTEXT_ID:
      {
        if (context_id)
          {
            result_append(result, context_id, strlen(context_id), escape);
          }
        break;
      }

    case M_RCPTID:
      {
        rcptid_append_formatted_id(result, msg->rcptid);
        break;
      }

    case M_RUNID:
      {
        run_id_append_formatted_id(result);
        break;
      }

    case M_LOGHOST:
      {
        const gchar *hname = get_local_hostname_fqdn();

        result_append(result, hname, -1, escape);
        break;
      }
    case M_SYSUPTIME:
      {
        GTimeVal ct;

        g_get_current_time(&ct);
        format_uint64_padded(result, 0, 0, 10, g_time_val_diff(&ct, &app_uptime) / 1000 / 10);
        break;
      }

    default:
      {
        /* year, month, day */
        struct tm *tm, tm_storage;
        gchar buf[64];
        gint length;
        time_t t;
        LogStamp *stamp, sstamp;
        glong zone_ofs;
        guint tmp_hour;

        if (id >= M_TIME_FIRST && id <= M_TIME_LAST)
          {
            stamp = &msg->timestamps[LM_TS_STAMP];
          }
        else if (id >= M_TIME_FIRST + M_RECVD_OFS && id <= M_TIME_LAST + M_RECVD_OFS)
          {
            id -= M_RECVD_OFS;
            stamp = &msg->timestamps[LM_TS_RECVD];
          }
        else if (id >= M_TIME_FIRST + M_STAMP_OFS && id <= M_TIME_LAST + M_STAMP_OFS)
          {
            id -= M_STAMP_OFS;
            stamp = &msg->timestamps[LM_TS_STAMP];
          }
	else if (id >= M_TIME_FIRST + M_CSTAMP_OFS && id <= M_TIME_LAST + M_CSTAMP_OFS)
	  {
	    GTimeVal tv;

	    id -= M_CSTAMP_OFS;
	    cached_g_current_time(&tv);
	    sstamp.tv_sec = tv.tv_sec;
	    sstamp.tv_usec = tv.tv_usec;
	    sstamp.zone_offset = -1;
	    stamp = &sstamp;
	  }
	else
          {
            g_assert_not_reached();
            break;
          }

        /* try to use the following zone values in order:
         *   destination specific timezone, if one is specified
         *   message specific timezone, if one is specified
         *   local timezone
         */
        zone_ofs = (opts->time_zone_info[tz] != NULL ? time_zone_info_get_offset(opts->time_zone_info[tz], stamp->tv_sec) : stamp->zone_offset);
        if (zone_ofs == -1)
          zone_ofs = stamp->zone_offset;

        t = stamp->tv_sec + zone_ofs;

        cached_gmtime(&t, &tm_storage);
        tm  = &tm_storage;

        switch (id)
          {
          case M_WEEK_DAY_ABBREV:
            g_string_append_len(result, weekday_names_abbrev[tm->tm_wday], 3);
            break;
          case M_WEEK_DAY_NAME:
            g_string_append(result, weekday_names[tm->tm_wday]);
            break;
          case M_WEEK_DAY:
            format_uint32_padded(result, 0, 0, 10, tm->tm_wday + 1);
            break;
          case M_WEEK:
            format_uint32_padded(result, 2, '0', 10, (tm->tm_yday - (tm->tm_wday - 1 + 7) % 7 + 7) / 7);
            break;
          case M_YEAR:
            format_uint32_padded(result, 4, '0', 10, tm->tm_year + 1900);
            break;
          case M_YEAR_DAY:
            format_uint32_padded(result, 3, '0', 10, tm->tm_yday + 1);
            break;
          case M_MONTH:
            format_uint32_padded(result, 2, '0', 10, tm->tm_mon + 1);
            break;
          case M_MONTH_WEEK:
            format_uint32_padded(result, 0, 0, 10, ((tm->tm_mday / 7) + ((tm->tm_wday > 0) && ((tm->tm_mday % 7) >= tm->tm_wday))));
            break;
          case M_MONTH_ABBREV:
            g_string_append_len(result, month_names_abbrev[tm->tm_mon], 3);
            break;
          case M_MONTH_NAME:
            g_string_append(result, month_names[tm->tm_mon]);
            break;
          case M_DAY:
            format_uint32_padded(result, 2, '0', 10, tm->tm_mday);
            break;
          case M_HOUR:
            format_uint32_padded(result, 2, '0', 10, tm->tm_hour);
            break;
          case M_HOUR12:
            if (tm->tm_hour < 12)
              tmp_hour = tm->tm_hour;
            else
              tmp_hour = tm->tm_hour - 12;

            if (tmp_hour == 0)
              tmp_hour = 12;
            format_uint32_padded(result, 2, '0', 10, tmp_hour);
            break;
          case M_MIN:
            format_uint32_padded(result, 2, '0', 10, tm->tm_min);
            break;
          case M_SEC:
            format_uint32_padded(result, 2, '0', 10, tm->tm_sec);
            break;
          case M_MSEC:
            format_uint32_padded(result, 3, '0', 10, stamp->tv_usec/1000);
            break;
          case M_USEC:
            format_uint32_padded(result, 6, '0', 10, stamp->tv_usec);
            break;
          case M_AMPM:
            g_string_append(result, tm->tm_hour < 12 ? "AM" : "PM");
            break;
          case M_DATE:
          case M_STAMP:
          case M_ISODATE:
          case M_FULLDATE:
          case M_UNIXTIME:
            {
              gint format = id == M_DATE ? TS_FMT_BSD :
                            id == M_ISODATE ? TS_FMT_ISO :
                            id == M_FULLDATE ? TS_FMT_FULL :
                            id == M_UNIXTIME ? TS_FMT_UNIX :
                            opts->ts_format;

              log_stamp_append_format(stamp, result, format, zone_ofs, opts->frac_digits);
              break;
            }
          case M_TZ:
          case M_TZOFFSET:
            length = format_zone_info(buf, sizeof(buf), zone_ofs);
            g_string_append_len(result, buf, length);
            break;
          }
        break;
      }
    }
示例#10
0
文件: modes.c 项目: svn2github/irssi
/* Parse channel mode string */
void parse_channel_modes(IRC_CHANNEL_REC *channel, const char *setby,
			 const char *mode, int update_key)
{
	IRC_SERVER_REC *server = channel->server;
        GString *newmode;
	char *dup, *modestr, *arg, *curmode, type, *old_key;
	int umode;

	g_return_if_fail(IS_IRC_CHANNEL(channel));
	g_return_if_fail(mode != NULL);

	type = '+';
	newmode = g_string_new(channel->mode);
	old_key = update_key ? NULL : g_strdup(channel->key);

	dup = modestr = g_strdup(mode);
	curmode = cmd_get_param(&modestr);
	while (*curmode != '\0') {
		if (HAS_MODE_ARG(server, type, *curmode)) {
			/* get the argument for the mode. NOTE: We don't
			   get the +k's argument when joining to channel. */
			arg = cmd_get_param(&modestr);
		} else {
			arg = NULL;
		}

		switch (*curmode) {
		case '+':
		case '-':
			type = *curmode;
			break;
		default:
			umode = (unsigned char) *curmode;
			if (server->modes[umode].func != NULL) {
				server->modes[umode].func(channel, setby,
							  type, *curmode, arg,
							  newmode);
			} else {
				/* Treat unknown modes as ones without params */
				modes_type_d(channel, setby, type, *curmode,
					     arg, newmode);
			}
		}

		curmode++;
	}
	g_free(dup);

	if (channel->key != NULL &&
	    strchr(channel->mode, 'k') == NULL &&
	    strchr(newmode->str, 'k') == NULL) {
		/* join was used with key but there's no key set
		   in channel modes.. */
		g_free(channel->key);
		channel->key = NULL;
	} else if (!update_key && old_key != NULL) {
		/* get the old one back, just in case it was replaced */
		g_free(channel->key);
		channel->key = old_key;
		mode_set_arg(channel->server, newmode, '+', 'k', old_key, FALSE);
		old_key = NULL;
	}

	if (strcmp(newmode->str, channel->mode) != 0) {
		g_free(channel->mode);
		channel->mode = g_strdup(newmode->str);

		signal_emit("channel mode changed", 2, channel, setby);
	}

	g_string_free(newmode, TRUE);
	g_free(old_key);
}
示例#11
0
文件: modes.c 项目: svn2github/irssi
void channel_set_mode(IRC_SERVER_REC *server, const char *channel,
		      const char *mode)
{
	IRC_CHANNEL_REC *chanrec;
	GString *tmode, *targs;
	char *modestr, *curmode, *orig, type, prevtype;
	int count;

	g_return_if_fail(IS_IRC_SERVER(server));
	g_return_if_fail(channel != NULL && mode != NULL);

	tmode = g_string_new(NULL);
	targs = g_string_new(NULL);
	count = 0;

	chanrec = irc_channel_find(server, channel);
	if (chanrec != NULL)
		channel = chanrec->name;

	orig = modestr = g_strdup(mode);

        type = '+'; prevtype = '\0';
	curmode = cmd_get_param(&modestr);
	for (;; curmode++) {
		if (*curmode == '\0') {
			/* support for +o nick +o nick2 */
			curmode = cmd_get_param(&modestr);
			if (*curmode == '\0')
				break;
		}

		if (*curmode == '+' || *curmode == '-') {
			type = *curmode;
			continue;
		}

		if (count == server->max_modes_in_cmd &&
		    HAS_MODE_ARG(server, type, *curmode)) {
			irc_send_cmdv(server, "MODE %s %s%s",
				      channel, tmode->str, targs->str);

			count = 0; prevtype = '\0';
			g_string_truncate(tmode, 0);
			g_string_truncate(targs, 0);
		}

		if (type != prevtype) {
			prevtype = type;
			g_string_append_c(tmode, type);
		}
		g_string_append_c(tmode, *curmode);

		if (HAS_MODE_ARG(server, type, *curmode)) {
			char *arg;

			count++;
			arg = cmd_get_param(&modestr);
			if (*arg == '\0' && type == '-' && *curmode == 'k') {
				/* "/mode #channel -k" - no reason why it
				   shouldn't work really, so append the key */
				IRC_CHANNEL_REC *chanrec;

				chanrec = irc_channel_find(server, channel);
				if (chanrec != NULL && chanrec->key != NULL)
                                        arg = chanrec->key;
			}

			if (*arg != '\0')
				g_string_sprintfa(targs, " %s", arg);
		}
	}

	if (tmode->len > 0) {
		irc_send_cmdv(server, "MODE %s %s%s",
			      channel, tmode->str, targs->str);
	}

	g_string_free(tmode, TRUE);
	g_string_free(targs, TRUE);
	g_free(orig);
}
示例#12
0
文件: gimprc.c 项目: Distrotech/gimp
/**
 * gimp_rc_query:
 * @rc:  a #GimpRc object.
 * @key: a string used as a key for the lookup.
 *
 * This function looks up @key in the object properties of @rc. If
 * there's a matching property, a string representation of its value
 * is returned. If no property is found, the list of unknown tokens
 * attached to the @rc object is searched.
 *
 * Return value: a newly allocated string representing the value or %NULL
 *               if the key couldn't be found.
 **/
gchar *
gimp_rc_query (GimpRc      *rc,
               const gchar *key)
{
  GObjectClass  *klass;
  GObject       *rc_object;
  GParamSpec   **property_specs;
  GParamSpec    *prop_spec;
  guint          i, n_property_specs;
  gchar         *retval = NULL;

  g_return_val_if_fail (GIMP_IS_RC (rc), NULL);
  g_return_val_if_fail (key != NULL, NULL);

  rc_object = G_OBJECT (rc);
  klass = G_OBJECT_GET_CLASS (rc);

  property_specs = g_object_class_list_properties (klass, &n_property_specs);

  if (!property_specs)
    return NULL;

  for (i = 0, prop_spec = NULL; i < n_property_specs && !prop_spec; i++)
    {
      prop_spec = property_specs[i];

      if (! (prop_spec->flags & GIMP_CONFIG_PARAM_SERIALIZE) ||
          strcmp (prop_spec->name, key))
        {
          prop_spec = NULL;
        }
    }

  if (prop_spec)
    {
      GString *str   = g_string_new (NULL);
      GValue   value = { 0, };

      g_value_init (&value, prop_spec->value_type);
      g_object_get_property (rc_object, prop_spec->name, &value);

      if (gimp_config_serialize_value (&value, str, FALSE))
        retval = g_string_free (str, FALSE);
      else
        g_string_free (str, TRUE);

      g_value_unset (&value);
    }
  else
    {
      retval = g_strdup (gimp_rc_lookup_unknown_token (GIMP_CONFIG (rc), key));
    }

  g_free (property_specs);

  if (!retval)
    {
      const gchar * const path_tokens[] =
      {
        "gimp_dir",
        "gimp_data_dir",
        "gimp_plug_in_dir",
        "gimp_plugin_dir",
        "gimp_sysconf_dir"
      };

      for (i = 0; !retval && i < G_N_ELEMENTS (path_tokens); i++)
        if (strcmp (key, path_tokens[i]) == 0)
          retval = g_strdup_printf ("${%s}", path_tokens[i]);
    }

  if (retval)
    {
      gchar *tmp = gimp_config_path_expand (retval, FALSE, NULL);

      if (tmp)
        {
          g_free (retval);
          retval = tmp;
        }
    }

  return retval;
}
示例#13
0
文件: luautil.c 项目: liaonau/luakit
gint
luaH_traceback(lua_State *L, lua_State *T, gint min_level)
{
    lua_Debug ar;
    gint max_level;
    gint loc_pad = 0;

#define AR_SRC(ar) \
    (g_strstr_len((ar).source, 3, "@./") ? (ar).source+3 : \
     (ar).source[0] == '@'               ? (ar).source+1 : \
     (ar).short_src)
#define LENF(fmt, ...) \
    (snprintf(NULL, 0, fmt, ##__VA_ARGS__))

    if (!lua_getstack(T, min_level, &ar)) {
        lua_pushliteral(L, "");
        return 1;
    }

    /* Traverse the stack to determine max level and padding sizes */
    for (gint level = min_level; lua_getstack(T, level, &ar); level++) {
        lua_getinfo(T, "Sl", &ar);

        max_level = level;

        gint cur_pad = LENF("%s:%d", AR_SRC(ar), ar.currentline);
        if (cur_pad > loc_pad) loc_pad = cur_pad;
    }

    GString *tb = g_string_new("");
    gint level_pad = LENF("%d", max_level);

    for (gint level = min_level; level <= max_level; level++) {
        lua_getstack(T, level, &ar);
        lua_getinfo(T, "Sln", &ar);

        /* Current stack level */
        gint shown_level = level - min_level + 1;
        g_string_append_printf(tb, ANSI_COLOR_GRAY "(%*d)" ANSI_COLOR_RESET " ",
                level_pad, shown_level);

        /* Current location, padded */
        if (g_str_equal(ar.what, "C")) {
            g_string_append_printf(tb, "%-*s", loc_pad, "[C]");
        } else {
            const char *src = AR_SRC(ar);
            int n;
            g_string_append_printf(tb, "%s:%d%n", src, ar.currentline, &n);
            g_string_append_printf(tb, "%*.*s", loc_pad-n, loc_pad-n, "");
        }

        /* Function name */
        if (g_str_equal(ar.what, "main")) {
            g_string_append(tb, ANSI_COLOR_GRAY " in main chunk" ANSI_COLOR_RESET);
        } else {
            g_string_append_printf(tb, ANSI_COLOR_GRAY " in function " ANSI_COLOR_RESET "%s",
                    ar.name ?: "[anonymous]");
        }

        if (level != max_level) {
            g_string_append(tb, "\n");
        }
    }

    lua_pushstring(L, tb->str);
    g_string_free(tb, TRUE);
    return 1;
}
char *
nm_dhcp_dhclient_create_config (const char *interface,
                                gboolean is_ip6,
                                GBytes *client_id,
                                const char *anycast_addr,
                                const char *hostname,
                                const char *orig_path,
                                const char *orig_contents,
                                GBytes **out_new_client_id)
{
	GString *new_contents;
	GPtrArray *alsoreq;
	int i;

	g_return_val_if_fail (!anycast_addr || nm_utils_hwaddr_valid (anycast_addr, ETH_ALEN), NULL);

	new_contents = g_string_new (_("# Created by NetworkManager\n"));
	alsoreq = g_ptr_array_sized_new (5);

	if (orig_contents) {
		char **lines, **line;
		gboolean in_alsoreq = FALSE;

		g_string_append_printf (new_contents, _("# Merged from %s\n\n"), orig_path);

		lines = g_strsplit_set (orig_contents, "\n\r", 0);
		for (line = lines; lines && *line; line++) {
			char *p = *line;

			if (!strlen (g_strstrip (p)))
				continue;

			if (!strncmp (p, CLIENTID_TAG, strlen (CLIENTID_TAG))) {
				/* Override config file "dhcp-client-id" and use one from the connection */
				if (client_id)
					continue;

				/* Otherwise capture and return the existing client id */
				if (out_new_client_id)
					*out_new_client_id = read_client_id (p);
			}

			/* Override config file hostname and use one from the connection */
			if (hostname) {
				if (strncmp (p, HOSTNAME4_TAG, strlen (HOSTNAME4_TAG)) == 0)
					continue;
				if (strncmp (p, FQDN_TAG, strlen (FQDN_TAG)) == 0)
					continue;
			}

			/* Ignore 'script' since we pass our own */
			if (g_str_has_prefix (p, "script "))
				continue;

			/* Check for "also require" */
			if (!strncmp (p, ALSOREQ_TAG, strlen (ALSOREQ_TAG))) {
				in_alsoreq = TRUE;
				p += strlen (ALSOREQ_TAG);
			}

			if (in_alsoreq) {
				char **areq, **aiter;

				/* Grab each 'also require' option and save for later */
				areq = g_strsplit_set (p, "\t ,", -1);
				for (aiter = areq; aiter && *aiter; aiter++) {
					if (!strlen (g_strstrip (*aiter)))
						continue;

					if (*aiter[0] == ';') {
						/* all done */
						in_alsoreq = FALSE;
						break;
					}

					if (!g_ascii_isalnum ((*aiter)[0]))
						continue;

					if ((*aiter)[strlen (*aiter) - 1] == ';') {
						/* Remove the EOL marker */
						(*aiter)[strlen (*aiter) - 1] = '\0';
						in_alsoreq = FALSE;
					}

					add_also_request (alsoreq, *aiter);
				}

				if (areq)
					g_strfreev (areq);

				continue;
			}

			/* Existing configuration line is OK, add it to new configuration */
			g_string_append (new_contents, *line);
			g_string_append_c (new_contents, '\n');
		}

		if (lines)
			g_strfreev (lines);
	} else
		g_string_append_c (new_contents, '\n');

	if (is_ip6) {
		add_hostname6 (new_contents, hostname);
		add_also_request (alsoreq, "dhcp6.name-servers");
		add_also_request (alsoreq, "dhcp6.domain-search");
		add_also_request (alsoreq, "dhcp6.client-id");
	} else {
		add_ip4_config (new_contents, client_id, hostname);
		add_also_request (alsoreq, "rfc3442-classless-static-routes");
		add_also_request (alsoreq, "ms-classless-static-routes");
		add_also_request (alsoreq, "static-routes");
		add_also_request (alsoreq, "wpad");
		add_also_request (alsoreq, "ntp-servers");
	}

	/* And add it to the dhclient configuration */
	for (i = 0; i < alsoreq->len; i++) {
		char *t = g_ptr_array_index (alsoreq, i);

		g_string_append_printf (new_contents, "also request %s;\n", t);
		g_free (t);
	}
	g_ptr_array_free (alsoreq, TRUE);

	g_string_append_c (new_contents, '\n');

	if (anycast_addr) {
		g_string_append_printf (new_contents, "interface \"%s\" {\n"
		                        " initial-interval 1; \n"
		                        " anycast-mac ethernet %s;\n"
		                        "}\n",
		                        interface, anycast_addr);
	}

	return g_string_free (new_contents, FALSE);
}
示例#15
0
static void text_window_clear(funnel_text_window_t *tw) {
    g_string_free(tw->text, TRUE);
    tw->text = g_string_new("");
}
示例#16
0
/* listen to a socket */
int li_angel_fake_listen(liServer *srv, GString *str) {
	guint32 ipv4;
#ifdef HAVE_IPV6
	guint8 ipv6[16];
#endif
	guint16 port;

#ifdef HAVE_SYS_UN_H
	if (0 == strncmp(str->str, "unix:/", 6)) {
		int s;
		struct sockaddr_un *un;
		socklen_t slen = str->len + 1 - 5 + sizeof(un->sun_family);

		un = g_malloc0(slen);
		un->sun_family = AF_UNIX;
		strcpy(un->sun_path, str->str + 5);

		if (-1 == unlink(un->sun_path)) {
			switch (errno) {
			case ENOENT:
				break;
			default:
				ERROR(srv, "removing old socket '%s' failed: %s\n", str->str, g_strerror(errno));
				g_free(un);
				return -1;
			}
		}
		if (-1 == (s = socket(AF_UNIX, SOCK_STREAM, 0))) {
			ERROR(srv, "Couldn't open socket: %s", g_strerror(errno));
			g_free(un);
			return -1;
		}
		if (-1 == bind(s, (struct sockaddr*) un, slen)) {
			close(s);
			ERROR(srv, "Couldn't bind socket to '%s': %s", str->str, g_strerror(errno));
			g_free(un);
			return -1;
		}
		if (-1 == listen(s, 1000)) {
			close(s);
			ERROR(srv, "Couldn't listen on '%s': %s", str->str, g_strerror(errno));
			g_free(un);
			return -1;
		}
		g_free(un);
		DEBUG(srv, "listen to unix socket: '%s'", str->str);
		return s;
	} else
#endif
	if (li_parse_ipv4(str->str, &ipv4, NULL, &port)) {
		int s, v;
		struct sockaddr_in addr;

		if (!port) port = 80;
		memset(&addr, 0, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = ipv4;
		addr.sin_port = htons(port);
		if (-1 == (s = socket(AF_INET, SOCK_STREAM, 0))) {
			ERROR(srv, "Couldn't open socket: %s", g_strerror(errno));
			return -1;
		}
		v = 1;
		if (-1 == setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v))) {
			close(s);
			ERROR(srv, "Couldn't setsockopt(SO_REUSEADDR): %s", g_strerror(errno));
			return -1;
		}
		if (-1 == bind(s, (struct sockaddr*)&addr, sizeof(addr))) {
			close(s);
			ERROR(srv, "Couldn't bind socket to '%s': %s", inet_ntoa(addr.sin_addr), g_strerror(errno));
			return -1;
		}
		if (-1 == listen(s, 1000)) {
			close(s);
			ERROR(srv, "Couldn't listen on '%s': %s", inet_ntoa(addr.sin_addr), g_strerror(errno));
			return -1;
		}
		DEBUG(srv, "listen to ipv4: '%s' port: %d", inet_ntoa(addr.sin_addr), port);
		return s;
#ifdef HAVE_IPV6
	} else if (li_parse_ipv6(str->str, ipv6, NULL, &port)) {
		GString *ipv6_str = g_string_sized_new(0);
		int s, v;
		struct sockaddr_in6 addr;
		li_ipv6_tostring(ipv6_str, ipv6);
		
		if (!port) port = 80;
		memset(&addr, 0, sizeof(addr));
		addr.sin6_family = AF_INET6;
		memcpy(&addr.sin6_addr, ipv6, 16);
		addr.sin6_port = htons(port);
		if (-1 == (s = socket(AF_INET6, SOCK_STREAM, 0))) {
			ERROR(srv, "Couldn't open socket: %s", g_strerror(errno));
			g_string_free(ipv6_str, TRUE);
			return -1;
		}
		v = 1;
		if (-1 == setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v))) {
			close(s);
			ERROR(srv, "Couldn't setsockopt(SO_REUSEADDR): %s", g_strerror(errno));
			g_string_free(ipv6_str, TRUE);
			return -1;
		}
		if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &v, sizeof(v))) {
			close(s);
			ERROR(srv, "Couldn't setsockopt(IPV6_V6ONLY): %s", g_strerror(errno));
			g_string_free(ipv6_str, TRUE);
			return -1;
		}
		if (-1 == bind(s, (struct sockaddr*)&addr, sizeof(addr))) {
			close(s);
			ERROR(srv, "Couldn't bind socket to '%s': %s", ipv6_str->str, g_strerror(errno));
			g_string_free(ipv6_str, TRUE);
			return -1;
		}
		if (-1 == listen(s, 1000)) {
			close(s);
			ERROR(srv, "Couldn't listen on '%s': %s", ipv6_str->str, g_strerror(errno));
			g_string_free(ipv6_str, TRUE);
			return -1;
		}
		DEBUG(srv, "listen to ipv6: '%s' port: %d", ipv6_str->str, port);
		g_string_free(ipv6_str, TRUE);
		return s;
#endif
	} else {
		ERROR(srv, "Invalid ip: '%s'", str->str);
		return -1;
	}
}
示例#17
0
static void text_window_set_text(funnel_text_window_t *tw, const char *text) {
    g_string_free(tw->text, TRUE);
    tw->text = g_string_new(text);
}
void *accept_thread(void *accept_sock)
{
    //socket descriptor for each client
    int acptsock;
    //Retrieve the socket that passed from pthread_create
    acptsock= (intptr_t)accept_sock;

    //Buffer to send&receive data//
    char buf[256];

    //Received bytes
    int bytes;

    //Declare the structure of the sending message in order
    //the filemanager to communicate with the client and vice versa
    FILEHEADER *msg = (FILEHEADER *)malloc(sizeof(FILEHEADER));


    //While the client is connect to the system you have to keep the connection
    while(1)
    {
        //If connection is established then start communicating //
        //Initialize buffer with zeros //
        bzero(buf, sizeof(buf));
        //Waiting...to receive data from the client//
        if (recv(acptsock, buf, sizeof(buf), 0) < 0)
        {
            perror("Received() failed!");
            close(acptsock);
            pthread_exit((void *) 0);
        }

        //Check if direc received a message
        if(strlen(buf) != 0)
        {
            //Show the message that received//
            printf("----------------------------------\n");
            printf("accept_thread received: %s\n", buf);
        }
        else if (strlen(buf) == 0)
        {
            //printf("Unable to received messsage!\n");
            close(acptsock);
            pthread_exit((void *) 0);
        }

        //Decode the message that receive from the client
        //in order to identify the type of the message//
        decode(buf,msg);

        if( strcmp(msg->type , "REQCLIENTID" )== 0)
        {
            bzero(buf,sizeof(buf));
            //encode the clientID
            sprintf(buf,"REQCLIENTID,%ld,%ld" , registerClient(msg->username ), msg->MSGID );
            if (send(acptsock, buf, sizeof(buf) , 0) < 0 )
            {
                perror("Send:Unable to send clientID");
            }

            //Deallocations
            free(msg->username);
        }


        else if( strcmp(msg->type , "REQCREATE" )== 0 )
        {
            printf("Received Create: %s , owner:%ld\n", msg->filename, msg->owner);

            //Store fileid
            unsigned long fileid = lookUpFileID(msg->filename , msg->owner );

            if(fileid == -1)
            {
                //Store the new file in the metadata
                //Also , retrieve the fileID for the file
                fileid = registerFile(msg->filename, msg->owner);
            }

            printf("REQCREATE Function return: %ld \n", fileid);

            bzero(buf, sizeof(buf));
            //encode the clientID
            sprintf(buf, "REQCREATE,%ld,%ld", fileid, msg->MSGID);
            if (send(acptsock, buf, sizeof(buf), 0) < 0)
            {
                perror("Send:Unable to send clientID");
            }
            //Deallocations
            free(msg->filename);

        }
        else if( strcmp(msg->type , "REQFILEID" )== 0 )
        {
            printf("Received REQFILEID: %s , owner:%ld\n" , msg->filename ,msg->owner);

            //Store the new file in the metadata
            //Also , retrieve the fileID for the file
            unsigned long fileid = lookUpFileID(msg->filename , msg->owner );

            if(fileid == -1)
            {
                //Store the new file in the metadata
                //Also , retrieve the fileID for the file
                fileid = registerFile(msg->filename, msg->owner);
            }

            printf("REQFILEID Function return: %ld \n" , fileid);

            bzero(buf,sizeof(buf));
            //encode the clientID
            sprintf(buf,"REQFILEID,%ld,%ld" , fileid , msg->MSGID );
            if (send(acptsock, buf, sizeof(buf) , 0) < 0 )
            {
                perror("Send:Unable to send clientID");
            }

            //Deallocations
            free(msg->filename);
        }
        else if( strcmp(msg->type , "REQFILESLIST" )== 0 )
        {
            bzero(buf,sizeof(buf));

            GString *list=NULL;

            list=getfilelist(list);
            printf("List\n");

            if (send(acptsock, list->str, strlen(list->str) , 0) < 0 )
            {
                perror("Send:Unable to send clientID");
            }

            //Deallocate memory
            g_string_free(list,TRUE);

        }


    }//While
}
示例#19
0
void
gtr_confirm_remove( GtkWindow  * parent,
                    TrCore     * core,
                    GSList     * torrent_ids,
                    gboolean     delete_files )
{
    GSList * l;
    GtkWidget * d;
    GString * primary_text;
    GString * secondary_text;
    struct delete_data * dd;
    int connected = 0;
    int incomplete = 0;
    const int count = g_slist_length( torrent_ids );

    if( !count )
        return;

    dd = g_new0( struct delete_data, 1 );
    dd->core = core;
    dd->torrent_ids = torrent_ids;
    dd->delete_files = delete_files;

    for( l=torrent_ids; l!=NULL; l=l->next )
    {
        const int id = GPOINTER_TO_INT( l->data );
        tr_torrent * tor = gtr_core_find_torrent( core, id );
        const tr_stat * stat = tr_torrentStat( tor );
        if( stat->leftUntilDone ) ++incomplete;
        if( stat->peersConnected ) ++connected;
    }

    primary_text = g_string_new( NULL );

    if( !delete_files )
    {
        g_string_printf( primary_text, ngettext( "Remove torrent?",
                                                 "Remove %d torrents?",
                                                 count ), count );
    }
    else
    {
        g_string_printf( primary_text, ngettext( "Delete this torrent's downloaded files?",
                                                 "Delete these %d torrents' downloaded files?",
                                                 count ), count );
    }

    secondary_text = g_string_new( NULL );

    if( !incomplete && !connected )
    {
        g_string_assign( secondary_text, ngettext(
                "Once removed, continuing the transfer will require the torrent file or magnet link.",
                "Once removed, continuing the transfers will require the torrent files or magnet links.",
                count ) );
    }
    else if( count == incomplete )
    {
        g_string_assign( secondary_text, ngettext( "This torrent has not finished downloading.",
                                                   "These torrents have not finished downloading.",
                                                   count ) );
    }
    else if( count == connected )
    {
        g_string_assign( secondary_text, ngettext( "This torrent is connected to peers.",
                                                   "These torrents are connected to peers.",
                                                   count ) );
    }
    else
    {
        if( connected )
            g_string_append( secondary_text, ngettext( "One of these torrents is connected to peers.",
                                                       "Some of these torrents are connected to peers.",
                                                       connected ) );
        if( connected && incomplete )
            g_string_append( secondary_text, "\n" );

        if( incomplete )
            g_string_assign( secondary_text, ngettext( "One of these torrents has not finished downloading.",
                                                       "Some of these torrents have not finished downloading.",
                                                       incomplete ) );
    }

    d = gtk_message_dialog_new_with_markup( parent,
                                            GTK_DIALOG_DESTROY_WITH_PARENT,
                                            GTK_MESSAGE_QUESTION,
                                            GTK_BUTTONS_NONE,
                                            "<big><b>%s</b></big>",
                                            primary_text->str );
    if( secondary_text->len )
        gtk_message_dialog_format_secondary_markup( GTK_MESSAGE_DIALOG( d ),
                                                    "%s", secondary_text->str );
    gtk_dialog_add_buttons( GTK_DIALOG( d ),
                            GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                            ( delete_files ? GTK_STOCK_DELETE :
                              GTK_STOCK_REMOVE ), GTK_RESPONSE_ACCEPT,
                            NULL );
    gtk_dialog_set_default_response( GTK_DIALOG ( d ),
                                     GTK_RESPONSE_CANCEL );
    gtk_dialog_set_alternative_button_order( GTK_DIALOG( d ),
                                             GTK_RESPONSE_ACCEPT,
                                             GTK_RESPONSE_CANCEL,
                                             -1 );
    g_signal_connect( d, "response", G_CALLBACK( on_remove_dialog_response ), dd );
    gtk_widget_show_all( d );

    g_string_free( primary_text, TRUE );
    g_string_free( secondary_text, TRUE );
}
示例#20
0
/**
 * @brief get_results Get and parse the results from a search query
 * @param search_term String submitted as the search term
 * @return Search results
 */
GSList * get_results(char *search_term, UnityCancellable* cancellable){
  GString *url = NULL;
  GSList *results = NULL;
  result_t *result = NULL;

  trim_string(search_term);
  /* Check if a proper search term was submitted, return otherwise */
  if ( search_term == NULL || search_term[0] == '\0' || strlen(search_term) < 3 ) {
    g_warning("get_results: search_term null or too short\n");
    return results;
  }

  g_warning("Starting search for %s\n", search_term);

  /* Construct the full search query */
  url = g_string_new(ARTIST_BASE_URI);
  g_string_append(url, search_term);

  GError *error = NULL;
  JsonParser *parser = json_parser_new();
  GFile * file = g_file_new_for_uri(url->str);

  g_print("\nReading %s from file pointer...", url->str);
  GInputStream * fis = (GInputStream*) \
    g_file_read(file, unity_cancellable_get_gcancellable(cancellable), &error);
  g_print("done!\n");

  if (error){
    g_debug("** ERROR **: %s (domain: %s, code: %d) at %d (in get_results) \n",\
	    error->message, g_quark_to_string (error->domain), error->code, \
	    __LINE__);
    g_object_unref(file);
    if (fis)
      g_object_unref(fis);
    g_object_unref (parser);
    g_string_free(url, TRUE);
    return results;
  }

  json_parser_load_from_stream(parser, fis, NULL, &error);
  if (error){
    g_debug("Unable to parse `%s': %s\n", url->str, error->message);
    g_object_unref(file);
    g_object_unref(fis);
    g_object_unref (parser);
    g_string_free(url, TRUE);
    return results;
  }

  JsonNode *root = json_parser_get_root(parser);
  JsonObject * content = json_node_get_object(root);

  JsonNode * ArtistsNode = json_object_get_member(content, "artists");
  JsonArray * ArtistsArray = json_node_get_array(ArtistsNode);
  guint ArtistsArrayLength = json_array_get_length(ArtistsArray);
  if ( ArtistsArrayLength > MAX_RESULTS)
    ArtistsArrayLength = MAX_RESULTS;
  guint i = 0;
  for (i = 0; i < ArtistsArrayLength; i++){
    if ( g_cancellable_is_cancelled( unity_cancellable_get_gcancellable( cancellable ) ) )
      break;
    JsonNode * artistNode = json_array_get_element(ArtistsArray, i);
    JsonObject * artistNodeContent = json_node_get_object(artistNode);
    const gchar * title = json_object_get_string_member(artistNodeContent, "name");
    const gchar * spotify_uri = \
      json_object_get_string_member(artistNodeContent, "href");
    const gchar * popularity = \
      json_object_get_string_member(artistNodeContent, "popularity");

    gchar * n_of_albums = g_strdup_printf("%i", get_spotify_artist_albums(spotify_uri) );

    result = (result_t*)malloc(sizeof(result_t));
    bzero((result_t*)result, sizeof(result_t));

    gchar * fallback_icon_url = \
      "/usr/share/icons/unity-icon-theme/places/svg/service-spotify.svg";    
    g_print("Fetching thumbnail for %s\n", title);
    gchar * icon_url = get_spotify_thumbnail(spotify_uri);
    if ( icon_url == NULL ) {
      icon_url = fallback_icon_url;
      result->icon_url = (char *)malloc(strlen(icon_url)+1);
      strcpy(result->icon_url, icon_url);
    }
    else {
      result->icon_url = (char *)malloc(strlen(icon_url)+1);
      strcpy(result->icon_url, icon_url);
      free(icon_url);
    }

    g_print("%s\n\n", result->icon_url);

    result->title = (char *)malloc(strlen(title)+1);
    strcpy(result->title, title);

    result->link = (char *)malloc(strlen(spotify_uri)+1);
    strcpy(result->link, spotify_uri);

    result->popularity = (char *)malloc(strlen(popularity)+1);
    strcpy(result->popularity, popularity);

    result->n_of_albums = (char *)malloc(strlen(n_of_albums)+1);
    strcpy(result->n_of_albums, n_of_albums);
    g_free(n_of_albums);

    results = g_slist_append(results, result);
  }

  g_object_unref(file);
  g_object_unref(fis);
  g_object_unref (parser);
  g_string_free(url, TRUE);
  return results;
}
示例#21
0
JSBool
gjs_console_interact(JSContext *context,
                     unsigned   argc,
                     jsval     *vp)
{
    JSObject *object = JS_THIS_OBJECT(context, vp);
    gboolean eof = FALSE;
    jsval result;
    JSString *str;
    GString *buffer = NULL;
    char *temp_buf = NULL;
    int lineno;
    int startline;
    FILE *file = stdin;

    JS_SetErrorReporter(context, gjs_console_error_reporter);

        /* It's an interactive filehandle; drop into read-eval-print loop. */
    lineno = 1;
    do {
        /*
         * Accumulate lines until we get a 'compilable unit' - one that either
         * generates an error (before running out of source) or that compiles
         * cleanly.  This should be whenever we get a complete statement that
         * coincides with the end of a line.
         */
        startline = lineno;
        buffer = g_string_new("");
        do {
            if (!gjs_console_readline(context, &temp_buf, file,
                                      startline == lineno ? "gjs> " : ".... ")) {
                eof = JS_TRUE;
                break;
            }
            g_string_append(buffer, temp_buf);
            g_free(temp_buf);
            lineno++;
        } while (!JS_BufferIsCompilableUnit(context, object, buffer->str, buffer->len));

        JS::CompileOptions options(context);
        options.setUTF8(true)
               .setFileAndLine("typein", startline);
        js::RootedObject rootedObj(context, object);
        JS::Evaluate(context, rootedObj, options, buffer->str, buffer->len,  &result);

        if (JS_GetPendingException(context, &result)) {
            str = JS_ValueToString(context, result);
            JS_ClearPendingException(context);
        } else if (JSVAL_IS_VOID(result)) {
            goto next;
        } else {
            str = JS_ValueToString(context, result);
        }

        if (str) {
            char *display_str;
            display_str = gjs_value_debug_string(context, result);
            if (display_str != NULL) {
                g_fprintf(stdout, "%s\n", display_str);
                g_free(display_str);
            }
        }

 next:
        g_string_free(buffer, TRUE);
    } while (!eof);

    g_fprintf(stdout, "\n");

    if (file != stdin)
        fclose(file);

    return JS_TRUE;
}
static char*
getProgressString( const tr_info * info,
                   const tr_stat * torStat )
{
    const int      isDone = torStat->leftUntilDone == 0;
    const uint64_t haveTotal = torStat->haveUnchecked + torStat->haveValid;
    const int      isSeed = torStat->haveValid >= info->totalSize;
    char           buf1[32], buf2[32], buf3[32], buf4[32];
    char *         str;

    if( !isDone )
        str = g_strdup_printf(
            /* %1$s is how much we've got,
               %2$s is how much we'll have when done,
               %3$.2f%% is a percentage of the two */
            _( "%1$s of %2$s (%3$.2f%%)" ),
            tr_strlsize( buf1, haveTotal, sizeof( buf1 ) ),
            tr_strlsize( buf2, torStat->sizeWhenDone, sizeof( buf2 ) ),
            torStat->percentDone * 100.0 );
    else if( !isSeed )
        str = g_strdup_printf(
            /* %1$s is how much we've got,
               %2$s is the torrent's total size,
               %3$.2f%% is a percentage of the two,
               %4$s is how much we've uploaded,
               %5$s is our upload-to-download ratio */
            _( "%1$s of %2$s (%3$.2f%%), uploaded %4$s (Ratio: %5$s)" ),
            tr_strlsize( buf1, haveTotal, sizeof( buf1 ) ),
            tr_strlsize( buf2, info->totalSize, sizeof( buf2 ) ),
            torStat->percentComplete * 100.0,
            tr_strlsize( buf3, torStat->uploadedEver, sizeof( buf3 ) ),
            tr_strlratio( buf4, torStat->ratio, sizeof( buf4 ) ) );
    else
        str = g_strdup_printf(
            /* %1$s is the torrent's total size,
               %2$s is how much we've uploaded,
               %3$s is our upload-to-download ratio */
            _( "%1$s, uploaded %2$s (Ratio: %3$s)" ),
            tr_strlsize( buf1, info->totalSize, sizeof( buf1 ) ),
            tr_strlsize( buf2, torStat->uploadedEver, sizeof( buf2 ) ),
            tr_strlratio( buf3, torStat->ratio, sizeof( buf3 ) ) );

    /* add time when downloading */
    if( torStat->activity == TR_STATUS_DOWNLOAD )
    {
        const int eta = torStat->eta;
        GString * gstr = g_string_new( str );
        g_string_append( gstr, " - " );
        if( eta < 0 )
            g_string_append( gstr, _( "Remaining time unknown" ) );
        else
        {
            char timestr[128];
            tr_strltime( timestr, eta, sizeof( timestr ) );
            /* time remaining */
            g_string_append_printf( gstr, _( "%s remaining" ), timestr );
        }
        g_free( str );
        str = g_string_free( gstr, FALSE );
    }

    return str;
}
示例#23
0
static void ebookpull_cb(EBook *book, const GError *gerr, GList *contacts,
							void *user_data)
{
	struct query_context *data = user_data;
	GList *l;
	unsigned int count, maxcount;

	data->queued_calls--;

	if (data->canceled)
		goto canceled;

	if (gerr != NULL) {
		error("E-Book query failed: %s", gerr->message);
		goto done;
	}

	DBG("");

	/*
	 * When MaxListCount is zero, PCE wants to know the number of used
	 * indexes in the phonebook of interest. All other parameters that
	 * may be present in the request shall be ignored.
	 */
	maxcount = data->params->maxlistcount;
	if (maxcount == 0) {
		data->count += g_list_length(contacts);
		goto done;
	}

	l = g_list_nth(contacts, data->params->liststartoffset);

	for (count = 0; l && count + data->count < maxcount; l = g_list_next(l),
								count++) {
		EContact *contact = E_CONTACT(l->data);
		EVCard *evcard = E_VCARD(contact);
		char *vcard;

		vcard = evcard_to_string(evcard, EVC_FORMAT_VCARD_30,
						data->params->filter);

		data->buf = g_string_append(data->buf, vcard);
		data->buf = g_string_append(data->buf, "\r\n");
		g_free(vcard);
	}

	DBG("collected %d vcards", count);

	data->count += count;

	g_list_free_full(contacts, g_object_unref);

done:
	if (data->queued_calls == 0) {
		GString *buf = data->buf;
		data->buf = NULL;

		data->contacts_cb(buf->str, buf->len, data->count,
						0, TRUE, data->user_data);

		g_string_free(buf, TRUE);

	}

	return;

canceled:
	if (data->queued_calls == 0)
		free_query_context(data);
}
示例#24
0
文件: bcas_stream.c 项目: 9060/tsniff
static void
bcas_stream_parse(BCASStream *self, BCASStreamCallbackFunc cbfn, gpointer user_data)
{
	BCASPacket packet;

	guint8 *p = self->raw_stream->data;
	guint left_size = self->raw_stream->len;
	guint parsed_size = 0;
	guint parsed_packets = 0;

	for (;;) {
		gint i;
		guint8 size, checksum, x = 0;

		/* 同期を取る */
		if (!self->is_synced) {
			self->is_synced = bcas_stream_sync(self);
			if (!self->is_synced) {
				g_warning("[bcas_stream_parse] couldn't sync stream at %u", self->pos);
				break;
			}

			self->n_sync_packets = 0;
			p = self->raw_stream->data;
			left_size = self->raw_stream->len;
			parsed_size = 0;
		}

		/* 1パケット分のデータが残っていなければ終了 */
		if (left_size < PACKET_MIN_SIZE) {
/* 			g_debug("[bcas_stream_parse] not enough stream (left=%d, expect=%d) at %u", */
/* 					left_size, PACKET_MIN_SIZE, self->pos); */
			break;
		} else if (left_size < PACKET_HEADER_SIZE + p[PACKET_LEN_INDEX] + 1) {
/* 			g_debug("[bcas_stream_parse] not enough stream (left=%d, expect=%d) at %u", */
/* 					left_size, p[PACKET_LEN_INDEX] + 1, self->pos); */
			break;
		}

		size = PACKET_HEADER_SIZE + p[PACKET_LEN_INDEX] + 1/* checksum */;
		checksum = p[size - 1];

		/* パケットのチェックサムを計算 */
		for (i = 0; i < PACKET_HEADER_SIZE + p[PACKET_LEN_INDEX]; ++i)
			x ^= p[i];

		/* チェックサムが一致しなければ再同期 */
		if (x != checksum) {
			guint strip_size;
			GString *dump = hexdump(p, size, TRUE);
			g_warning("[bcas_stream_parse] packet corrupted at %u [%s]", self->pos, dump->str);
			g_string_free(dump, TRUE);

			/* 解析済みパケットを削る(現パケットがECMコマンドであればそれも削る) */
			strip_size = parsed_size + (IS_ECM_REQUEST(p) ? PACKET_COMMAND_INDEX + 4 : 0);
			if (strip_size > 0) {
				self->raw_stream = g_byte_array_remove_range(self->raw_stream, 0, strip_size);
			}
			self->pos += strip_size;

			self->is_synced = FALSE;
			continue;
		}

		/* ここまでくれば、パケットとしては正しいので、コールバック関数を呼ぶ */
		++self->n_sync_packets;

		packet.header = (p[0] << 8) | p[1];
		packet.len = p[2];
		memcpy(packet.payload, &p[3], packet.len);
		if (cbfn)
			(*cbfn)(&packet, self->n_sync_packets == 1, user_data);

		++parsed_packets;
		p += size;
		parsed_size += size;
		left_size -= size;
		self->pos += size;
	}

	/* 解析の終わったストリームを削る */
	if (parsed_size > 0) {
		self->raw_stream = g_byte_array_remove_range(self->raw_stream, 0, parsed_size);
	}
	g_debug("[bcas_stream_parse] %d packets parsed (left=%d)", parsed_packets, self->raw_stream->len);
}
static EContact *
getNextCSVEntry (CSVImporter *gci,
                 FILE *f)
{
	EContact *contact = NULL;
	GString  *line;
	GString *str;
	gchar *buf;
	gint c;

	line = g_string_new ("");
	while (1) {
		c = fgetc (f);
		if (c == EOF)
			return NULL;
		if (c == '\n') {
			g_string_append_c (line, c);
			break;
		}
		if (c == '"') {
			g_string_append_c (line, c);
			c = fgetc (f);
			while (!feof (f) && c != '"') {
				g_string_append_c (line, c);
				c = fgetc (f);
			}
			g_string_append_c (line, c);
		}
		else
			g_string_append_c (line, c);
	}

	if (gci->count == 0 && importer != MOZILLA_IMPORTER) {
		gci->fields_map = map_fields (line->str, importer);
		g_string_free (line, TRUE);
		line = g_string_new ("");
		while (1) {
			c = fgetc (f);
			if (c == EOF)
				return NULL;
			if (c == '\n') {
				g_string_append_c (line, c);
				break;
			}
			if (c == '"') {
				g_string_append_c (line, c);
				c = fgetc (f);
				while (!feof (f) && c != '"') {
					g_string_append_c (line, c);
					c = fgetc (f);
				}
				g_string_append_c (line, c);
			}
			else
				g_string_append_c (line, c);
		}
		gci->count++;
	}

	str = g_string_new ("");
	str = g_string_append (str, line->str);

	g_string_free (line, TRUE);

	if (strlen (str->str) == 0) {
		g_string_free (str, TRUE);
		return NULL;
	}

	contact = e_contact_new ();

	buf = str->str;

	if (!parseLine (gci, contact, buf)) {
		g_object_unref (contact);
		return NULL;
	}
	gci->count++;

	g_string_free (str, TRUE);

	return contact;
}
示例#26
0
/* Basically, we build a new regex, either based on subset regex's, or substrings,
   that can be executed once over the whoel body, to match anything suitable.
   This is more efficient than multiple searches, and probably most (naive) strstr
   implementations, over long content.

   A small issue is that case-insenstivity wont work entirely correct for utf8 strings. */
int
camel_search_build_match_regex (regex_t *pattern, camel_search_flags_t type, int argc,
				void *argv_in, CamelException *ex)
{
	struct _ESExpResult **argv = argv_in;
	GString *match = g_string_new("");
	int c, i, count=0, err;
	char *word;
	int flags;

	/* build a regex pattern we can use to match the words, we OR them together */
	if (argc>1)
		g_string_append_c (match, '(');
	for (i = 0; i < argc; i++) {
		if (argv[i]->type == ESEXP_RES_STRING) {
			if (count > 0)
				g_string_append_c (match, '|');

			word = argv[i]->value.string;
			if (type & CAMEL_SEARCH_MATCH_REGEX) {
				/* no need to escape because this should already be a valid regex */
				g_string_append (match, word);
			} else {
				/* escape any special chars (not sure if this list is complete) */
				if (type & CAMEL_SEARCH_MATCH_START)
					g_string_append_c (match, '^');
				while ((c = *word++)) {
					if (strchr ("*\\.()[]^$+", c) != NULL) {
						g_string_append_c (match, '\\');
					}
					g_string_append_c (match, c);
				}
				if (type & CAMEL_SEARCH_MATCH_END)
					g_string_append_c (match, '^');
			}
			count++;
		} else {
			g_warning("Invalid type passed to body-contains match function");
		}
	}
	if (argc > 1)
		g_string_append_c (match, ')');
	flags = REG_EXTENDED|REG_NOSUB;
	if (type & CAMEL_SEARCH_MATCH_ICASE)
		flags |= REG_ICASE;
	if (type & CAMEL_SEARCH_MATCH_NEWLINE)
		flags |= REG_NEWLINE;
	err = regcomp (pattern, match->str, flags);
	if (err != 0) {
		/* regerror gets called twice to get the full error string
		   length to do proper posix error reporting */
		int len = regerror (err, pattern, 0, 0);
		char *buffer = g_malloc0 (len + 1);

		regerror (err, pattern, buffer, len);
		camel_exception_setv (ex, CAMEL_EXCEPTION_SYSTEM,
				      _("Regular expression compilation failed: %s: %s"),
				      match->str, buffer);

		regfree (pattern);
	}
	d(printf("Built regex: '%s'\n", match->str));
	g_string_free (match, TRUE);

	return err;
}
示例#27
0
int
main(int argc, char *argv[])
{
  int                 opt;
  gboolean            do_append          = FALSE;
  gboolean            verbose            = FALSE;
  int                 in_file_count      = 0;
  guint               snaplen            = 0;
#ifdef PCAP_NG_DEFAULT
  int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
#else
  int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
#endif
  int                 frame_type         = -2;
  int                 out_fd;
  merge_in_file_t    *in_files           = NULL, *in_file;
  int                 i;
  struct wtap_pkthdr *phdr, snap_phdr;
  wtap_dumper        *pdh;
  int                 open_err, read_err = 0, write_err, close_err;
  gchar              *err_info;
  int                 err_fileno;
  char               *out_filename       = NULL;
  gboolean            got_read_error     = FALSE, got_write_error = FALSE;
  int                 count;

#ifdef _WIN32
  arg_list_utf_16to8(argc, argv);
  create_app_running_mutex();
#endif /* _WIN32 */

  /* Process the options first */
  while ((opt = getopt(argc, argv, "aF:hs:T:vw:")) != -1) {

    switch (opt) {
    case 'a':
      do_append = !do_append;
      break;

    case 'F':
      file_type = wtap_short_string_to_file_type_subtype(optarg);
      if (file_type < 0) {
        fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
                optarg);
        list_capture_types();
        exit(1);
      }
      break;

    case 'h':
      usage(FALSE);
      exit(0);
      break;

    case 's':
      snaplen = get_positive_int(optarg, "snapshot length");
      break;

    case 'T':
      frame_type = wtap_short_string_to_encap(optarg);
      if (frame_type < 0) {
        fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
                optarg);
        list_encap_types();
        exit(1);
      }
      break;

    case 'v':
      verbose = TRUE;
      break;

    case 'w':
      out_filename = optarg;
      break;

    case '?':              /* Bad options if GNU getopt */
      switch(optopt) {
      case'F':
        list_capture_types();
        break;
      case'T':
        list_encap_types();
        break;
      default:
        usage(TRUE);
      }
      exit(1);
      break;
    }
  }

  /* check for proper args; at a minimum, must have an output
   * filename and one input file
   */
  in_file_count = argc - optind;
  if (!out_filename) {
    fprintf(stderr, "mergecap: an output filename must be set with -w\n");
    fprintf(stderr, "          run with -h for help\n");
    return 1;
  }
  if (in_file_count < 1) {
    fprintf(stderr, "mergecap: No input files were specified\n");
    return 1;
  }

  /* open the input files */
  if (!merge_open_in_files(in_file_count, &argv[optind], &in_files,
                           &open_err, &err_info, &err_fileno)) {
    fprintf(stderr, "mergecap: Can't open %s: %s\n", argv[optind + err_fileno],
            wtap_strerror(open_err));
    switch (open_err) {

    case WTAP_ERR_UNSUPPORTED:
    case WTAP_ERR_UNSUPPORTED_ENCAP:
    case WTAP_ERR_BAD_FILE:
      fprintf(stderr, "(%s)\n", err_info);
      g_free(err_info);
      break;
    }
    return 2;
  }

  if (verbose) {
    for (i = 0; i < in_file_count; i++)
      fprintf(stderr, "mergecap: %s is type %s.\n", argv[optind + i],
              wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
  }

  if (snaplen == 0) {
    /*
     * Snapshot length not specified - default to the maximum of the
     * snapshot lengths of the input files.
     */
    snaplen = merge_max_snapshot_length(in_file_count, in_files);
  }

  /* set the outfile frame type */
  if (frame_type == -2) {
    /*
     * Default to the appropriate frame type for the input files.
     */
    frame_type = merge_select_frame_type(in_file_count, in_files);
    if (verbose) {
      if (frame_type == WTAP_ENCAP_PER_PACKET) {
        /*
         * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
         */
        int first_frame_type, this_frame_type;

        first_frame_type = wtap_file_encap(in_files[0].wth);
        for (i = 1; i < in_file_count; i++) {
          this_frame_type = wtap_file_encap(in_files[i].wth);
          if (first_frame_type != this_frame_type) {
            fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
            fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
            fprintf(stderr, "          %s had type %s (%s)\n",
                    in_files[0].filename,
                    wtap_encap_string(first_frame_type),
                    wtap_encap_short_string(first_frame_type));
            fprintf(stderr, "          %s had type %s (%s)\n",
                    in_files[i].filename,
                    wtap_encap_string(this_frame_type),
                    wtap_encap_short_string(this_frame_type));
            break;
          }
        }
      }
      fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
              wtap_encap_string(frame_type),
              wtap_encap_short_string(frame_type));
    }
  }

  /* open the outfile */
  if (strncmp(out_filename, "-", 2) == 0) {
    /* use stdout as the outfile */
    out_fd = 1 /*stdout*/;
  } else {
    /* open the outfile */
    out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
    if (out_fd == -1) {
      fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
              out_filename, g_strerror(errno));
      exit(1);
    }
  }

  /* prepare the outfile */
  if(file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG ){
    wtapng_section_t *shb_hdr;
    GString *comment_gstr;
    wtapng_iface_descriptions_t *idb_inf = NULL, *idb_inf_merge_file;
    wtapng_if_descr_t int_data, *file_int_data;
    guint8 if_tsresol = 6;
    guint64 time_units_per_second = 1000000;

    shb_hdr = g_new(wtapng_section_t,1);
    comment_gstr = g_string_new("File created by merging: \n");

    for (i = 0; i < in_file_count; i++) {
      g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
    }
    shb_hdr->section_length = -1;
    /* options */
    shb_hdr->opt_comment   = comment_gstr->str; /* NULL if not available */
    shb_hdr->shb_hardware  = NULL;              /* NULL if not available, UTF-8 string containing the description of the hardware used to create this section. */
    shb_hdr->shb_os        = NULL;              /* NULL if not available, UTF-8 string containing the name of the operating system used to create this section. */
    shb_hdr->shb_user_appl = "mergecap";        /* NULL if not available, UTF-8 string containing the name of the application used to create this section. */

    for (i = 0; i < in_file_count; i++) {
      idb_inf_merge_file = wtap_file_get_idb_info(in_files[i].wth);
      file_int_data = &g_array_index (idb_inf_merge_file->interface_data, wtapng_if_descr_t, 0);
      if (file_int_data->time_units_per_second > time_units_per_second) {
        time_units_per_second = file_int_data->time_units_per_second;
        if_tsresol = file_int_data->if_tsresol;
      }
      g_free(idb_inf_merge_file);
    }
    if (time_units_per_second > 1000000) {
      /* We are using a better than microsecond precision; let's create a fake IDB */
      idb_inf = g_new(wtapng_iface_descriptions_t,1);
      idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
      int_data.wtap_encap            = frame_type;
      int_data.time_units_per_second = time_units_per_second;
      int_data.link_type             = wtap_wtap_encap_to_pcap_encap(frame_type);
      int_data.snap_len              = snaplen;
      int_data.if_name               = g_strdup("Unknown/not available in original file format(libpcap)");
      int_data.opt_comment           = NULL;
      int_data.if_description        = NULL;
      int_data.if_speed              = 0;
      int_data.if_tsresol            = if_tsresol;
      int_data.if_filter_str         = NULL;
      int_data.bpf_filter_len        = 0;
      int_data.if_filter_bpf_bytes   = NULL;
      int_data.if_os                 = NULL;
      int_data.if_fcslen             = -1;
      int_data.num_stat_entries      = 0;          /* Number of ISB:s */
      int_data.interface_statistics  = NULL;
      g_array_append_val(idb_inf->interface_data, int_data);
    }

    pdh = wtap_dump_fdopen_ng(out_fd, file_type, frame_type, snaplen,
                              FALSE /* compressed */, shb_hdr, idb_inf, &open_err);
    g_string_free(comment_gstr, TRUE);
  } else {
    pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, &open_err);
  }
  if (pdh == NULL) {
    merge_close_in_files(in_file_count, in_files);
    g_free(in_files);
    fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
            wtap_strerror(open_err));
    exit(1);
  }

  /* do the merge (or append) */
  count = 1;
  for (;;) {
    if (do_append)
      in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
                                         &err_info);
    else
      in_file = merge_read_packet(in_file_count, in_files, &read_err,
                                  &err_info);
    if (in_file == NULL) {
      /* EOF */
      break;
    }

    if (read_err != 0) {
      /* I/O error reading from in_file */
      got_read_error = TRUE;
      break;
    }

    if (verbose)
      fprintf(stderr, "Record: %u\n", count++);

    /* We simply write it, perhaps after truncating it; we could do other
     * things, like modify it. */
    phdr = wtap_phdr(in_file->wth);
    if (snaplen != 0 && phdr->caplen > snaplen) {
      snap_phdr = *phdr;
      snap_phdr.caplen = snaplen;
      phdr = &snap_phdr;
    }

    if (!wtap_dump(pdh, phdr, wtap_buf_ptr(in_file->wth), &write_err)) {
      got_write_error = TRUE;
      break;
    }
  }

  merge_close_in_files(in_file_count, in_files);
  if (!got_write_error) {
    if (!wtap_dump_close(pdh, &write_err))
      got_write_error = TRUE;
  } else {
    /*
     * We already got a write error; no need to report another
     * write error on close.
     *
     * Don't overwrite the earlier write error.
     */
    (void)wtap_dump_close(pdh, &close_err);
  }

  if (got_read_error) {
    /*
     * Find the file on which we got the error, and report the error.
     */
    for (i = 0; i < in_file_count; i++) {
      if (in_files[i].state == GOT_ERROR) {
        fprintf(stderr, "mergecap: Error reading %s: %s\n",
                in_files[i].filename, wtap_strerror(read_err));
        switch (read_err) {

        case WTAP_ERR_UNSUPPORTED:
        case WTAP_ERR_UNSUPPORTED_ENCAP:
        case WTAP_ERR_BAD_FILE:
          fprintf(stderr, "(%s)\n", err_info);
          g_free(err_info);
          break;
        }
      }
    }
  }

  if (got_write_error) {
    switch (write_err) {

    case WTAP_ERR_UNSUPPORTED_ENCAP:
      /*
       * This is a problem with the particular frame we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the frame number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    case WTAP_ERR_PACKET_TOO_LARGE:
      /*
       * This is a problem with the particular frame we're writing and
       * the file type and subtype we're wwriting; note that, and
       * report the frame number and file type/subtype.
       */
      fprintf(stderr, "mergecap: Frame %u of \"%s\" is too large for a \"%s\" file\n.",
              in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
              wtap_file_type_subtype_string(file_type));
      break;

    default:
      fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
              wtap_strerror(write_err));
      break;
    }
  }

  g_free(in_files);

  return (!got_read_error && !got_write_error) ? 0 : 2;
}
G_MODULE_EXPORT gboolean
tracker_extract_get_metadata (TrackerExtractInfo *info)
{
	TrackerSparqlBuilder *preupdate, *metadata;
	goffset size;
	GifFileType *gifFile = NULL;
	GString *where;
	const gchar *graph;
	gchar *filename, *uri;
	GFile *file;
	int fd;
#if GIFLIB_MAJOR >= 5
	int err;
#endif

	preupdate = tracker_extract_info_get_preupdate_builder (info);
	metadata = tracker_extract_info_get_metadata_builder (info);
	graph = tracker_extract_info_get_graph (info);

	file = tracker_extract_info_get_file (info);
	filename = g_file_get_path (file);
	size = tracker_file_get_size (filename);

	if (size < 64) {
		g_free (filename);
		return FALSE;
	}

	fd = tracker_file_open_fd (filename);

	if (fd == -1) {
		g_warning ("Could not open GIF file '%s': %s\n",
		           filename,
		           g_strerror (errno));
		g_free (filename);
		return FALSE;
	}	

#if GIFLIB_MAJOR < 5
	if ((gifFile = DGifOpenFileHandle (fd)) == NULL) {
		print_gif_error ();
#else   /* GIFLIB_MAJOR < 5 */
	if ((gifFile = DGifOpenFileHandle (fd, &err)) == NULL) {
		gif_error ("Could not open GIF file with handle", err);
#endif /* GIFLIB_MAJOR < 5 */
		g_free (filename);
		close (fd);
		return FALSE;
	}

	g_free (filename);

	tracker_sparql_builder_predicate (metadata, "a");
	tracker_sparql_builder_object (metadata, "nfo:Image");
	tracker_sparql_builder_object (metadata, "nmm:Photo");

	where = g_string_new ("");
	uri = g_file_get_uri (file);

	read_metadata (preupdate, metadata, where, gifFile, uri, graph);
	tracker_extract_info_set_where_clause (info, where->str);
	g_string_free (where, TRUE);

	g_free (uri);

	if (DGifCloseFile (gifFile, NULL) != GIF_OK) {
#if GIFLIB_MAJOR < 5
		print_gif_error ();
#else  /* GIFLIB_MAJOR < 5 */
		gif_error ("Could not close GIF file", gifFile->Error);
#endif /* GIFLIB_MAJOR < 5 */
	}

	return TRUE;
}
示例#29
0
static char *
parse_exec (EggDesktopFile  *desktop_file,
	    GSList         **documents,
	    GError         **error)
{
  char *exec, *p, *command;
  gboolean escape, single_quot, double_quot;
  GString *gs;

  exec = g_key_file_get_string (desktop_file->key_file,
				EGG_DESKTOP_FILE_GROUP,
				EGG_DESKTOP_FILE_KEY_EXEC,
				error);
  if (!exec)
    return NULL;

  /* Build the command */
  gs = g_string_new (NULL);
  escape = single_quot = double_quot = FALSE;

  for (p = exec; *p != '\0'; p++)
    {
      if (escape)
	{
	  escape = FALSE;
	  g_string_append_c (gs, *p);
	}
      else if (*p == '\\')
	{
	  if (!single_quot)
	    escape = TRUE;
	  g_string_append_c (gs, *p);
	}
      else if (*p == '\'')
	{
	  g_string_append_c (gs, *p);
	  if (!single_quot && !double_quot)
	    single_quot = TRUE;
	  else if (single_quot)
	    single_quot = FALSE;
	}
      else if (*p == '"')
	{
	  g_string_append_c (gs, *p);
	  if (!single_quot && !double_quot)
	    double_quot = TRUE;
	  else if (double_quot)
	    double_quot = FALSE;
	}
      else if (*p == '%' && p[1])
	{
	  do_percent_subst (desktop_file, p[1], gs, documents,
			    single_quot, double_quot);
	  p++;
	}
      else
	g_string_append_c (gs, *p);
    }

  g_free (exec);
  command = g_string_free (gs, FALSE);

  /* Prepend "xdg-terminal " if needed (FIXME: use gvfs) */
  if (g_key_file_has_key (desktop_file->key_file,
			  EGG_DESKTOP_FILE_GROUP,
			  EGG_DESKTOP_FILE_KEY_TERMINAL,
			  NULL))
    {
      GError *terminal_error = NULL;
      gboolean use_terminal =
	g_key_file_get_boolean (desktop_file->key_file,
				EGG_DESKTOP_FILE_GROUP,
				EGG_DESKTOP_FILE_KEY_TERMINAL,
				&terminal_error);
      if (terminal_error)
	{
	  g_free (command);
	  g_propagate_error (error, terminal_error);
	  return NULL;
	}

      if (use_terminal)
	{
	  gs = g_string_new ("xdg-terminal ");
	  append_quoted_word (gs, command, FALSE, FALSE);
	  g_free (command);
	  command = g_string_free (gs, FALSE);
	}
    }

  return command;
}
static gchar*
thunar_sbr_replace_renamer_pcre_exec (ThunarSbrReplaceRenamer *replace_renamer,
                                      const gchar             *subject)
{
  const gchar *r;
  GString     *result;
  gint         second;
  gint         first;
  gint         index;
  gint        *ovec;
  gint         olen;
  gint         rc;

  /* guess an initial ovec size */
  olen = (replace_renamer->pcre_capture_count + 10) * 3;
  ovec = g_new0 (gint, olen);

  /* try to match the subject (increasing ovec on-demand) */
  for (rc = 0; rc <= 0; )
    {
      /* try to exec, will return 0 if the ovec is too small */
      rc = pcre_exec (replace_renamer->pcre_pattern, NULL, subject, strlen (subject), 0, PCRE_NOTEMPTY, ovec, olen);
      if (G_UNLIKELY (rc < 0))
        {
          /* no match or error */
          g_free (ovec);
          return g_strdup (subject);
        }
      else if (rc == 0)
        {
          /* ovec too small, try to increase */
          olen += 18;
          ovec = g_realloc (ovec, olen * sizeof (gint));
        }
    }

  /* allocate a string for the result */
  result = g_string_sized_new (32);

  /* append the text before the match */
  g_string_append_len (result, subject, ovec[0]);

  /* apply the replacement */
  for (r = replace_renamer->replacement; *r != '\0'; r = g_utf8_next_char (r))
    {
      if (G_UNLIKELY ((r[0] == '\\' || r[0] == '$') && r[1] != '\0'))
        {
          /* skip the first char ($ or \) */
          r += 1;

          /* default to no subst */
          first = 0;
          second = 0;

          /* check the char after the \ or $ */
          if (r[0] == '+' && rc > 1)
            {
              /* \+ and $+ is replaced with the last subpattern */
              first = ovec[(rc - 1) * 2];
              second = ovec[(rc - 1) * 2 + 1];
            }
          else if (r[0] == '&')
            {
              /* \& and $& is replaced with the first subpattern (the whole match) */
              first = ovec[0];
              second = ovec[1];
            }
          else if (r[0] == '`')
            {
              /* \` and $` is replaced with the text before the whole match */
              first = 0;
              second = ovec[0];
            }
          else if (r[0] == '\'')
            {
              /* \' and $' is replaced with the text after the whole match */
              first = ovec[1];
              second = strlen (subject) - 1;
            }
          else if (g_ascii_isdigit (r[0]))
            {
              /* \<num> and $<num> is replaced with the <num>th subpattern */
              index = (r[0] - '0');
              if (G_LIKELY (index >= 0 && index < rc))
                {
                  first = ovec[2 * index];
                  second = ovec[2 * index + 1];
                }
            }
          else if (r[-1] == r[0])
            {
              /* just add the $ or \ char */
              g_string_append_c (result, r[0]);
              continue;
            }
          else
            {
              /* just ignore the $ or \ char */
              continue;
            }

          /* substitute the string */
          g_string_append_len (result, subject + first, second - first);
        }
      else
        {
          /* just append the unichar */
          g_string_append_unichar (result, g_utf8_get_char (r));
        }
    }

  /* append the text after the match */
  g_string_append (result, subject + ovec[1]);

  /* release the output vector */
  g_free (ovec);

  /* return the new name */
  return g_string_free (result, FALSE);
}