コード例 #1
0
ファイル: html.c プロジェクト: Distrotech/php-src
/* {{{ entity_charset determine_charset
 * returns the charset identifier based on current locale or a hint.
 * defaults to UTF-8 */
static enum entity_charset determine_charset(char *charset_hint)
{
	int i;
	enum entity_charset charset = cs_utf_8;
	size_t len = 0;
	const zend_encoding *zenc;

	/* Default is now UTF-8 */
	if (charset_hint == NULL)
		return cs_utf_8;

	if ((len = strlen(charset_hint)) != 0) {
		goto det_charset;
	}

	zenc = zend_multibyte_get_internal_encoding();
	if (zenc != NULL) {
		charset_hint = (char *)zend_multibyte_get_encoding_name(zenc);
		if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
			if ((len == 4) /* sizeof (auto|pass) */ &&
					/* XXX should the "wchar" be ignored as well?? */
					(!memcmp("pass", charset_hint, 4) ||
					 !memcmp("auto", charset_hint, 4))) {
				charset_hint = NULL;
				len = 0;
			} else {
				goto det_charset;
			}
		}
	}

	charset_hint = SG(default_charset);
	if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
		goto det_charset;
	}

	/* try to detect the charset for the locale */
#if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET)
	charset_hint = nl_langinfo(CODESET);
	if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
		goto det_charset;
	}
#endif

#if HAVE_LOCALE_H
	/* try to figure out the charset from the locale */
	{
		char *localename;
		char *dot, *at;

		/* lang[_territory][.codeset][@modifier] */
		localename = setlocale(LC_CTYPE, NULL);

		dot = strchr(localename, '.');
		if (dot) {
			dot++;
			/* locale specifies a codeset */
			at = strchr(dot, '@');
			if (at)
				len = at - dot;
			else
				len = strlen(dot);
			charset_hint = dot;
		} else {
			/* no explicit name; see if the name itself
			 * is the charset */
			charset_hint = localename;
			len = strlen(charset_hint);
		}
	}
#endif

det_charset:

	if (charset_hint) {
		int found = 0;

		/* now walk the charset map and look for the codeset */
		for (i = 0; i < sizeof(charset_map)/sizeof(charset_map[0]); i++) {
			if (len == charset_map[i].codeset_len &&
			    zend_binary_strcasecmp(charset_hint, len, charset_map[i].codeset, len) == 0) {
				charset = charset_map[i].charset;
				found = 1;
				break;
			}
		}
		if (!found) {
			php_error_docref(NULL, E_WARNING, "charset `%s' not supported, assuming utf-8",
					charset_hint);
		}
	}
	return charset;
}
コード例 #2
0
ファイル: hyfiletext.c プロジェクト: freeVM/freeVM
static char*
buf_write_using_iconv (struct HyPortLibrary *portLibrary,
                        const char *buf, IDATA nbytes)
{
    UDATA outBufLen = 512;
    iconv_t converter;
    size_t inbytesleft, outbytesleft;
    char *inbuf;
    char *outbuf;
    char *bufStart;
    /* iconv_open is not an a2e function, so we need to pass it honest-to-goodness EBCDIC strings */
    converter = iconv_open (nl_langinfo (CODESET), "UTF-8");
    if (converter == (iconv_t) - 1)
    {
        /* no converter available for this code set. Just dump the UTF-8 chars */
        outbuf = portLibrary->mem_allocate_memory (portLibrary, nbytes + 1);
        memcpy(outbuf, buf, nbytes);
        outbuf[nbytes] = '\0';
        return  outbuf;
    }
    bufStart = portLibrary->mem_allocate_memory (portLibrary, outBufLen);
    outbuf = bufStart;
    inbuf = (char *) buf;         /* for some reason this argument isn't const */
    inbytesleft = nbytes;
    outbytesleft = outBufLen;
    while ((size_t) - 1 ==
        iconv (converter, &inbuf, &inbytesleft, &outbuf, &outbytesleft))
    {
        if (errno == E2BIG)
        {
            /* grow the buffer by 512 more bytes */
            char *newBuf =
                portLibrary->mem_allocate_memory (portLibrary, outBufLen += 512);
            if (newBuf == NULL)
            {
                break;            /* just output what we've got so far */
            }
            /* copy over the work we've already done */
            memcpy (newBuf, bufStart, outbuf - bufStart);
            /* set up the new buffer, and free the old one */
            outbytesleft = outBufLen - (outbuf - bufStart);
            outbuf = newBuf + (outbuf - bufStart);
            portLibrary->mem_free_memory (portLibrary, bufStart);
            bufStart = newBuf;
        }
        else
        {
            /* failure -- just output the unconverted data */
            iconv_close (converter);
            outbuf = portLibrary->mem_allocate_memory (portLibrary, nbytes + 1);
            memcpy(outbuf, buf, nbytes);
            outbuf[nbytes] = '\0';
            portLibrary->mem_free_memory (portLibrary, bufStart);
            return  outbuf;
        }
    }
    iconv_close (converter);
    outbuf = portLibrary->mem_allocate_memory (portLibrary, outbuf - bufStart + 1);
    memcpy(outbuf, buf, outbuf - bufStart);
    outbuf[outbuf - bufStart] = '\0';
    portLibrary->mem_free_memory (portLibrary, bufStart);
    return outbuf;
}
コード例 #3
0
ファイル: localcharset.c プロジェクト: 201528013329008/htmljs
STATIC
#endif
const char *
locale_charset (void)
{
  const char *codeset;
  const char *aliases;

#if !(defined WIN32_NATIVE || defined OS2)

# if HAVE_LANGINFO_CODESET

  /* Most systems support nl_langinfo (CODESET) nowadays.  */
  codeset = nl_langinfo (CODESET);

#  ifdef __CYGWIN__
  /* Cygwin < 1.7 does not have locales.  nl_langinfo (CODESET) always
     returns "US-ASCII".  Return the suffix of the locale name from the
     environment variables (if present) or the codepage as a number.  */
  if (codeset != NULL && strcmp (codeset, "US-ASCII") == 0)
    {
      const char *locale;
      static char buf[2 + 10 + 1];

      locale = getenv ("LC_ALL");
      if (locale == NULL || locale[0] == '\0')
        {
          locale = getenv ("LC_CTYPE");
          if (locale == NULL || locale[0] == '\0')
            locale = getenv ("LANG");
        }
      if (locale != NULL && locale[0] != '\0')
        {
          /* If the locale name contains an encoding after the dot, return
             it.  */
          const char *dot = strchr (locale, '.');

          if (dot != NULL)
            {
              const char *modifier;

              dot++;
              /* Look for the possible @... trailer and remove it, if any.  */
              modifier = strchr (dot, '@');
              if (modifier == NULL)
                return dot;
              if (modifier - dot < sizeof (buf))
                {
                  memcpy (buf, dot, modifier - dot);
                  buf [modifier - dot] = '\0';
                  return buf;
                }
            }
        }

      /* Woe32 has a function returning the locale's codepage as a number:
         GetACP().  This encoding is used by Cygwin, unless the user has set
         the environment variable CYGWIN=codepage:oem (which very few people
         do).
         Output directed to console windows needs to be converted (to
         GetOEMCP() if the console is using a raster font, or to
         GetConsoleOutputCP() if it is using a TrueType font).  Cygwin does
         this conversion transparently (see winsup/cygwin/fhandler_console.cc),
         converting to GetConsoleOutputCP().  This leads to correct results,
         except when SetConsoleOutputCP has been called and a raster font is
         in use.  */
      sprintf (buf, "CP%u", GetACP ());
      codeset = buf;
    }
#  endif

# else

  /* On old systems which lack it, use setlocale or getenv.  */
  const char *locale = NULL;

  /* But most old systems don't have a complete set of locales.  Some
     (like SunOS 4 or DJGPP) have only the C locale.  Therefore we don't
     use setlocale here; it would return "C" when it doesn't support the
     locale name the user has set.  */
#  if 0
  locale = setlocale (LC_CTYPE, NULL);
#  endif
  if (locale == NULL || locale[0] == '\0')
    {
      locale = getenv ("LC_ALL");
      if (locale == NULL || locale[0] == '\0')
        {
          locale = getenv ("LC_CTYPE");
          if (locale == NULL || locale[0] == '\0')
            locale = getenv ("LANG");
        }
    }

  /* On some old systems, one used to set locale = "iso8859_1". On others,
     you set it to "language_COUNTRY.charset". In any case, we resolve it
     through the charset.alias file.  */
  codeset = locale;

# endif

#elif defined WIN32_NATIVE

  static char buf[2 + 10 + 1];

  /* Woe32 has a function returning the locale's codepage as a number:
     GetACP().
     When the output goes to a console window, it needs to be provided in
     GetOEMCP() encoding if the console is using a raster font, or in
     GetConsoleOutputCP() encoding if it is using a TrueType font.
     But in GUI programs and for output sent to files and pipes, GetACP()
     encoding is the best bet.  */
  sprintf (buf, "CP%u", GetACP ());
  codeset = buf;

#elif defined OS2

  const char *locale;
  static char buf[2 + 10 + 1];
  ULONG cp[3];
  ULONG cplen;

  /* Allow user to override the codeset, as set in the operating system,
     with standard language environment variables.  */
  locale = getenv ("LC_ALL");
  if (locale == NULL || locale[0] == '\0')
    {
      locale = getenv ("LC_CTYPE");
      if (locale == NULL || locale[0] == '\0')
        locale = getenv ("LANG");
    }
  if (locale != NULL && locale[0] != '\0')
    {
      /* If the locale name contains an encoding after the dot, return it.  */
      const char *dot = strchr (locale, '.');

      if (dot != NULL)
        {
          const char *modifier;

          dot++;
          /* Look for the possible @... trailer and remove it, if any.  */
          modifier = strchr (dot, '@');
          if (modifier == NULL)
            return dot;
          if (modifier - dot < sizeof (buf))
            {
              memcpy (buf, dot, modifier - dot);
              buf [modifier - dot] = '\0';
              return buf;
            }
        }

      /* Resolve through the charset.alias file.  */
      codeset = locale;
    }
  else
    {
      /* OS/2 has a function returning the locale's codepage as a number.  */
      if (DosQueryCp (sizeof (cp), cp, &cplen))
        codeset = "";
      else
        {
          sprintf (buf, "CP%u", cp[0]);
          codeset = buf;
        }
    }

#endif

  if (codeset == NULL)
    /* The canonical name cannot be determined.  */
    codeset = "";

  /* Resolve alias. */
  for (aliases = get_charset_aliases ();
       *aliases != '\0';
       aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
    if (strcmp (codeset, aliases) == 0
        || (aliases[0] == '*' && aliases[1] == '\0'))
      {
        codeset = aliases + strlen (aliases) + 1;
        break;
      }

  /* Don't return an empty string.  GNU libc and GNU libiconv interpret
     the empty string as denoting "the locale's character encoding",
     thus GNU libiconv would call this function a second time.  */
  if (codeset[0] == '\0')
    codeset = "ASCII";

  return codeset;
}
コード例 #4
0
ファイル: utf8-posix.cpp プロジェクト: ryenus/vbox
/**
 * Gets the codeset of the current locale (LC_CTYPE).
 *
 * @returns Pointer to read-only string with the codeset name.
 */
DECLHIDDEN(const char *) rtStrGetLocaleCodeset(void)
{
    return nl_langinfo(CODESET);
}
コード例 #5
0
ファイル: tmux.c プロジェクト: wilywampa/tmux
int
main(int argc, char **argv)
{
	char					*path, *label, tmp[PATH_MAX];
	char					*shellcmd = NULL, **var;
	const char				*s, *shell;
	int					 opt, flags, keys;
	const struct options_table_entry	*oe;

	if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL) {
		if (setlocale(LC_CTYPE, "") == NULL)
			errx(1, "invalid LC_ALL, LC_CTYPE or LANG");
		s = nl_langinfo(CODESET);
		if (strcasecmp(s, "UTF-8") != 0 && strcasecmp(s, "UTF8") != 0)
			errx(1, "need UTF-8 locale (LC_CTYPE) but have %s", s);
	}

	setlocale(LC_TIME, "");
	tzset();

	if (**argv == '-')
		flags = CLIENT_LOGIN;
	else
		flags = 0;

	label = path = NULL;
	while ((opt = getopt(argc, argv, "2c:Cdf:lL:qS:uUVv")) != -1) {
		switch (opt) {
		case '2':
			flags |= CLIENT_256COLOURS;
			break;
		case 'c':
			free(shellcmd);
			shellcmd = xstrdup(optarg);
			break;
		case 'C':
			if (flags & CLIENT_CONTROL)
				flags |= CLIENT_CONTROLCONTROL;
			else
				flags |= CLIENT_CONTROL;
			break;
		case 'V':
			printf("%s %s\n", getprogname(), VERSION);
			exit(0);
		case 'f':
			set_cfg_file(optarg);
			break;
		case 'l':
			flags |= CLIENT_LOGIN;
			break;
		case 'L':
			free(label);
			label = xstrdup(optarg);
			break;
		case 'q':
			break;
		case 'S':
			free(path);
			path = xstrdup(optarg);
			break;
		case 'u':
			flags |= CLIENT_UTF8;
			break;
		case 'v':
			log_add_level();
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (shellcmd != NULL && argc != 0)
		usage();

	if ((ptm_fd = getptmfd()) == -1)
		err(1, "getptmfd");
	if (pledge("stdio rpath wpath cpath flock fattr unix getpw sendfd "
	    "recvfd proc exec tty ps", NULL) != 0)
		err(1, "pledge");

	/*
	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
	 * UTF-8, it is a safe assumption that either they are using a UTF-8
	 * terminal, or if not they know that output from UTF-8-capable
	 * programs may be wrong.
	 */
	if (getenv("TMUX") != NULL)
		flags |= CLIENT_UTF8;
	else {
		s = getenv("LC_ALL");
		if (s == NULL || *s == '\0')
			s = getenv("LC_CTYPE");
		if (s == NULL || *s == '\0')
			s = getenv("LANG");
		if (s == NULL || *s == '\0')
			s = "";
		if (strcasestr(s, "UTF-8") != NULL ||
		    strcasestr(s, "UTF8") != NULL)
			flags |= CLIENT_UTF8;
	}

	global_hooks = hooks_create(NULL);

	global_environ = environ_create();
	for (var = environ; *var != NULL; var++)
		environ_put(global_environ, *var);
	if (getcwd(tmp, sizeof tmp) != NULL)
		environ_set(global_environ, "PWD", "%s", tmp);

	global_options = options_create(NULL);
	global_s_options = options_create(NULL);
	global_w_options = options_create(NULL);
	for (oe = options_table; oe->name != NULL; oe++) {
		if (oe->scope == OPTIONS_TABLE_SERVER)
			options_default(global_options, oe);
		if (oe->scope == OPTIONS_TABLE_SESSION)
			options_default(global_s_options, oe);
		if (oe->scope == OPTIONS_TABLE_WINDOW)
			options_default(global_w_options, oe);
	}

	/*
	 * The default shell comes from SHELL or from the user's passwd entry
	 * if available.
	 */
	shell = getshell();
	options_set_string(global_s_options, "default-shell", 0, "%s", shell);

	/* Override keys to vi if VISUAL or EDITOR are set. */
	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
		if (strrchr(s, '/') != NULL)
			s = strrchr(s, '/') + 1;
		if (strstr(s, "vi") != NULL)
			keys = MODEKEY_VI;
		else
			keys = MODEKEY_EMACS;
		options_set_number(global_s_options, "status-keys", keys);
		options_set_number(global_w_options, "mode-keys", keys);
	}

	/*
	 * If socket is specified on the command-line with -S or -L, it is
	 * used. Otherwise, $TMUX is checked and if that fails "default" is
	 * used.
	 */
	if (path == NULL && label == NULL) {
		s = getenv("TMUX");
		if (s != NULL && *s != '\0' && *s != ',') {
			path = xstrdup(s);
			path[strcspn(path, ",")] = '\0';
		}
	}
	if (path == NULL && (path = make_label(label)) == NULL) {
		fprintf(stderr, "can't create socket: %s\n", strerror(errno));
		exit(1);
	}
	socket_path = path;
	free(label);

	/* Pass control to the client. */
	exit(client_main(osdep_event_init(), argc, argv, flags, shellcmd));
}
コード例 #6
0
ファイル: r2t.c プロジェクト: dunn/rsstail
int main(int argc, char *argv[])
{
	char **url = NULL;
	int n_url = 0, cur_url = 0;
	int check_interval = 15 * 60;
	mrss_t **data_prev = NULL;
	mrss_t **data_cur = NULL;
	char *proxy = NULL, *proxy_auth = NULL;
	int sw = 0;
	int verbose = 0;
	char show_timestamp = 0, show_link = 0, show_description = 0, show_pubdate = 0, show_author = 0, show_comments = 0;
	char strip_html = 0, no_error_exit = 0;
	char one_shot = 0;
	char no_heading = 0;
	int bytes_limit = 0;
	time_t last_changed = (time_t)0;
	char continue_on_error = 0;
	int show_n = -1;
	char *heading = NULL;
	mrss_options_t mot;
	char *auth = NULL;
	char *current_encoding = NULL;
	char reverse = 0;
	iconv_t converter = 0;

	memset(&mot, 0x00, sizeof(mot));

	while((sw = getopt(argc, argv, "A:Z:1b:PHztldrpacu:Ni:n:x:y:vVh")) != -1)
	{
		switch(sw)
		{
			case 'A':
				auth = optarg;
				break;

			case 'Z':
				heading = optarg;
				break;

			case 'N':
				no_heading = 1;
				break;

			case '1':
				one_shot = 1;
				break;

			case 'b':
				bytes_limit = atoi(optarg);
				if (bytes_limit <= 0)
				{
					printf("-b requires a number > 0\n");
					return 1;
				}
				break;

			case 'P':
				no_error_exit = 1;
				break;

			case 'H':
				strip_html = 1;
				break;

			case 'n':
				show_n = atoi(optarg);
				if (show_n < 0)
				{
					printf("-n requires an positive value\n");
					return 1;
				}
				else if (show_n > 50)
					printf("Initially showing more then 50 items, must be one hell of an rss feed!\n");
				break;

#if 0
			case 'o':
				dummy = optarg[strlen(optarg) - 1];
				max_age = atoi(optarg);
				if (max_age < 0)
				{
					printf("-o requires an positive value\n");
					return 1;
				}
				if (dummy == 's')
					max_age *= 1;
				else if (dummy == 'M')
					max_age *= 60;
				else if (dummy == 'h')
					max_age *= 3600;
				else if (dummy == 'd')
					max_age *= 86400;
				else if (dummy == 'm')
					max_age *= 86400 * 31;
				else if (dummy == 'y')
					max_age *= 86400 * 365.25;
				else if (isalpha(dummy))
				{
					printf("'%c' is a not recognized multiplier\n", dummy);
					return 1;
				}
				break;
#endif

			case 'z':
				continue_on_error = 1;
				break;

			case 't':
				show_timestamp = 1;
				break;

			case 'l':
				show_link = 1;
				break;

			case 'd':
				show_description = 1;
				break;

			case 'r':
				reverse = 1;
				break;

			case 'p':
				show_pubdate = 1;
				break;

			case 'a':
				show_author = 1;
				break;

			case 'c':
				show_comments = 1;
				break;

			case 'u':
				url = (char **)realloc(url, sizeof(char *) * (n_url + 1));
				if (!url)
				{
					fprintf(stderr, "Cannot allocate memory\n");
					return 2;
				}

				url[n_url++] = optarg;

				break;

			case 'i':
				check_interval = atoi(optarg);
				break;

			case 'x':
				proxy = optarg;
				break;

			case 'y':
				proxy_auth = optarg;
				break;

			case 'v':
				verbose++;
				break;

			case 'V':
				version();
				return 1;

			case 'h':
			default:
				usage();
				return 1;
		}
	}

	mot.timeout = check_interval;
	mot.proxy = proxy;
	mot.proxy_authentication = proxy_auth;
	mot.user_agent = (char *)name;
	mot.authentication = auth;

	if (n_url == 0)
	{
		fprintf(stderr, "Please give the URL of the RSS feed to check with the '-u' parameter.\n");
		return 1;
	}

	data_prev = (mrss_t **)calloc(n_url, sizeof(mrss_t));
	data_cur  = (mrss_t **)calloc(n_url, sizeof(mrss_t));
	if (!data_prev || !data_cur)
	{
		fprintf(stderr, "Cannot allocate memory\n");
		return 2;
	}

	setlocale(LC_ALL, "");
	current_encoding = nl_langinfo(CODESET);

	if (verbose)
	{
		int loop;

		printf("Monitoring RSS feeds:\n");

		for(loop=0; loop<n_url; loop++)
			printf("\t%s\n", url[loop]);

		printf("Check interval: %d\n", check_interval);
		printf("Output current_encoding: %s\n", current_encoding);
	}

	for(;;)
	{
		mrss_error_t err_read;
		mrss_item_t *item_cur = NULL;
		mrss_item_t *first_item[n_url];
		mrss_item_t *tmp_first_item;
		time_t cur_last_changed;
		int n_shown = 0;

		if (verbose)
			printf("Retrieving RSS feed '%s'...\n", url[cur_url]);

		if ((err_read = mrss_get_last_modified_with_options(url[cur_url], &cur_last_changed, &mot)) != MRSS_OK)
		{
			if (err_read == MRSS_ERR_POSIX)
			{
				if (errno == EINPROGRESS)
				{
					fprintf(stderr, "Time-out while connecting to RSS feed, continuing\n");
					goto goto_next_url;
				}
			}

			fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));

			if (no_error_exit)
				goto goto_next_url;

			return 2;
		}

		if (cur_last_changed == last_changed && cur_last_changed != 0)
		{
			if (verbose)
				printf("Feed did not change since last check.\n");

			goto goto_next_url;
		}
		else if (verbose > 2)
		{
			printf("Feed change detected, %s", ctime(&cur_last_changed));
		}

		last_changed = cur_last_changed;

		if ((err_read = mrss_parse_url_with_options(url[cur_url], &data_cur[cur_url], &mot)) != MRSS_OK)
		{
			if (err_read == MRSS_ERR_POSIX)
			{
				if (errno == EINPROGRESS)
				{
					fprintf(stderr, "Time-out while connecting to RSS feed, continuing\n");
					goto goto_next_url;
				}
			}
			else if (err_read == MRSS_ERR_PARSER && continue_on_error)
			{
				fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));
				goto goto_next_url;
			}

			fprintf(stderr, "Error reading RSS feed: %s\n", mrss_strerror(err_read));

			if (no_error_exit)
				goto goto_next_url;

			return 2;
		}

		if (data_cur[cur_url]->encoding == NULL) {
			data_cur[cur_url]->encoding = "utf-8";
		}

		if (verbose)
			printf("Creating converter %s -> %s\n", data_cur[cur_url] -> encoding, current_encoding);

		converter = iconv_open(current_encoding, data_cur[cur_url] -> encoding);

		if (converter == (iconv_t) -1)
		{
			fprintf(stderr, "Error creating converter: %s \n", strerror(errno));
			return 2;
		}

		item_cur = data_cur[cur_url] -> item;

		if (reverse)
		{
			if (verbose)
				printf("Reversing...\n");

			mrss_item_t *rev_item_cur = NULL;
			mrss_item_t *rev_item_last = NULL;

			for (;;)
			{
				rev_item_last = rev_item_cur;
				rev_item_cur = item_cur;

				if (!item_cur)
					break;

				if (!item_cur -> next)
				{
					rev_item_cur -> next = rev_item_last;
					break;
				}

				item_cur = item_cur -> next;
				rev_item_cur -> next = rev_item_last;
			}
		}

		tmp_first_item = item_cur;

		while(item_cur)
		{
			if ((data_prev[cur_url] && is_new_record(first_item[cur_url], item_cur) != -1) || !data_prev[cur_url])
			{
				if (!data_prev[cur_url] && n_shown >= show_n && show_n != -1)
				{
					item_cur = item_cur -> next;
					continue;
				}

				n_shown++;

				if (show_link + show_description + show_pubdate + show_author + show_comments > 1)
					printf("\n");

				if (show_timestamp)
				{
					time_t now = time(NULL);
					struct tm *now_tm = localtime(&now);

					printf("%04d/%02d/%02d %02d:%02d:%02d  ",
							now_tm -> tm_year + 1900,
							now_tm -> tm_mon + 1,
							now_tm -> tm_mday,
							now_tm -> tm_hour,
							now_tm -> tm_min,
							now_tm -> tm_sec);
				}

				if (heading)
					printf(" %s", heading);

				if (item_cur -> title != NULL)
				{
					char *title = my_convert(converter, item_cur -> title);

					if (title)
					{
						printf("%s%s\n", no_heading?" ":"Title: ", title);
						free(title);
					}
				}

				if (show_link && item_cur -> link != NULL)
				{
					char *link = my_convert(converter, item_cur -> link);

					if (link)
					{
						printf("%s%s\n", no_heading?" ":"Link: ", item_cur -> link);
						free(link);
					}
				}

				if (show_description && item_cur -> description != NULL)
				{
					if (strip_html)
					{
						char *stripped = remove_html_tags(item_cur -> description);

						if (bytes_limit != 0 && bytes_limit < strlen(stripped))
							stripped[bytes_limit] = 0x00;

						char *description = my_convert(converter, stripped);
						if (description)
						{
							printf("%s%s\n", no_heading?" ":"Description: ", description);
							free(description);
						}

						free(stripped);
					}
					else
					{
						if (bytes_limit != 0 && bytes_limit < strlen(item_cur -> description))
							(item_cur -> description)[bytes_limit] = 0x00;

						char *description = my_convert(converter, item_cur -> description);
						if (description)
						{
							printf("%s%s\n", no_heading?" ":"Description: ", description);
							free(description);
						}
					}
				}

				if (show_pubdate && item_cur -> pubDate != NULL)
					printf("%s%s\n", no_heading?" ":"Pub.date: ", item_cur -> pubDate);

				if (show_author && item_cur -> author != NULL){
					char *author = my_convert(converter, item_cur -> author);
					if (author)
					{
						printf("%s%s\n", no_heading?" ":"Author: ", author);
						free(author);
					}
				}

				if (show_comments && item_cur -> comments != NULL)
				{
					if (bytes_limit != 0 && bytes_limit < strlen(item_cur -> comments))
						(item_cur -> comments)[bytes_limit] = 0x00;

					char *comments = my_convert(converter, item_cur -> comments);
					if (comments)
					{
						printf("%s%s\n", no_heading?" ":"Comments: ", item_cur -> comments);
						free(comments);
					}
				}
			}

			item_cur = item_cur -> next;
		}

		if (data_prev[cur_url])
		{
			mrss_error_t err_free = mrss_free(data_prev[cur_url]);

			if (err_free != MRSS_OK)
			{
				fprintf(stderr, "Error freeing up memory: %s\n", mrss_strerror(err_read));

				if (no_error_exit)
					goto goto_next_url;

				return 2;
			}
		}

		data_prev[cur_url] = data_cur[cur_url];
		data_cur[cur_url] = NULL;
		first_item[cur_url] = tmp_first_item;

goto_next_url:
		if (converter)
		{
			iconv_close(converter);
			converter = 0;
		}

		cur_url++;
		if (cur_url >= n_url)
			cur_url = 0;

		fflush(stdout);

		if (one_shot)
			break;

		if (verbose > 2)
			printf("Sleeping...\n");

		sleep(check_interval / n_url);
	}

	return 0;
}
コード例 #7
0
ファイル: main.c プロジェクト: NickMcConnell/FirstAgeAngband
/**
 * Simple "main" function for multiple platforms.
 *
 * Note the special "--" option which terminates the processing of
 * standard options.  All non-standard options (if any) are passed
 * directly to the "init_xxx()" function.
 */
int main(int argc, char *argv[])
{
	int i;

	bool done = FALSE;

	const char *mstr = NULL;
	const char *soundstr = NULL;

	bool args = TRUE;

	/* Save the "program name" XXX XXX XXX */
	argv0 = argv[0];

#ifdef UNIX

	/* Default permissions on files */
	(void)umask(022);

	/* Get the user id */
	player_uid = getuid();

#endif /* UNIX */

#ifdef SETGID

	/* Save the effective GID for later recall */
	player_egid = getegid();

#endif /* UNIX */


	/* Drop permissions */
	safe_setuid_drop();

	/* Get the file paths 
	 * Paths may be overriden by -d options, so this has to occur *before* 
	 * processing command line args */
	init_stuff();

	/* Process the command line arguments */
	for (i = 1; args && (i < argc); i++) {
		const char *arg = argv[i];

		/* Require proper options */
		if (*arg++ != '-') goto usage;

		/* Analyze option */
		switch (*arg++)
		{
			case 'l':
				list_saves();
				exit(0);

			case 'n':
				new_game = TRUE;
				break;

			case 'w':
				arg_wizard = TRUE;
				break;

			case 'p':
				arg_power = TRUE;
				break;

			case 'r':
				arg_rebalance = TRUE;
				break;

			case 'g':
				/* Default graphics tile */
				/* in graphics.txt, 2 corresponds to adam bolt's tiles */
				arg_graphics = 2; 
				if (*arg) arg_graphics = atoi(arg);
				break;

			case 'u': {

				if (!*arg) goto usage;
				my_strcpy(op_ptr->full_name, arg, sizeof op_ptr->full_name);

				/* The difference here is because on setgid we have to be
				 * careful to only let the player have savefiles stored in
				 * the central save directory.  Sanitising input using
				 * player_safe_name() removes anything like that.
				 *
				 * But if the player is running with per-user saves, they
				 * can do whatever the hell they want.
				 */
#ifdef SETGID
				savefile_set_name(player_safe_name(player, FALSE));
#else
				savefile_set_name(arg);
#endif /* SETGID */

				continue;
			}

			case 'm':
				if (!*arg) goto usage;
				mstr = arg;
				continue;

			case 's':
				if (!*arg) goto usage;
				soundstr = arg;
				continue;

			case 'd':
				change_path(arg);
				continue;

			case 'x':
				debug_opt(arg);
				continue;

			case '-':
				argv[i] = argv[0];
				argc = argc - i;
				argv = argv + i;
				args = FALSE;
				break;

			default:
			usage:
				puts("Usage: angband [options] [-- subopts]");
				puts("  -n             Start a new character (WARNING: overwrites default savefile without -u)");
				puts("  -l             Lists all savefiles you can play");
				puts("  -w             Resurrect dead character (marks savefile)");
				puts("  -r             Rebalance monsters");
				puts("  -g             Request graphics mode");
				puts("  -x<opt>        Debug options; see -xhelp");
				puts("  -u<who>        Use your <who> savefile");
				puts("  -d<dir>=<path> Override a specific directory with <path>. <path> can be:");
				for (i = 0; i < (int)N_ELEMENTS(change_path_values); i++) {
#ifdef SETGID
					if (!change_path_values[i].setgid_ok) continue;
#endif
					printf("    %s (default is %s)\n", change_path_values[i].name, *change_path_values[i].path);
				}
				puts("                 Multiple -d options are allowed.");
				puts("  -s<mod>        Use sound module <sys>:");
				for (i = 0; i < (int)N_ELEMENTS(sound_modules); i++)
					printf("     %s   %s\n", sound_modules[i].name,
					       sound_modules[i].help);
				puts("  -m<sys>        Use module <sys>, where <sys> can be:");

				/* Print the name and help for each available module */
				for (i = 0; i < (int)N_ELEMENTS(modules); i++)
					printf("     %s   %s\n",
					       modules[i].name, modules[i].help);

				/* Actually abort the process */
				quit(NULL);
		}
		if (*arg) goto usage;
	}

	/* Hack -- Forget standard args */
	if (args) {
		argc = 1;
		argv[1] = NULL;
	}

	/* Install "quit" hook */
	quit_aux = quit_hook;

	/* If we were told which mode to use, then use it */
	if (mstr)
		ANGBAND_SYS = mstr;

	if (setlocale(LC_CTYPE, "")) {
		/* Require UTF-8 */
		if (strcmp(nl_langinfo(CODESET), "UTF-8") != 0)
			quit("Angband requires UTF-8 support");
	}

	/* Try the modules in the order specified by modules[] */
	for (i = 0; i < (int)N_ELEMENTS(modules); i++) {
		/* User requested a specific module? */
		if (!mstr || (streq(mstr, modules[i].name))) {
			ANGBAND_SYS = modules[i].name;
			if (0 == modules[i].init(argc, argv)) {
				done = TRUE;
				break;
			}
		}
	}

	/* Make sure we have a display! */
	if (!done) quit("Unable to prepare any 'display module'!");

#ifdef UNIX

	/* Get the "user name" as default player name, unless set with -u switch */
	if (!op_ptr->full_name[0]) {
		user_name(op_ptr->full_name, sizeof(op_ptr->full_name), player_uid);

		/* Set the savefile to load */
		savefile_set_name(player_safe_name(player, FALSE));
	}

	/* Create any missing directories */
	create_needed_dirs();

#endif /* UNIX */

	/* Try the modules in the order specified by sound_modules[] */
	for (i = 0; i < (int)N_ELEMENTS(sound_modules); i++)
		if (!soundstr || streq(soundstr, sound_modules[i].name))
			if (0 == sound_modules[i].init(argc, argv))
				break;

	/* Catch nasty signals */
	signals_init();

	/* Set up the command hook */
	cmd_get_hook = textui_get_cmd;

	/* Set up the display handlers and things. */
	init_display();
	init_angband();
	textui_init();

	/* Wait for response */
	pause_line(Term);

	/* Play the game */
	play_game(new_game);

	/* Free resources */
	textui_cleanup();
	cleanup_angband();

	/* Quit */
	quit(NULL);

	/* Exit */
	return (0);
}
コード例 #8
0
int
main(int argc, char *argv[])
{
	struct kinfo_proc *kp;
	struct kinfo_proc *dkp;
	struct stat *stp;
	time_t touched;
	int ch, i, nentries, nusers, wcmd, longidle, longattime, dropgid;
	const char *memf, *nlistf, *p;
	char *x_suffix;
	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
	char fn[MAXHOSTNAMELEN];
	char *dot;

	(void)setlocale(LC_ALL, "");
	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
	use_comma = (*nl_langinfo(RADIXCHAR) != ',');

	/* Are we w(1) or uptime(1)? */
	if (this_is_uptime(argv[0]) == 0) {
		wcmd = 0;
		p = "";
	} else {
		wcmd = 1;
		p = "dhiflM:N:nsuw";
	}

	dropgid = 0;
	memf = _PATH_DEVNULL;
	nlistf = NULL;
	while ((ch = getopt(argc, argv, p)) != -1)
		switch (ch) {
		case 'd':
			dflag = 1;
			break;
		case 'h':
			header = 0;
			break;
		case 'i':
			sortidle = 1;
			break;
		case 'M':
			header = 0;
			memf = optarg;
			dropgid = 1;
			break;
		case 'N':
			nlistf = optarg;
			dropgid = 1;
			break;
		case 'n':
			nflag = 1;
			break;
		case 'f': case 'l': case 's': case 'u': case 'w':
			warnx("[-flsuw] no longer supported");
			/* FALLTHROUGH */
		case '?':
		default:
			usage(wcmd);
		}
	argc -= optind;
	argv += optind;

	if (!(_res.options & RES_INIT))
		res_init();
	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
	_res.retry = 1;		/* only try once.. */

	/*
	 * Discard setgid privileges if not the running kernel so that bad
	 * guys can't print interesting stuff from kernel memory.
	 */
	if (dropgid)
		setgid(getgid());

	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
		errx(1, "%s", errbuf);

	(void)time(&now);

	if (*argv)
		sel_users = argv;

	setutxent();
	for (nusers = 0; (utmp = getutxent()) != NULL;) {
		if (utmp->ut_type != USER_PROCESS)
			continue;
		if (!(stp = ttystat(utmp->ut_line)))
			continue;	/* corrupted record */
		++nusers;
		if (wcmd == 0)
			continue;
		if (sel_users) {
			int usermatch;
			char **user;

			usermatch = 0;
			for (user = sel_users; !usermatch && *user; user++)
				if (!strcmp(utmp->ut_user, *user))
					usermatch = 1;
			if (!usermatch)
				continue;
		}
		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
			errx(1, "calloc");
		*nextp = ep;
		nextp = &ep->next;
		memmove(&ep->utmp, utmp, sizeof *utmp);
		ep->tdev = stp->st_rdev;
		/*
		 * If this is the console device, attempt to ascertain
		 * the true console device dev_t.
		 */
		if (ep->tdev == 0) {
			size_t size;

			size = sizeof(dev_t);
			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
		}
		touched = stp->st_atime;
		if (touched < ep->utmp.ut_tv.tv_sec) {
			/* tty untouched since before login */
			touched = ep->utmp.ut_tv.tv_sec;
		}
		if ((ep->idle = now - touched) < 0)
			ep->idle = 0;
	}
	endutxent();

	if (header || wcmd == 0) {
		pr_header(&now, nusers);
		if (wcmd == 0) {
			(void)kvm_close(kd);
			exit(0);
		}

#define HEADER_USER		"USER"
#define HEADER_TTY		"TTY"
#define HEADER_FROM		"FROM"
#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
#define HEADER_WHAT		"WHAT\n"
#define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \
		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */ 
		(void)printf("%-*.*s %-*.*s %-*.*s  %s", 
				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
				HEADER_LOGIN_IDLE HEADER_WHAT);
	}

	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
		err(1, "%s", kvm_geterr(kd));
	for (i = 0; i < nentries; i++, kp++) {
		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
		    kp->ki_tdev == NODEV)
			continue;
		for (ep = ehead; ep != NULL; ep = ep->next) {
			if (ep->tdev == kp->ki_tdev) {
				/*
				 * proc is associated with this terminal
				 */
				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
					/*
					 * Proc is 'most interesting'
					 */
					if (proc_compare(ep->kp, kp))
						ep->kp = kp;
				}
				/*
				 * Proc debug option info; add to debug
				 * list using kinfo_proc ki_spare[0]
				 * as next pointer; ptr to ptr avoids the
				 * ptr = long assumption.
				 */
				dkp = ep->dkp;
				ep->dkp = kp;
				debugproc(kp) = dkp;
			}
		}
	}
	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
	       ttywidth = 79;
        else
	       ttywidth = ws.ws_col - 1;
	argwidth = ttywidth - WUSED;
	if (argwidth < 4)
		argwidth = 8;
	for (ep = ehead; ep != NULL; ep = ep->next) {
		if (ep->kp == NULL) {
			ep->args = strdup("-");
			continue;
		}
		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
		    ep->kp->ki_comm, NULL, MAXCOMLEN);
		if (ep->args == NULL)
			err(1, NULL);
	}
	/* sort by idle time */
	if (sortidle && ehead != NULL) {
		struct entry *from, *save;

		from = ehead;
		ehead = NULL;
		while (from != NULL) {
			for (nextp = &ehead;
			    (*nextp) && from->idle >= (*nextp)->idle;
			    nextp = &(*nextp)->next)
				continue;
			save = from;
			from = from->next;
			save->next = *nextp;
			*nextp = save;
		}
	}

	for (ep = ehead; ep != NULL; ep = ep->next) {
		struct addrinfo hints, *res;
		struct sockaddr_storage ss;
		struct sockaddr *sa = (struct sockaddr *)&ss;
		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
		time_t t;
		int isaddr;

		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
		if ((x_suffix = strrchr(p, ':')) != NULL) {
			if ((dot = strchr(x_suffix, '.')) != NULL &&
			    strchr(dot+1, '.') == NULL)
				*x_suffix++ = '\0';
			else
				x_suffix = NULL;
		}

		isaddr = 0;
		memset(&ss, '\0', sizeof(ss));
		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
			lsin6->sin6_len = sizeof(*lsin6);
			lsin6->sin6_family = AF_INET6;
			isaddr = 1;
		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
			lsin->sin_len = sizeof(*lsin);
			lsin->sin_family = AF_INET;
			isaddr = 1;
		}
		if (!nflag) {
			/* Attempt to change an IP address into a name */
			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
			    sa->sa_len) == HOSTNAME_FOUND)
				p = fn;
		} else if (!isaddr) {
			/*
			 * If a host has only one A/AAAA RR, change a
			 * name into an IP address
			 */
			memset(&hints, 0, sizeof(hints));
			hints.ai_flags = AI_PASSIVE;
			hints.ai_family = AF_UNSPEC;
			hints.ai_socktype = SOCK_STREAM;
			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
				if (res->ai_next == NULL &&
				    getnameinfo(res->ai_addr, res->ai_addrlen,
					fn, sizeof(fn), NULL, 0,
					NI_NUMERICHOST) == 0)
					p = fn;
				freeaddrinfo(res);
			}
		}

		if (x_suffix) {
			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
			p = buf;
		}
		if (dflag) {
			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
				const char *ptr;

				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
				    dkp->ki_comm, NULL, MAXCOMLEN);
				if (ptr == NULL)
					ptr = "-";
				(void)printf("\t\t%-9d %s\n",
				    dkp->ki_pid, ptr);
			}
		}
		(void)printf("%-*.*s %-*.*s %-*.*s ",
		    W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
		    W_DISPLINESIZE, W_DISPLINESIZE,
		    *ep->utmp.ut_line ?
		    (strncmp(ep->utmp.ut_line, "tty", 3) &&
		    strncmp(ep->utmp.ut_line, "cua", 3) ?
		    ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-",
		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
		t = ep->utmp.ut_tv.tv_sec;
		longattime = pr_attime(&t, &now);
		longidle = pr_idle(ep->idle);
		(void)printf("%.*s\n", argwidth - longidle - longattime,
		    ep->args);
	}
	(void)kvm_close(kd);
	exit(0);
}
コード例 #9
0
ファイル: parser.c プロジェクト: baohaojun/luit
char *
resolveLocale(const char *locale)
{
    FILE *f;
    char first[MAX_KEYWORD_LENGTH];
    char second[MAX_KEYWORD_LENGTH];
    char *resolved = NULL;
    int rc;
    int found = 0;

    TRACE(("resolveLocale(%s)\n", locale));

    TRACE(("...looking in %s\n", locale_alias));
    f = fopen(locale_alias, "r");

    if (f != NULL) {
	do {
	    rc = parseTwoTokenLine(f, first, second);
	    if (rc < -1)
		break;
	    if (!strcmp(first, locale)) {
		resolved = strmalloc(second);
		found = 1;
		break;
	    }
	} while (rc >= 0);

	if (!found) {
	    if (resolved == NULL) {
		TRACE(("...not found in %s\n", locale_alias));
		resolved = strmalloc(locale);
	    }
	}

	fclose(f);
    }

    /*
     * If we did not find the data in the locale.alias file (or as happens with
     * some, the right column does not appear to specify a valid locale), see
     * if we can get a better result from the system's locale tables.
     */
    if (!found || !has_encoding(resolved)) {
#ifdef HAVE_LANGINFO_CODESET
	char *improved;
	if (!ignore_locale
	    && strcmp(locale, "C")
	    && strcmp(locale, "POSIX")
	    && strcmp(locale, "US-ASCII")
	    && (improved = nl_langinfo(CODESET)) != 0) {
	    TRACE(("...nl_langinfo ->%s\n", improved));
	    free(resolved);
	    resolved = strmalloc(improved);
	} else
#endif
	if (f == 0 && (fopen(locale_alias, "r") == 0)) {
	    perror(locale_alias);
	}
    }

    TRACE(("...resolveLocale ->%s\n", resolved));
    return resolved;
}
コード例 #10
0
ファイル: localcharset.c プロジェクト: caomw/glib
const char *
_g_locale_charset_raw (void)
{
  const char *codeset;

#if !(defined WIN32_NATIVE || defined OS2)

# if HAVE_LANGINFO_CODESET

  /* Most systems support nl_langinfo (CODESET) nowadays.  */
  codeset = nl_langinfo (CODESET);

#  ifdef __CYGWIN__
  /* Cygwin 2006 does not have locales.  nl_langinfo (CODESET) always
     returns "US-ASCII".  As long as this is not fixed, return the suffix
     of the locale name from the environment variables (if present) or
     the codepage as a number.  */
  if (codeset != NULL && strcmp (codeset, "US-ASCII") == 0)
    {
      const char *locale;
      static char buf[2 + 10 + 1];

      locale = getenv ("LC_ALL");
      if (locale == NULL || locale[0] == '\0')
	{
	  locale = getenv ("LC_CTYPE");
	  if (locale == NULL || locale[0] == '\0')
	    locale = getenv ("LANG");
	}
      if (locale != NULL && locale[0] != '\0')
	{
	  /* If the locale name contains an encoding after the dot, return
	     it.  */
	  const char *dot = strchr (locale, '.');

	  if (dot != NULL)
	    {
	      const char *modifier;

	      dot++;
	      /* Look for the possible @... trailer and remove it, if any.  */
	      modifier = strchr (dot, '@');
	      if (modifier == NULL)
		return dot;
	      if (modifier - dot < sizeof (buf))
		{
		  memcpy (buf, dot, modifier - dot);
		  buf [modifier - dot] = '\0';
		  return buf;
		}
	    }
	}

      /* Woe32 has a function returning the locale's codepage as a number.  */
      sprintf (buf, "CP%u", GetACP ());
      codeset = buf;
    }
#  endif

# else

  /* On old systems which lack it, use setlocale or getenv.  */
  const char *locale = NULL;

  /* But most old systems don't have a complete set of locales.  Some
     (like SunOS 4 or DJGPP) have only the C locale.  Therefore we don't
     use setlocale here; it would return "C" when it doesn't support the
     locale name the user has set.  */
#  if 0
  locale = setlocale (LC_CTYPE, NULL);
#  endif
  if (locale == NULL || locale[0] == '\0')
    {
      locale = getenv ("LC_ALL");
      if (locale == NULL || locale[0] == '\0')
	{
	  locale = getenv ("LC_CTYPE");
	  if (locale == NULL || locale[0] == '\0')
	    locale = getenv ("LANG");
	}
    }

  /* On some old systems, one used to set locale = "iso8859_1". On others,
     you set it to "language_COUNTRY.charset". In any case, we resolve it
     through the charset.alias file.  */
  codeset = locale;

# endif

#elif defined WIN32_NATIVE

  static char buf[2 + 10 + 1];

  /* Woe32 has a function returning the locale's codepage as a number.  */
  sprintf (buf, "CP%u", GetACP ());
  codeset = buf;

#elif defined OS2

  const char *locale;
  static char buf[2 + 10 + 1];
  ULONG cp[3];
  ULONG cplen;

  /* Allow user to override the codeset, as set in the operating system,
     with standard language environment variables.  */
  locale = getenv ("LC_ALL");
  if (locale == NULL || locale[0] == '\0')
    {
      locale = getenv ("LC_CTYPE");
      if (locale == NULL || locale[0] == '\0')
	locale = getenv ("LANG");
    }
  if (locale != NULL && locale[0] != '\0')
    {
      /* If the locale name contains an encoding after the dot, return it.  */
      const char *dot = strchr (locale, '.');

      if (dot != NULL)
	{
	  const char *modifier;

	  dot++;
	  /* Look for the possible @... trailer and remove it, if any.  */
	  modifier = strchr (dot, '@');
	  if (modifier == NULL)
	    return dot;
	  if (modifier - dot < sizeof (buf))
	    {
	      memcpy (buf, dot, modifier - dot);
	      buf [modifier - dot] = '\0';
	      return buf;
	    }
	}

      /* Resolve through the charset.alias file.  */
      codeset = locale;
    }
  else
    {
      /* OS/2 has a function returning the locale's codepage as a number.  */
      if (DosQueryCp (sizeof (cp), cp, &cplen))
	codeset = "";
      else
	{
	  sprintf (buf, "CP%u", cp[0]);
	  codeset = buf;
	}
    }

#endif

  return codeset;
}
コード例 #11
0
STATIC
#endif
const char *
locale_charset ()
{
  const char *codeset;
  const char *aliases;

#if !(defined WIN32 || defined OS2)

# if HAVE_LANGINFO_CODESET

  
  codeset = nl_langinfo (CODESET);

# else

  
  const char *locale = NULL;

#  if HAVE_SETLOCALE && 0
  locale = setlocale (LC_CTYPE, NULL);
#  endif
  if (locale == NULL || locale[0] == '\0')
    {
      locale = getenv ("LC_ALL");
      if (locale == NULL || locale[0] == '\0')
	{
	  locale = getenv ("LC_CTYPE");
	  if (locale == NULL || locale[0] == '\0')
	    locale = getenv ("LANG");
	}
    }

  codeset = locale;

# endif

#elif defined WIN32

  static char buf[2 + 10 + 1];

  
  sprintf (buf, "CP%u", GetACP ());
  codeset = buf;

#elif defined OS2

  const char *locale;
  static char buf[2 + 10 + 1];
  ULONG cp[3];
  ULONG cplen;

  locale = getenv ("LC_ALL");
  if (locale == NULL || locale[0] == '\0')
    {
      locale = getenv ("LC_CTYPE");
      if (locale == NULL || locale[0] == '\0')
	locale = getenv ("LANG");
    }
  if (locale != NULL && locale[0] != '\0')
    {
      
      const char *dot = strchr (locale, '.');

      if (dot != NULL)
	{
	  const char *modifier;

	  dot++;
	  
	  modifier = strchr (dot, '@');
	  if (modifier == NULL)
	    return dot;
	  if (modifier - dot < sizeof (buf))
	    {
	      memcpy (buf, dot, modifier - dot);
	      buf [modifier - dot] = '\0';
	      return buf;
	    }
	}

      
      codeset = locale;
    }
  else
    {
      
      if (DosQueryCp (sizeof (cp), cp, &cplen))
	codeset = "";
      else
	{
	  sprintf (buf, "CP%u", cp[0]);
	  codeset = buf;
	}
    }

#endif

  if (codeset == NULL)
    
    codeset = "";

  
  for (aliases = get_charset_aliases ();
       *aliases != '\0';
       aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
    if (strcmp (codeset, aliases) == 0
	|| (aliases[0] == '*' && aliases[1] == '\0'))
      {
	codeset = aliases + strlen (aliases) + 1;
	break;
      }

  if (codeset[0] == '\0')
    codeset = "ASCII";

  return codeset;
}
コード例 #12
0
ファイル: weechat.c プロジェクト: bukzor/weechat
int
main (int argc, char *argv[])
{
    weechat_first_start_time = time (NULL); /* initialize start time        */
    gettimeofday (&weechat_current_start_timeval, NULL);

    setlocale (LC_ALL, "");             /* initialize gettext               */
#ifdef ENABLE_NLS
    bindtextdomain (PACKAGE, LOCALEDIR);
    bind_textdomain_codeset (PACKAGE, "UTF-8");
    textdomain (PACKAGE);
#endif

#ifdef HAVE_LANGINFO_CODESET
    weechat_local_charset = strdup (nl_langinfo (CODESET));
#else
    weechat_local_charset = strdup ("");
#endif
    utf8_init ();

    util_catch_signal (SIGINT, SIG_IGN);  /* ignore SIGINT signal           */
    util_catch_signal (SIGQUIT, SIG_IGN); /* ignore SIGQUIT signal          */
    util_catch_signal (SIGPIPE, SIG_IGN); /* ignore SIGPIPE signal          */
    util_catch_signal (SIGSEGV,
                       &debug_sigsegv); /* crash dump for SIGSEGV signal    */
    hdata_init ();                      /* initialize hdata                 */
    hook_init ();                       /* initialize hooks                 */
    debug_init ();                      /* hook signals for debug           */
    gui_main_pre_init (&argc, &argv);   /* pre-initialize interface         */
    command_init ();                    /* initialize WeeChat commands      */
    completion_init ();                 /* add core completion hooks        */
    gui_key_init ();                    /* init keys                        */
    network_init_gcrypt ();             /* init gcrypt                      */
    if (!secure_init ())                /* init secured data options (sec.*)*/
        weechat_shutdown (EXIT_FAILURE, 0);
    if (!config_weechat_init ())        /* init WeeChat options (weechat.*) */
        weechat_shutdown (EXIT_FAILURE, 0);
    weechat_parse_args (argc, argv);    /* parse command line args          */
    weechat_create_home_dir ();         /* create WeeChat home directory    */
    log_init ();                        /* init log file                    */
    plugin_api_init ();                 /* create some hooks (info,hdata,..)*/
    secure_read ();                     /* read secured data options        */
    config_weechat_read ();             /* read WeeChat options             */
    network_init_gnutls ();             /* init GnuTLS                      */
    gui_main_init ();                   /* init WeeChat interface           */
    if (weechat_upgrading)
    {
        upgrade_weechat_load ();        /* upgrade with session file        */
        weechat_upgrade_count++;        /* increase /upgrade count          */
    }
    weechat_welcome_message ();         /* display WeeChat welcome message  */
    gui_chat_print_lines_waiting_buffer (NULL); /* display lines waiting    */
    command_startup (0);                /* command executed before plugins  */
    plugin_init (weechat_auto_load_plugins, /* init plugin interface(s)     */
                 argc, argv);
    command_startup (1);                /* commands executed after plugins  */
    if (!weechat_upgrading)
        gui_layout_window_apply (gui_layout_current, -1);
    if (weechat_upgrading)
        upgrade_weechat_end ();         /* remove .upgrade files + signal   */

    gui_main_loop ();                   /* WeeChat main loop                */

    gui_layout_store_on_exit ();        /* store layout                     */
    plugin_end ();                      /* end plugin interface(s)          */
    if (CONFIG_BOOLEAN(config_look_save_config_on_exit))
        (void) config_weechat_write (); /* save WeeChat config file         */
    (void) secure_write ();             /* save secured data                */
    gui_main_end (1);                   /* shut down WeeChat GUI            */
    proxy_free_all ();                  /* free all proxies                 */
    config_weechat_free ();             /* free WeeChat options             */
    secure_free ();                     /* free secured data options        */
    config_file_free_all ();            /* free all configuration files     */
    gui_key_end ();                     /* remove all keys                  */
    unhook_all ();                      /* remove all hooks                 */
    hdata_end ();                       /* end hdata                        */
    secure_end ();                      /* end secured data                 */
    string_end ();                      /* end string                       */
    weechat_shutdown (EXIT_SUCCESS, 0); /* quit WeeChat (oh no, why?)       */

    return EXIT_SUCCESS;                /* make C compiler happy            */
}
コード例 #13
0
ファイル: marcdump.c プロジェクト: nla/yaz
int main (int argc, char **argv)
{
    int r;
    int print_offset = 0;
    char *arg;
    int verbose = 0;
    int no = 0;
    int output_format = YAZ_MARC_LINE;
    FILE *cfile = 0;
    char *from = 0, *to = 0;
    int input_format = YAZ_MARC_ISO2709;
    int split_chunk = 1;
    const char *split_fname = 0;
    const char *leader_spec = 0;
    int write_using_libxml2 = 0;

#if HAVE_LOCALE_H
    setlocale(LC_CTYPE, "");
#endif
#if HAVE_LANGINFO_H
#ifdef CODESET
    to = nl_langinfo(CODESET);
#endif
#endif

    prog = *argv;
    while ((r = options("i:o:C:npc:xOeXIf:t:s:l:Vv", argv, argc, &arg)) != -2)
    {
        no++;
        switch (r)
        {
        case 'i':
            input_format = yaz_marc_decode_formatstr(arg);
            if (input_format == -1)
            {
                fprintf(stderr, "%s: bad input format: %s\n", prog, arg);
                exit(1);
            }
#if YAZ_HAVE_XML2
#else
            if (input_format == YAZ_MARC_MARCXML
                || input_format == YAZ_MARC_XCHANGE)
            {
                fprintf(stderr, "%s: Libxml2 support not enabled\n", prog);
                exit(3);
            }
#endif
            break;
        case 'o':
            /* dirty hack so we can make Libxml2 do the writing ..
               rather than WRBUF */
            if (strlen(arg) > 4 && strncmp(arg, "xml,", 4) == 0)
            {
                /* Only supported for Libxml2 2.6.0 or later */
#if LIBXML_VERSION >= 20600
                arg = arg + 4;
                write_using_libxml2 = 1;
#else
                fprintf(stderr, "%s: output using Libxml2 unsupported\n", prog);
                exit(4);
#endif
            }
            output_format = yaz_marc_decode_formatstr(arg);
            if (output_format == -1)
            {
                fprintf(stderr, "%s: bad output format: %s\n", prog, arg);
                exit(1);
            }
            break;
        case 'l':
            leader_spec = arg;
            break;
        case 'f':
            from = arg;
            break;
        case 't':
            to = arg;
            break;
        case 'c':
            if (cfile)
                fclose(cfile);
            cfile = fopen(arg, "w");
            break;
        case 'x':
            fprintf(stderr, "%s: -x no longer supported. "
                    "Use -i marcxml instead\n", prog);
            exit(1);
            break;
        case 'O':
            fprintf(stderr, "%s: OAI MARC no longer supported."
                    " Use MARCXML instead.\n", prog);
            exit(1);
            break;
        case 'e':
            fprintf(stderr, "%s: -e no longer supported. "
                    "Use -o marcxchange instead\n", prog);
            exit(1);
            break;
        case 'X':
            fprintf(stderr, "%s: -X no longer supported. "
                    "Use -o marcxml instead\n", prog);
            exit(1);
            break;
        case 'I':
            fprintf(stderr, "%s: -I no longer supported. "
                    "Use -o marc instead\n", prog);
            exit(1);
            break;
        case 'n':
            output_format = YAZ_MARC_CHECK;
            break;
        case 'p':
            print_offset = 1;
            break;
        case 's':
            split_fname = arg;
            break;
        case 'C':
            split_chunk = atoi(arg);
            break;
        case 0:
            dump(arg, from, to, input_format, output_format,
                 write_using_libxml2,
                 print_offset, split_fname, split_chunk,
                 verbose, cfile, leader_spec);
            break;
        case 'v':
            verbose++;
            break;
        case 'V':
            show_version();
            break;
        default:
            usage(prog);
            exit(1);
        }
    }
    if (cfile)
        fclose(cfile);
    if (!no)
    {
        usage(prog);
        exit(1);
    }
    if (no_errors)
        exit(5);
    exit(0);
}
コード例 #14
0
ファイル: rdesktop.c プロジェクト: z0x010/rdesktop
/* Client program */
int
main(int argc, char *argv[])
{
	char server[256];
	char fullhostname[64];
	char domain[256];
	char shell[256];
	char directory[256];
	RD_BOOL prompt_password, deactivated;
	struct passwd *pw;
	uint32 flags, ext_disc_reason = 0;
	char *p;
	int c;
	char *locale = NULL;
	int username_option = 0;
	RD_BOOL geometry_option = False;
#ifdef WITH_RDPSND
	char *rdpsnd_optarg = NULL;
#endif

#ifdef HAVE_LOCALE_H
	/* Set locale according to environment */
	locale = setlocale(LC_ALL, "");
	if (locale)
	{
		locale = xstrdup(locale);
	}

#endif

	/* Ignore SIGPIPE, since we are using popen() */
	struct sigaction act;
	memset(&act, 0, sizeof(act));
	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGPIPE, &act, NULL);

	/* setup default flags for TS_INFO_PACKET */
	flags = RDP_INFO_MOUSE | RDP_INFO_DISABLECTRLALTDEL
		| RDP_INFO_UNICODE | RDP_INFO_MAXIMIZESHELL | RDP_INFO_ENABLEWINDOWSKEY;

	prompt_password = False;
	g_seamless_spawn_cmd[0] = domain[0] = g_password[0] = shell[0] = directory[0] = 0;
	g_embed_wnd = 0;

	g_num_devices = 0;

#ifdef RDP2VNC
#define VNCOPT "V:Q:"
#else
#define VNCOPT
#endif
	while ((c = getopt(argc, argv,
			   VNCOPT "A:u:L:d:s:c:p:n:k:g:o:fbBeEitmzCDKS:T:NX:a:x:Pr:045h?")) != -1)
	{
		switch (c)
		{
#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'Q':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'A':
				g_seamless_rdp = True;
				STRNCPY(g_seamless_shell, optarg, sizeof(g_seamless_shell));
				break;

			case 'u':
				g_username = (char *) xmalloc(strlen(optarg) + 1);
				STRNCPY(g_username, optarg, strlen(optarg) + 1);
				username_option = 1;
				break;

			case 'L':
#ifdef HAVE_ICONV
				STRNCPY(g_codepage, optarg, sizeof(g_codepage));
#else
				error("iconv support not available\n");
#endif
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				g_seamless_persistent_mode = False;
				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(g_password, optarg, sizeof(g_password));
				flags |= RDP_INFO_AUTOLOGON;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;
#ifdef WITH_SCARD
			case 'i':
				flags |= RDP_INFO_PASSWORD_IS_SC_PIN;
				g_use_password_as_pin = True;
				break;
#endif
			case 't':
				g_use_ctrl = False;
				break;

			case 'n':
				STRNCPY(g_hostname, optarg, sizeof(g_hostname));
				break;

			case 'k':
				STRNCPY(g_keymapname, optarg, sizeof(g_keymapname));
				break;

			case 'g':
				geometry_option = True;
				g_fullscreen = False;
				if (!strcmp(optarg, "workarea"))
				{
					g_sizeopt = 1;
					break;
				}

				g_width = strtol(optarg, &p, 10);
				if (g_width <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == 'x')
					g_height = strtol(p + 1, &p, 10);

				if (g_height <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == '%')
				{
					g_sizeopt = -g_width;
					g_width = 800;
					p++;
				}

				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 2 : 1;
					g_xpos = strtol(p, &p, 10);

				}
				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 4 : 1;
					g_ypos = strtol(p, NULL, 10);
				}

				break;

			case 'f':
				g_fullscreen = True;
				break;

			case 'b':
				g_bitmap_cache = False;
				break;

			case 'B':
				g_ownbackstore = False;
				break;

			case 'e':
				g_encryption_initial = g_encryption = False;
				break;
			case 'E':
				g_packet_encryption = False;
				break;
			case 'm':
				g_sendmotion = False;
				break;

			case 'C':
				g_owncolmap = True;
				break;

			case 'D':
				g_hide_decorations = True;
				break;

			case 'K':
				g_grab_keyboard = False;
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					g_win_button_size = 18;
					break;
				}

				g_win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return EX_USAGE;
				}

				break;

			case 'T':
				STRNCPY(g_title, optarg, sizeof(g_title));
				break;

			case 'N':
				g_numlock_sync = True;
				break;

			case 'X':
				g_embed_wnd = strtol(optarg, NULL, 0);
				break;

			case 'a':
				g_server_depth = strtol(optarg, NULL, 10);
				if (g_server_depth != 8 &&
				    g_server_depth != 16 &&
				    g_server_depth != 15 && g_server_depth != 24
				    && g_server_depth != 32)
				{
					error("Invalid server colour depth.\n");
					return EX_USAGE;
				}
				break;

			case 'z':
				DEBUG(("rdp compression enabled\n"));
				flags |= (RDP_INFO_COMPRESSION | RDP_INFO_COMPRESSION2);
				break;

			case 'x':
				if (str_startswith(optarg, "m"))	/* modem */
				{
					g_rdp5_performanceflags = RDP5_NO_CURSOR_SHADOW |
						RDP5_NO_WALLPAPER | RDP5_NO_FULLWINDOWDRAG |
						RDP5_NO_MENUANIMATIONS | RDP5_NO_THEMING;
				}
				else if (str_startswith(optarg, "b"))	/* broadband */
				{
					g_rdp5_performanceflags =
						RDP5_NO_CURSOR_SHADOW | RDP5_NO_WALLPAPER;
				}
				else if (str_startswith(optarg, "l"))	/* lan */
				{
					g_rdp5_performanceflags =
						RDP5_NO_CURSOR_SHADOW | RDP5_DISABLE_NOTHING;
				}
				else
				{
					g_rdp5_performanceflags =
						RDP5_NO_CURSOR_SHADOW | strtol(optarg, NULL, 16);
				}
				break;

			case 'P':
				g_bitmap_cache_persist_enable = True;
				break;

			case 'r':

				if (str_startswith(optarg, "sound"))
				{
					optarg += 5;

					if (*optarg == ':')
					{
						optarg++;
						while ((p = next_arg(optarg, ',')))
						{
							if (str_startswith(optarg, "remote"))
								flags |= RDP_INFO_REMOTE_CONSOLE_AUDIO;

							if (str_startswith(optarg, "local"))
#ifdef WITH_RDPSND
							{
								rdpsnd_optarg =
									next_arg(optarg, ':');
								g_rdpsnd = True;
							}

#else
								warning("Not compiled with sound support\n");
#endif

							if (str_startswith(optarg, "off"))
#ifdef WITH_RDPSND
								g_rdpsnd = False;
#else
								warning("Not compiled with sound support\n");
#endif

							optarg = p;
						}
					}
					else
					{
#ifdef WITH_RDPSND
						g_rdpsnd = True;
#else
						warning("Not compiled with sound support\n");
#endif
					}
				}
				else if (str_startswith(optarg, "disk"))
				{
					/* -r disk:h:=/mnt/floppy */
					disk_enum_devices(&g_num_devices, optarg + 4);
				}
				else if (str_startswith(optarg, "comport"))
				{
					serial_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "lspci"))
				{
					g_lspci_enabled = True;
				}
				else if (str_startswith(optarg, "lptport"))
				{
					parallel_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "printer"))
				{
					printer_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "clientname"))
				{
					g_rdpdr_clientname = xmalloc(strlen(optarg + 11) + 1);
					strcpy(g_rdpdr_clientname, optarg + 11);
				}
				else if (str_startswith(optarg, "clipboard"))
				{
					optarg += 9;

					if (*optarg == ':')
					{
						optarg++;

						if (str_startswith(optarg, "off"))
							g_rdpclip = False;
						else
							cliprdr_set_mode(optarg);
					}
					else
						g_rdpclip = True;
				}
				else if (strncmp("scard", optarg, 5) == 0)
				{
#ifdef WITH_SCARD
					scard_enum_devices(&g_num_devices, optarg + 5);
#else
					warning("Not compiled with smartcard support\n");
#endif
				}
				else
				{
					warning("Unknown -r argument\n\n\tPossible arguments are: comport, disk, lptport, printer, sound, clipboard, scard\n");
				}
				break;

			case '0':
				g_console_session = True;
				break;

			case '4':
				g_rdp_version = RDP_V4;
				break;

			case '5':
				g_rdp_version = RDP_V5;
				break;
#if WITH_SCARD
			case 'o':
				{
					char *p = strchr(optarg, '=');
					if (p == NULL)
					{
						warning("Skipping option '%s' specified, lacks name=value format.\n");
						continue;
					}

					if (strncmp(optarg, "sc-csp-name", strlen("sc-scp-name")) ==
					    0)
						g_sc_csp_name = strdup(p + 1);
					else if (strncmp
						 (optarg, "sc-reader-name",
						  strlen("sc-reader-name")) == 0)
						g_sc_reader_name = strdup(p + 1);
					else if (strncmp
						 (optarg, "sc-card-name",
						  strlen("sc-card-name")) == 0)
						g_sc_card_name = strdup(p + 1);
					else if (strncmp
						 (optarg, "sc-container-name",
						  strlen("sc-container-name")) == 0)
						g_sc_container_name = strdup(p + 1);

				}
				break;
#endif
			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return EX_USAGE;
		}
	}

	if (argc - optind != 1)
	{
		usage(argv[0]);
		return EX_USAGE;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	parse_server_and_port(server);

	if (g_seamless_rdp)
	{
		if (shell[0])
			STRNCPY(g_seamless_spawn_cmd, shell, sizeof(g_seamless_spawn_cmd));

		STRNCPY(shell, g_seamless_shell, sizeof(shell));

		if (g_win_button_size)
		{
			error("You cannot use -S and -A at the same time\n");
			return EX_USAGE;
		}
		g_rdp5_performanceflags &= ~RDP5_NO_FULLWINDOWDRAG;
		if (geometry_option)
		{
			error("You cannot use -g and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_fullscreen)
		{
			error("You cannot use -f and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_hide_decorations)
		{
			error("You cannot use -D and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_embed_wnd)
		{
			error("You cannot use -X and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_rdp_version < RDP_V5)
		{
			error("You cannot use -4 and -A at the same time\n");
			return EX_USAGE;
		}
		g_sizeopt = -100;
		g_grab_keyboard = False;
	}

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return EX_OSERR;
		}
		/* +1 for trailing \0 */
		int pwlen = strlen(pw->pw_name) + 1;
		g_username = (char *) xmalloc(pwlen);
		STRNCPY(g_username, pw->pw_name, pwlen);
	}

#ifdef HAVE_ICONV
	if (g_codepage[0] == 0)
	{
		if (setlocale(LC_CTYPE, ""))
		{
			STRNCPY(g_codepage, nl_langinfo(CODESET), sizeof(g_codepage));
		}
		else
		{
			STRNCPY(g_codepage, DEFAULT_CODEPAGE, sizeof(g_codepage));
		}
	}
#endif

	if (g_hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return EX_OSERR;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(g_hostname, fullhostname, sizeof(g_hostname));
	}

	if (g_keymapname[0] == 0)
	{
		if (locale && xkeymap_from_locale(locale))
		{
			fprintf(stderr, "Autoselected keyboard map %s\n", g_keymapname);
		}
		else
		{
			STRNCPY(g_keymapname, "en-us", sizeof(g_keymapname));
		}
	}
	if (locale)
		xfree(locale);


	if (prompt_password && read_password(g_password, sizeof(g_password)))
		flags |= RDP_INFO_AUTOLOGON;

	if (g_title[0] == 0)
	{
		strcpy(g_title, "rdesktop - ");
		strncat(g_title, server, sizeof(g_title) - sizeof("rdesktop - "));
	}

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, g_password, shell, directory);
	return EX_OK;
#else

	/* Only startup ctrl functionality is seamless are used for now. */
	if (g_use_ctrl && g_seamless_rdp)
	{
		if (ctrl_init(server, domain, g_username) < 0)
		{
			error("Failed to initialize ctrl mode.");
			exit(1);
		}

		if (ctrl_is_slave())
		{
			fprintf(stdout,
				"rdesktop in slave mode sending command to master process.\n");

			if (g_seamless_spawn_cmd[0])
				return ctrl_send_command("seamless.spawn", g_seamless_spawn_cmd);

			fprintf(stdout, "No command specified to be spawn in seamless mode.\n");
			return EX_USAGE;
		}
	}

	if (!ui_init())
		return EX_OSERR;

#ifdef WITH_RDPSND
	if (!rdpsnd_init(rdpsnd_optarg))
		warning("Initializing sound-support failed!\n");
#endif

	if (g_lspci_enabled)
		lspci_init();

	rdpdr_init();
	g_reconnect_loop = False;
	while (1)
	{
		rdesktop_reset_state();

		if (g_redirect)
		{
			STRNCPY(domain, g_redirect_domain, sizeof(domain));
			xfree(g_username);
			g_username = (char *) xmalloc(strlen(g_redirect_username) + 1);
			STRNCPY(g_username, g_redirect_username, strlen(g_redirect_username) + 1);
			STRNCPY(server, g_redirect_server, sizeof(server));
			flags |= RDP_INFO_AUTOLOGON;

			fprintf(stderr, "Redirected to %s@%s session %d.\n",
				g_redirect_username, g_redirect_server, g_redirect_session_id);

			/* A redirect on SSL from a 2003 WTS will result in a 'connection reset by peer'
			   and therefor we just clear this error before we connect to redirected server.
			 */
			g_network_error = False;
			g_redirect = False;
		}

		ui_init_connection();
		if (!rdp_connect
		    (server, flags, domain, g_password, shell, directory, g_reconnect_loop))
		{

			g_network_error = False;

			if (g_reconnect_loop == False)
				return EX_PROTOCOL;

			/* check if auto reconnect cookie has timed out */
			if (time(NULL) - g_reconnect_random_ts > RECONNECT_TIMEOUT)
			{
				fprintf(stderr, "Tried to reconnect for %d minutes, giving up.\n",
					RECONNECT_TIMEOUT / 60);
				return EX_PROTOCOL;
			}

			sleep(4);
			continue;
		}

		if (g_redirect)
		{
			rdp_disconnect();
			continue;
		}

		/* By setting encryption to False here, we have an encrypted login 
		   packet but unencrypted transfer of other packets */
		if (!g_packet_encryption)
			g_encryption_initial = g_encryption = False;

		DEBUG(("Connection successful.\n"));

		rd_create_ui();
		tcp_run_ui(True);

		deactivated = False;
		g_reconnect_loop = False;
		rdp_main_loop(&deactivated, &ext_disc_reason);

		tcp_run_ui(False);

		DEBUG(("Disconnecting...\n"));
		rdp_disconnect();

		if (g_redirect)
			continue;

		/* handle network error and start autoreconnect */
		if (g_network_error && !deactivated)
		{
			fprintf(stderr,
				"Disconnected due to network error, retrying to reconnect for %d minutes.\n",
				RECONNECT_TIMEOUT / 60);
			g_network_error = False;
			g_reconnect_loop = True;
			continue;
		}

		ui_seamless_end();
		ui_destroy_window();

		/* Enter a reconnect loop if we have a pending resize request */
		if (g_pending_resize)
		{
			g_pending_resize = False;
			g_reconnect_loop = True;
			continue;
		}
		break;
	}

	cache_save_state();
	ui_deinit();

	if (g_user_quit)
		return EXRD_WINDOW_CLOSED;

	return handle_disconnect_reason(deactivated, ext_disc_reason);

#endif
	if (g_redirect_username)
		xfree(g_redirect_username);

	xfree(g_username);
}
コード例 #15
0
ファイル: camel-iconv.c プロジェクト: Pecisk/eds-gtasks
/* NOTE: Owns the lock on return if keep is TRUE !*/
static void
iconv_init (gint keep)
{
	gchar *from, *to, *locale;
	gint i;

	G_LOCK (iconv);

	if (iconv_charsets != NULL) {
		if (!keep)
			G_UNLOCK (iconv);
		return;
	}

	iconv_charsets = g_hash_table_new (g_str_hash, g_str_equal);

	for (i = 0; known_iconv_charsets[i].charset != NULL; i++) {
		from = g_strdup (known_iconv_charsets[i].charset);
		to = g_strdup (known_iconv_charsets[i].iconv_name);
		e_strdown (from);
		g_hash_table_insert (iconv_charsets, from, to);
	}

	iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
	iconv_cache_open = g_hash_table_new (NULL, NULL);

#ifndef G_OS_WIN32
	locale = setlocale (LC_ALL, NULL);
#else
	locale = g_win32_getlocale ();
#endif

	if (!locale || !strcmp (locale, "C") || !strcmp (locale, "POSIX")) {
		/* The locale "C"  or  "POSIX"  is  a  portable  locale;  its
		 * LC_CTYPE  part  corresponds  to  the 7-bit ASCII character
		 * set.
		 */

		locale_charset = NULL;
		locale_lang = NULL;
	} else {
#ifdef G_OS_WIN32
		g_get_charset (&locale_charset);
		locale_charset = g_strdup (locale_charset);
		e_strdown (locale_charset);
#else
#ifdef HAVE_CODESET
		locale_charset = g_strdup (nl_langinfo (CODESET));
		e_strdown (locale_charset);
#else
		/* A locale name is typically of  the  form  language[_terri-
		 * tory][.codeset][@modifier],  where  language is an ISO 639
		 * language code, territory is an ISO 3166 country code,  and
		 * codeset  is  a  character  set or encoding identifier like
		 * ISO-8859-1 or UTF-8.
		 */
		gchar *codeset, *p;

		codeset = strchr (locale, '.');
		if (codeset) {
			codeset++;

			/* ; is a hack for debian systems and / is a hack for Solaris systems */
			for (p = codeset; *p && !strchr ("@;/", *p); p++);
			locale_charset = g_strndup (codeset, p - codeset);
			e_strdown (locale_charset);
		} else {
			/* charset unknown */
			locale_charset = NULL;
		}
#endif
#endif	/* !G_OS_WIN32 */

		/* parse the locale lang */
		locale_parse_lang (locale);

	}

#ifdef G_OS_WIN32
	g_free (locale);
#endif
	if (!keep)
		G_UNLOCK (iconv);
}
コード例 #16
0
ファイル: fileutils.c プロジェクト: 1564143452/kbengine
static int
check_force_ascii(void)
{
    char *loc;
#if defined(HAVE_LANGINFO_H) && defined(CODESET)
    char *codeset, **alias;
    char encoding[100];
    int is_ascii;
    unsigned int i;
    char* ascii_aliases[] = {
        "ascii",
        "646",
        "ansi-x3.4-1968",
        "ansi-x3-4-1968",
        "ansi-x3.4-1986",
        "cp367",
        "csascii",
        "ibm367",
        "iso646-us",
        "iso-646.irv-1991",
        "iso-ir-6",
        "us",
        "us-ascii",
        NULL
    };
#endif

    loc = setlocale(LC_CTYPE, NULL);
    if (loc == NULL)
        goto error;
    if (strcmp(loc, "C") != 0) {
        /* the LC_CTYPE locale is different than C */
        return 0;
    }

#if defined(HAVE_LANGINFO_H) && defined(CODESET)
    codeset = nl_langinfo(CODESET);
    if (!codeset || codeset[0] == '\0') {
        /* CODESET is not set or empty */
        goto error;
    }
    if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding)))
        goto error;

    is_ascii = 0;
    for (alias=ascii_aliases; *alias != NULL; alias++) {
        if (strcmp(encoding, *alias) == 0) {
            is_ascii = 1;
            break;
        }
    }
    if (!is_ascii) {
        /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
        return 0;
    }

    for (i=0x80; i<0xff; i++) {
        unsigned char ch;
        wchar_t wch;
        size_t res;

        ch = (unsigned char)i;
        res = mbstowcs(&wch, (char*)&ch, 1);
        if (res != (size_t)-1) {
            /* decoding a non-ASCII character from the locale encoding succeed:
               the locale encoding is not ASCII, force ASCII */
            return 1;
        }
    }
    /* None of the bytes in the range 0x80-0xff can be decoded from the locale
       encoding: the locale encoding is really ASCII */
    return 0;
#else
    /* nl_langinfo(CODESET) is not available: always force ASCII */
    return 1;
#endif

error:
    /* if an error occured, force the ASCII encoding */
    return 1;
}
コード例 #17
0
ファイル: langinfo.c プロジェクト: 2220142/ruby
int main()
{
  printf("%s\n", nl_langinfo(CODESET));
  return 0;
}
コード例 #18
0
void check_langinfo_functions(nl_item ni, locale_t l)
{
    (void)nl_langinfo(ni);
    (void)nl_langinfo_l(ni, l);
}
コード例 #19
0
ファイル: morse.c プロジェクト: coyizumi/cs111
int
main(int argc, char **argv)
{
	int    ch, lflags;
	char  *p, *codeset;

	while ((ch = getopt(argc, argv, GETOPTOPTS)) != -1)
		switch ((char) ch) {
		case 'c':
			cpm = atoi(optarg);
			break;
		case 'd':
			device = optarg;
			break;
		case 'e':
			eflag = 1;
			setvbuf(stdout, 0, _IONBF, 0);
			break;
		case 'f':
			freq = atoi(optarg);
			break;
		case 'l':
			lflag = 1;
			break;
#ifdef SPEAKER
		case 'p':
			pflag = 1;
			break;
#endif
		case 's':
			sflag = 1;
			break;
		case 'w':
			wpm = atoi(optarg);
			break;
		case '?':
		default:
			fputs(USAGE, stderr);
			exit(1);
		}
	if (sflag && lflag) {
		fputs("morse: only one of -l and -s allowed\n", stderr);
		exit(1);
	}
	if ((pflag || device) && (sflag || lflag)) {
		fputs("morse: only one of -p, -d and -l, -s allowed\n", stderr);
		exit(1);
	}
	if (cpm == 0)
		cpm = wpm;
	if ((pflag || device) && ((wpm < 1) || (wpm > 60) || (cpm < 1) || (cpm > 60))) {
		fputs("morse: insane speed\n", stderr);
		exit(1);
	}
	if ((pflag || device) && (freq == 0))
		freq = FREQUENCY;

#ifdef SPEAKER
	if (pflag) {
		if ((spkr = open(SPEAKER, O_WRONLY, 0)) == -1) {
			perror(SPEAKER);
			exit(1);
		}
	} else
#endif
	if (device) {
		if ((line = open(device, O_WRONLY | O_NONBLOCK)) == -1) {
			perror("open tty line");
			exit(1);
		}
		if (tcgetattr(line, &otty) == -1) {
			perror("tcgetattr() failed");
			exit(1);
		}
		ntty = otty;
		ntty.c_cflag |= CLOCAL;
		tcsetattr(line, TCSANOW, &ntty);
		lflags = fcntl(line, F_GETFL);
		lflags &= ~O_NONBLOCK;
		fcntl(line, F_SETFL, &lflags);
		ioctl(line, TIOCMGET, &lflags);
		lflags &= ~TIOCM_RTS;
		olflags = lflags;
		ioctl(line, TIOCMSET, &lflags);
		(void)signal(SIGHUP, sighandler);
		(void)signal(SIGINT, sighandler);
		(void)signal(SIGQUIT, sighandler);
		(void)signal(SIGTERM, sighandler);
	}
	if (pflag || device) {
		dot_clock = wpm / 2.4;		/* dots/sec */
		dot_clock = 1 / dot_clock;	/* duration of a dot */
		dot_clock = dot_clock / 2;	/* dot_clock runs at twice */
						/* the dot rate */
		dot_clock = dot_clock * 100;	/* scale for ioctl */

		cdot_clock = cpm / 2.4;		/* dots/sec */
		cdot_clock = 1 / cdot_clock;	/* duration of a dot */
		cdot_clock = cdot_clock / 2;	/* dot_clock runs at twice */
						/* the dot rate */
		cdot_clock = cdot_clock * 100;	/* scale for ioctl */
	}

	argc -= optind;
	argv += optind;

	if (setlocale(LC_CTYPE, "") != NULL &&
	    *(codeset = nl_langinfo(CODESET)) != '\0') {
		if (strcmp(codeset, "KOI8-R") == 0)
			hightab = koi8rtab;
		else if (strcmp(codeset, "ISO8859-1") == 0 ||
			 strcmp(codeset, "ISO8859-15") == 0)
			hightab = iso8859_1tab;
		else if (strcmp(codeset, "ISO8859-7") == 0)
			hightab = iso8859_7tab;
	}

	if (lflag)
		printf("m");
	if (*argv) {
		do {
			for (p = *argv; *p; ++p) {
				if (eflag)
					putchar(*p);
				morse(*p);
			}
			if (eflag)
				putchar(' ');
			morse(' ');
		} while (*++argv);
	} else {
		while ((ch = getchar()) != EOF) {
			if (eflag)
				putchar(ch);
			morse(ch);
		}
	}
	if (device)
		tcsetattr(line, TCSANOW, &otty);
	exit(0);
}
コード例 #20
0
ファイル: bwstring.c プロジェクト: JabirTech/Source
void
initialise_months(void)
{
	const nl_item item[12] = { ABMON_1, ABMON_2, ABMON_3, ABMON_4,
	    ABMON_5, ABMON_6, ABMON_7, ABMON_8, ABMON_9, ABMON_10,
	    ABMON_11, ABMON_12 };
	unsigned char *tmp;
	size_t len;

	if (MB_CUR_MAX == 1) {
		if (cmonths == NULL) {
			unsigned char *m;

			cmonths = sort_malloc(sizeof(unsigned char*) * 12);
			for (int i = 0; i < 12; i++) {
				cmonths[i] = NULL;
				tmp = (unsigned char *) nl_langinfo(item[i]);
				if (tmp == NULL)
					continue;
				if (debug_sort)
					printf("month[%d]=%s\n", i, tmp);
				len = strlen((char*)tmp);
				if (len < 1)
					continue;
				while (isblank(*tmp))
					++tmp;
				m = sort_malloc(len + 1);
				memcpy(m, tmp, len + 1);
				m[len] = '\0';
				for (unsigned int j = 0; j < len; j++)
					m[j] = toupper(m[j]);
				cmonths[i] = m;
			}
		}

	} else {
		if (wmonths == NULL) {
			wchar_t *m;

			wmonths = sort_malloc(sizeof(wchar_t *) * 12);
			for (int i = 0; i < 12; i++) {
				wmonths[i] = NULL;
				tmp = (unsigned char *) nl_langinfo(item[i]);
				if (tmp == NULL)
					continue;
				if (debug_sort)
					printf("month[%d]=%s\n", i, tmp);
				len = strlen((char*)tmp);
				if (len < 1)
					continue;
				while (isblank(*tmp))
					++tmp;
				m = sort_malloc(SIZEOF_WCHAR_STRING(len + 1));
				if (mbstowcs(m, (char*)tmp, len) == ((size_t) -1))
					continue;
				m[len] = L'\0';
				for (unsigned int j = 0; j < len; j++)
					m[j] = towupper(m[j]);
				wmonths[i] = m;
			}
		}
	}
}
コード例 #21
0
ファイル: qiconvcodec.cpp プロジェクト: GodFox/qtopia-ezx
iconv_t QIconvCodec::createIconv_t(const char *to, const char *from)
{
    Q_ASSERT((to == 0 && from != 0) || (to != 0 && from == 0));

    iconv_t cd = (iconv_t) -1;
#if defined(__GLIBC__) || defined(GNU_LIBICONV)
    // both GLIBC and libgnuiconv will use the locale's encoding if from or to is an empty string
    char *codeset = "";
    cd = iconv_open(to ? to : codeset, from ? from : codeset);
#else
    char *codeset = 0;
#endif

#if defined(_XOPEN_UNIX) && !defined(Q_OS_QNX6) && !defined(Q_OS_OSF)
    if (cd == (iconv_t) -1) {
        codeset = nl_langinfo(CODESET);
        if (codeset)
            cd = iconv_open(to ? to : codeset, from ? from : codeset);
    }
#endif

    if (cd == (iconv_t) -1) {
        // Very poorly defined and followed standards causes lots of
        // code to try to get all the cases... This logic is
        // duplicated in QTextCodec, so if you change it here, change
        // it there too.

        // Try to determine locale codeset from locale name assigned to
        // LC_CTYPE category.

        // First part is getting that locale name.  First try setlocale() which
        // definitely knows it, but since we cannot fully trust it, get ready
        // to fall back to environment variables.
        char * ctype = qstrdup(setlocale(LC_CTYPE, 0));

        // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG
        // environment variables.
        char * lang = qstrdup(qgetenv("LC_ALL").constData());
        if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) {
            if (lang) delete [] lang;
            lang = qstrdup(qgetenv("LC_CTYPE").constData());
        }
        if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) {
            if (lang) delete [] lang;
            lang = qstrdup(qgetenv("LANG").constData());
        }

        // Now try these in order:
        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
        // 2. CODESET from lang if it contains a .CODESET part
        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
        // 4. locale (ditto)
        // 5. check for "@euro"

        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
        codeset = ctype ? strchr(ctype, '.') : 0;
        if (codeset && *codeset == '.') {
            ++codeset;
            cd = iconv_open(to ? to : codeset, from ? from : codeset);
        }

        // 2. CODESET from lang if it contains a .CODESET part
        codeset = lang ? strchr(lang, '.') : 0;
        if (cd == (iconv_t) -1 && codeset && *codeset == '.') {
            ++codeset;
            cd = iconv_open(to ? to : codeset, from ? from : codeset);
        }

        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
        if (cd == (iconv_t) -1 && ctype && *ctype != 0 && strcmp (ctype, "C") != 0)
            cd = iconv_open(to ? to : ctype, from ? from : ctype);


        // 4. locale (ditto)
        if (cd == (iconv_t) -1 && lang && *lang != 0)
            cd = iconv_open(to ? to : lang, from ? from : lang);

        // 5. "@euro"
        if (cd == (iconv_t) -1 && ctype && strstr(ctype, "@euro") || lang && strstr(lang, "@euro"))
            cd = iconv_open(to ? to : "ISO8859-15", from ? from : "ISO8859-15");

        delete [] ctype;
        delete [] lang;
    }

    return cd;
}
コード例 #22
0
ファイル: printf_dfp.c プロジェクト: stliibm/libdfp
int
__printf_dfp (FILE *fp,
	      const struct printf_info *info,
	      const void *const *args)
{
  int wide = info->wide;
  /* Counter for number of written characters.  */
  int done = 0;

  /* Locale-dependent representation of decimal point.  */
  const char *decimal;

  union { const char *mb; int wc; } decimalwc;

  char spec = tolower(info->spec);

  /* Locale-dependent thousands separator and grouping specification.  */
  const char *thousands_sep = NULL;
  wchar_t thousands_sepwc = 0;
  const char * thousands_sepmb;

  const char *grouping;

#ifdef OPTION_EGLIBC_LOCALE_CODE
  if (info->extra == 0)
    {
      decimal = nl_langinfo (__DECIMAL_POINT);
      decimalwc.mb = nl_langinfo (_NL_NUMERIC_DECIMAL_POINT_WC);
    }
  else
    {
      decimal = nl_langinfo (__MON_DECIMAL_POINT);
      if (*decimal == '\0')
	decimal = nl_langinfo (__DECIMAL_POINT);

      decimalwc.mb = nl_langinfo (_NL_MONETARY_DECIMAL_POINT_WC);
      if (decimalwc.wc == L'\0')
	decimalwc.mb = nl_langinfo (_NL_NUMERIC_DECIMAL_POINT_WC);
    }
  /* The decimal point character must not be zero.  */
  assert (*decimal != '\0');
  assert (decimalwc.wc != L'\0');
#else
  /* Hard-code values from 'C' locale.  */
  decimal = ".";
  decimalwc.wc = L'.';
#endif

#ifdef OPTION_EGLIBC_LOCALE_CODE
  if (info->group)
    {
      if (info->extra == 0)
	grouping = nl_langinfo (__GROUPING);
      else
	grouping = nl_langinfo (__MON_GROUPING);

      if (*grouping <= 0 || *grouping == CHAR_MAX)
	grouping = NULL;
      else
	{
	  /* Figure out the thousands separator character.  */
	  if (wide)
	    {
	      if (info->extra == 0)
		{
		  thousands_sepmb = nl_langinfo (_NL_NUMERIC_THOUSANDS_SEP_WC);
		  mbrtowc(&thousands_sepwc,thousands_sepmb, CHAR_MAX, NULL);
		}
	      else
		{
		  thousands_sepmb = nl_langinfo (_NL_MONETARY_THOUSANDS_SEP_WC);
		  mbrtowc(&thousands_sepwc,thousands_sepmb, CHAR_MAX, NULL);
		}
	    }
	  else
	    {
	      if (info->extra == 0)
		thousands_sep = nl_langinfo (__THOUSANDS_SEP);
	      else
		thousands_sep = nl_langinfo (__MON_THOUSANDS_SEP);
	    }

	  if ((wide && thousands_sepwc == L'\0')
	      || (! wide && *thousands_sep == '\0'))
	    grouping = NULL;
	  else if (thousands_sepwc == L'\0')
	    /* If we are printing multibyte characters and there is a
	       multibyte representation for the thousands separator,
	       we must ensure the wide character thousands separator
	       is available, even if it is fake.  */
	    thousands_sepwc = 0xfffffffe;
	}
    }
  else
    grouping = NULL;
#else
  grouping = NULL;
#endif

  /* Seriously, only touch this code if you MUST.  */

{
  char digits[DECIMAL_PRINTF_BUF_SIZE];
  int exp,       /* The exponent. */
   is_neg,       /* Is negative?  */
   is_nan,       /* Is not a number?  */
   is_inf,       /* Is infinite? */
   decpt = 2,    /* decimal point offset into digits[] */
   prec,         /* number of digits that follow the decimal point, or number of significant digits for %g */
   default_prec = 6, /* Default precision, per the C Spec.  */
   input_prec = 0,   /* Precision of the _Decimal* value.  */
   mw,           /* Mantissa Width  */
   n,            /* Current digit offset into digits[] */
   nd,           /* num_digits before the get_digits call. */
   width,        /* Width of the field */
   is_zero = 0;  /* Used in some of the output tests.  */

  digits[0] = '0'; /* need an extra digit for rounding up */

  if (info->user & mod_D)
    {
      _Decimal64 d64 = **(_Decimal64**)args[0];
      if (d64 == 0) is_zero = 1;
      nd = numdigitsd64(d64);
      __get_digits_d64 (d64, digits+1, &exp, &is_neg, &is_nan, &is_inf);
      mw = __DEC64_MANT_DIG__ + 1;
    }
  else if (info->user & mod_DD)
    {
      _Decimal128 d128 = **(_Decimal128**)args[0];
      if (d128 == 0) is_zero = 1;
      nd = numdigitsd128(d128);
      __get_digits_d128 (d128, digits+1, &exp, &is_neg, &is_nan, &is_inf);
      mw = __DEC128_MANT_DIG__ + 1;
    }
  else if (info->user & mod_H)
    {
       _Decimal32 d32 = **(_Decimal32**)args[0];
       if (d32 == 0) is_zero = 1;
       nd = numdigitsd32(d32);
       __get_digits_d32 (d32, digits+1, &exp, &is_neg, &is_nan, &is_inf);
       mw = __DEC32_MANT_DIG__ + 1;
    }
  else /* We shouldn't get here, but it is possible.  */
    return -2;

  /* The first digit is always a zero to allow rounding.  */
  n = 0;

  /* 'n' = position of first non-zero digit in the right-justified mantissa.  */
  n = mw - nd;

  /* Width and precision can not both be set or the results are undefined per
   * the C Spec.  */
  width = info->width;

  /* The user specified precision overrides the input's inherent precision.
   * This gets complicated quickly.  */
  prec = info->prec;

  if (is_nan || is_inf)
    {
      width -= 3;
      /*if (is_nan) is_neg = 0;*/
      if (is_neg || info->showsign || info->space) width--;

      if (!info->left && width > 0)
	PADN (' ', width);

      if (is_neg)
	outchar ('-');
      else if (info->showsign)
	outchar ('+');
      else if (info->space)
	outchar (' ');

      if (is_nan)
	{
	  if (isupper(info->spec))
	    { outchar ('N'); outchar ('A'); outchar ('N'); }
	  else
	    { outchar ('n'); outchar ('a'); outchar ('n'); }
	}
      else
	{
	  if (isupper(info->spec))
	    { outchar ('I'); outchar ('N'); outchar ('F'); }
	  else
	    { outchar ('i'); outchar ('n'); outchar ('f'); }
	}
      if (info->left && width > 0)
	PADN (' ', width);

	return 0;
    }

  /* The term "precision" refers to the number of significant digits right of
   * the decimal place.  Determine the implicit precision of the input value.
   * There are special rules for each of the supported flags.*/
  switch (spec)
    {
      case 'a':
	  {
	    /* The DFP spec addition for %a refers to all of the significant
	     * digits in the precision.  */
	    input_prec = nd;

	    /* This same check is done in two different places but it'll only
	     * effect a single pass through once.  If prec is not set it'll hit
	     * this instance.  If prec is set it'll hit the next instance.  This
	     * is because the DFP spec requires this to be run after rounding
	     * when prec < input_prec.  */
	    if (prec < 0 || prec >= input_prec)
	    {
	      /* Per the DFP specification (s,c,q), c == digits, q = exp, s ==
	       * is_neg.  */
	      if (exp >= -(nd+5) && exp <= 0)
	        {
	          prec = -exp;
	          spec = 'f';
	        }
	      else
	        {
	          prec = nd - 1;
	          spec = 'e';
	          input_prec = nd - 1;
	        }
	      }
	    break;
	  }
	case 'g':
	  {
	    int P = prec;

	    /* When the C specification refers to X as the exponent it means the
	     * exponent when the input value encoding is normalized to the form
	     * d.dddd.  This means we have to do that before we can do the goof
	     * check.
	     *
	     * e.g., 123.456E-5
	     * right-justified -> 00123456E-9
	     * normalized -> 1.23456E-4
	     *
	     * Normalize X to d.ddd... form by taking (exp) + (nd - 1)
	     *
	     * X == -4  */
	    int X = exp + (nd -1);

	    /* The C Specification also indicates how to compute P. */
	    if (prec < 0)
	      P = 6;
	    else if (prec == 0)
	      P = 1;

	    /* Straight from the specification which assumes X is exponent normalized to
	     * d.ddd... form.  */
	    if (X >= -4 && P > X)
	      {
		prec = (P - (X + 1));
		spec = 'f';
	      }
	    else
	      {
		prec = P - 1;
		spec = 'e';
	      }
	    input_prec = nd - 1;
	  break;
	  }
	case 'e':
	  input_prec = nd - 1;
	  break;
	case 'f':
	  if(exp < 0 && (-exp) > default_prec)
	    /*  00123456E-7 has an input_prec of 7. */
	    input_prec = (-exp);
	  else
	    /*  01234567E-6 has an input_prec of 6. */
	    /*  00000190E6 has an input_prec of 6. */
	    /*  00000123E1 has an input_prec of 6.  */
	    /*  00000123E0 has an input_prec of 6.  */
	    input_prec = default_prec;
	  break;
    }

  /* The specs 'g' and 'a' may have already modified prec so this won't happen for
   * those cases.  */
  if (prec < 0)
    prec = default_prec;

  /* Do rounding if precision is less than the decimal type.  On hardware DFP
   * this could probably easily be done with quantize but on soft-dfp the
   * existing method would be faster.  */
  if (prec < input_prec)
    {
      int index, roundmode = 0;
      char rounddigit = '4';

      if (spec == 'f')
	/* This may force index to negative, in which case we ignore it at a
	 * later time.  */
	index = n + nd + exp + prec;
      /* Goofy special case where we round significant digits which aren't
       * right of the decimal place.  */
      else if (tolower(info->spec) == 'a' && prec > 0)
       {
	index = n + prec;
       }
      else
	index = n + prec + 1;

      /* FIXME: we should check rounding mode for %a */
      if (__printf_dfp_getround_callback)
        {
          roundmode = (*__printf_dfp_getround_callback)();

	  switch (roundmode)
	    {
	      case FE_DEC_TONEAREST: rounddigit = '4'; break;
	      case FE_DEC_TOWARDZERO: rounddigit = '9'; break;
	      case FE_DEC_UPWARD: rounddigit = (is_neg ? '9' : '0'-1); break;
	      case FE_DEC_DOWNWARD: rounddigit = (is_neg ? '0'-1 : '9'); break;
	      case FE_DEC_TONEARESTFROMZERO: rounddigit = '4'; break;
	      case 5: rounddigit = '4'; break; /* nearest, ties toward zero */
	      case 6: rounddigit = '0'-1; break; /* away from zero */
	      case 7: rounddigit = '4'; break; /* round for shorter precision */
	      default: rounddigit = '4'; break;
	    }
	}

      /* If this is true then the requested precision is smaller than the
      * default and rounding is required.  If 'exp' was sufficiently negative
      * 'index' may be negative, in which case we don't need to round.  */
      if (index > 0 && index < mw && digits[index] > rounddigit) 
	do {
	  int trailzero = index+1;
	  if (digits[index] == rounddigit+1)
	    {
	      while (trailzero < mw)
		{
		  if (digits[trailzero] != '0')
		    {
		      trailzero = 0;
		      break;
		    }
		  ++trailzero;
		}
	      if (roundmode == FE_DEC_TONEAREST && trailzero &&
	        (digits[index-1] & 1) == 0) break;
	      if (roundmode == FE_DEC_UPWARD && !trailzero) break;
	      if (roundmode == FE_DEC_DOWNWARD && !trailzero) break;
	      if (roundmode == 5 && trailzero) break;
	      if (roundmode == 6 && trailzero) break;
	  }

	while (digits[--index] == '9')
	  digits[index] = '0';
	digits[index]++;
	if (index < n)
	  {
	    n--;
	    nd++;
	  }
      } while (0);
    } /* Done rounding.  */

  /* If spec == 'a' at this point it means that prec was set by the user
   * and rounding had to be considered.  The spec now requires that the
   * 'a' format presentation algorithm be calculated again.  If prec
   * wasn't set by the user then this was handled earlier and spec has already
   * been set to either 'e' or 'f'.  */
  if (spec == 'a')
    {
      int old_exp = exp;

      /* The goofy DFP specification requires that we now assume that after
       * rounding the digits are right justified and truncated and the
       * algorithm recomputed using the new values for nd and exp, e.g.,
       *
       * 00654300E-2 with %.1Hf -> 00000007E3.  */

       exp = nd + exp - prec;
       nd = prec;

      /* Per the DFP specification (s,c,q), c == digits, q = exp, s ==
      * is_neg.  */
      if (exp >= -(nd+5) && exp <= 0)
	{
	  prec = -exp;
	  spec = 'f';
	}
      else
	{
	  prec = nd - 1;
	  if (prec < 0) prec = 0;
	  spec = 'e';
	  input_prec = nd - 1;
	  /* Return exp to the original value because the 'e' case below will
	   * recompute it.  */
	  exp = old_exp;
	}
	/* spec will have been changed to 'e' or 'f' at this point, so determine
	* the decimal point now.  */
    }

  /* Calculate decimal point, adjust prec and exp if necessary.
   * By this point everything should be represented as either %e or %f.  */
  if (spec == 'f')
    {
      if (exp < 0)
	decpt = exp + nd + n;
      else if (is_zero)
	decpt = n + 1;
      else
	decpt = n + nd + exp;
    }
  else if (spec == 'e')
    {
      decpt = n + 1;
      exp = mw + exp - decpt;
    }

  /* Remove trailing zeroes for %g */
  if (tolower(info->spec) == 'g' && !info->alt)
    {
      while (prec > 0 && decpt+prec > mw) prec--;
      while (prec > 0 && digits[decpt+prec-1] == '0') prec--;
    }

  /* Remove trailing zeroes for %a, but only if they are not significant.  */
  if (tolower(info->spec) == 'a')
    {
      while (prec > 0 && decpt+prec > mw) prec--;
      while (prec > 0 && decpt+prec > n+nd && digits[decpt+prec-1] == '0') prec--;
    }

  /* Digits to the left of the decimal pt. */
  if (n < decpt)
    {
      width -= decpt - n;
      if (grouping) width -= (decpt-n)/3;
    }
  else width--;  /* none to the left of the decimal point */

  /* Digits to the right of the decimal pt. */
  if (prec > 0) width -= 1 + prec;
  else if (info->alt) width -= 1;

  if (spec != 'f')
    {
      width -= 3;
      if (0!=(exp/10) || spec!='a') --width;
      if (0!=(exp/100)) --width;
      if (0!=(exp/1000)) --width;
    }

  if (is_neg || info->showsign || info->space) width--;

  if (!info->left && info->pad != '0' && width > 0)
    PADN (info->pad, width);

  if (is_neg)
    outchar ('-');
  else if (info->showsign)
    outchar ('+');
  else if (info->space)
    outchar (' ');

  if (!info->left && info->pad == '0' && width > 0)
    PADN ('0', width);

  /* Print zero, decimal point and leading zeroes if needed */
  if (decpt <= n)
    {
      n = decpt;
      outchar ('0');
      if (n < 0)
	{
	  outchar (wide ? decimalwc.wc : *decimal);
	  while (n < 0 && n < decpt + prec)
	    {
	      outchar ('0');
	      n++;
	    }
	}
    }

  /* Print the digits.  If decpt exceeds mw then we know that
   * they're simply trailing zeros and we don't need to display them.  */
  while (n < mw && n < decpt + prec)
    {
      if (n == decpt)
      {
	outchar (wide ? decimalwc.wc : *decimal);
      }
      else if (grouping && n < decpt && (decpt-n)%3 == 0)
	outchar (wide ? thousands_sepwc : *thousands_sep);
      outchar (digits[n]);
      n++;
    }

  /* print trailing zeroes */
  while (n < decpt + prec)
    {
      if (n == decpt)
	outchar (wide ? decimalwc.wc : *decimal);
      else if (grouping && n < decpt && (decpt-n)%3 == 0)
	outchar (wide ? thousands_sepwc : *thousands_sep);
      outchar ('0');
      n++;
    }

  /* print decimal point, if needed */
  if (n == decpt && info->alt) outchar (wide ? decimalwc.wc : *decimal);

  /* The C spec says that for %e, if the value is zero the exponent is zero.
   * This isn't true for the DFP spec for %a so make sure to check info->spec
   * and not spec since it could have promoted 'a' to 'e'.  */
  if(spec == 'e' && (tolower(info->spec) != 'a' && is_zero))
    exp = 0;

  /* Don't display the exponent part for 'f' because it is never used and don't
   * do it for 'g' if the value is zero.  */
  if (spec != 'f' && !((tolower(info->spec) == 'g') && is_zero))
    {
      outchar (isupper(info->spec) ? 'E' : 'e');
      if (exp < 0)
	{ outchar ('-'); n = -exp; }
      else
	{ outchar ('+'); n = exp; }
      if (n >= 1000) outchar ('0'+((n/1000)%10));
      if (n >= 100) outchar ('0'+((n/100)%10));
      if (n >= 10 || (tolower(info->spec) != 'a')) outchar ('0'+((n/10)%10));
      outchar ('0'+(n%10));
    }

  if (info->left && width > 0)
    PADN (info->pad, width);
} /* Done output block.  */

   return 0;
}
コード例 #23
0
ファイル: rdesktop.c プロジェクト: tomyl/rdesktop-agent
/* Client program */
int
main(int argc, char *argv[])
{
	char server[64];
	char fullhostname[64];
	char domain[256];
	char password[64];
	char shell[256];
	char directory[256];
	RD_BOOL prompt_password, deactivated;
	struct passwd *pw;
	uint32 flags, ext_disc_reason = 0;
	char *p;
	int c;
	char *locale = NULL;
	int username_option = 0;
	RD_BOOL geometry_option = False;
#ifdef WITH_RDPSND
	char *rdpsnd_optarg = NULL;
#endif

#ifdef HAVE_LOCALE_H
	/* Set locale according to environment */
	locale = setlocale(LC_ALL, "");
	if (locale)
	{
		locale = xstrdup(locale);
	}

#endif

	/* Ignore SIGPIPE, since we are using popen() */
	struct sigaction act;
	memset(&act, 0, sizeof(act));
	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGPIPE, &act, NULL);

	flags = RDP_LOGON_NORMAL;
	prompt_password = False;
	domain[0] = password[0] = shell[0] = directory[0] = 0;
	g_embed_wnd = 0;

	g_num_devices = 0;

#ifdef RDP2VNC
#define VNCOPT "V:Q:"
#else
#define VNCOPT
#endif

	while ((c = getopt(argc, argv,
			   VNCOPT "Au:L:d:s:c:p:n:k:G:g:fbBeEmzCDKS:T:NX:a:x:Pr:045h?")) != -1)
	{
		switch (c)
		{
            case 'G':
				STRNCPY(g_agent, optarg, sizeof(g_agent));
                break;

#ifdef RDP2VNC
			case 'V':
				rfb_port = strtol(optarg, NULL, 10);
				if (rfb_port < 100)
					rfb_port += 5900;
				break;

			case 'Q':
				defer_time = strtol(optarg, NULL, 10);
				if (defer_time < 0)
					defer_time = 0;
				break;
#endif

			case 'A':
				g_seamless_rdp = True;
				break;

			case 'u':
				g_username = (char *) xmalloc(strlen(optarg) + 1);
				STRNCPY(g_username, optarg, strlen(optarg) + 1);
				username_option = 1;
				break;

			case 'L':
#ifdef HAVE_ICONV
				STRNCPY(g_codepage, optarg, sizeof(g_codepage));
#else
				error("iconv support not available\n");
#endif
				break;

			case 'd':
				STRNCPY(domain, optarg, sizeof(domain));
				break;

			case 's':
				STRNCPY(shell, optarg, sizeof(shell));
				break;

			case 'c':
				STRNCPY(directory, optarg, sizeof(directory));
				break;

			case 'p':
				if ((optarg[0] == '-') && (optarg[1] == 0))
				{
					prompt_password = True;
					break;
				}

				STRNCPY(password, optarg, sizeof(password));
				flags |= RDP_LOGON_AUTO;

				/* try to overwrite argument so it won't appear in ps */
				p = optarg;
				while (*p)
					*(p++) = 'X';
				break;

			case 'n':
				STRNCPY(g_hostname, optarg, sizeof(g_hostname));
				break;

			case 'k':
				STRNCPY(g_keymapname, optarg, sizeof(g_keymapname));
				break;

			case 'g':
				geometry_option = True;
				g_fullscreen = False;
				if (!strcmp(optarg, "workarea"))
				{
					g_sizeopt = 1;
					break;
				}

				g_width = strtol(optarg, &p, 10);
				if (g_width <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == 'x')
					g_height = strtol(p + 1, &p, 10);

				if (g_height <= 0)
				{
					error("invalid geometry\n");
					return EX_USAGE;
				}

				if (*p == '%')
				{
					g_sizeopt = -g_width;
					g_width = 800;
					p++;
				}

				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 2 : 1;
					g_xpos = strtol(p, &p, 10);

				}
				if (*p == '+' || *p == '-')
				{
					g_pos |= (*p == '-') ? 4 : 1;
					g_ypos = strtol(p, NULL, 10);
				}

				break;

			case 'f':
				g_fullscreen = True;
				break;

			case 'b':
				g_bitmap_cache = False;
				break;

			case 'B':
				g_ownbackstore = False;
				break;

			case 'e':
				g_encryption = False;
				break;
			case 'E':
				g_packet_encryption = False;
				break;
			case 'm':
				g_sendmotion = False;
				break;

			case 'C':
				g_owncolmap = True;
				break;

			case 'D':
				g_hide_decorations = True;
				break;

			case 'K':
				g_grab_keyboard = False;
				break;

			case 'S':
				if (!strcmp(optarg, "standard"))
				{
					g_win_button_size = 18;
					break;
				}

				g_win_button_size = strtol(optarg, &p, 10);

				if (*p)
				{
					error("invalid button size\n");
					return EX_USAGE;
				}

				break;

			case 'T':
				STRNCPY(g_title, optarg, sizeof(g_title));
				break;

			case 'N':
				g_numlock_sync = True;
				break;

			case 'X':
				g_embed_wnd = strtol(optarg, NULL, 0);
				break;

			case 'a':
				g_server_depth = strtol(optarg, NULL, 10);
				if (g_server_depth != 8 &&
				    g_server_depth != 16 &&
				    g_server_depth != 15 && g_server_depth != 24
				    && g_server_depth != 32)
				{
					error("Invalid server colour depth.\n");
					return EX_USAGE;
				}
				break;

			case 'z':
				DEBUG(("rdp compression enabled\n"));
				flags |= (RDP_LOGON_COMPRESSION | RDP_LOGON_COMPRESSION2);
				break;

			case 'x':
				if (str_startswith(optarg, "m"))	/* modem */
				{
					g_rdp5_performanceflags =
						RDP5_NO_WALLPAPER | RDP5_NO_FULLWINDOWDRAG |
						RDP5_NO_MENUANIMATIONS | RDP5_NO_THEMING;
				}
				else if (str_startswith(optarg, "b"))	/* broadband */
				{
					g_rdp5_performanceflags = RDP5_NO_WALLPAPER;
				}
				else if (str_startswith(optarg, "l"))	/* lan */
				{
					g_rdp5_performanceflags = RDP5_DISABLE_NOTHING;
				}
				else
				{
					g_rdp5_performanceflags = strtol(optarg, NULL, 16);
				}
				break;

			case 'P':
				g_bitmap_cache_persist_enable = True;
				break;

			case 'r':

				if (str_startswith(optarg, "sound"))
				{
					optarg += 5;

					if (*optarg == ':')
					{
						optarg++;
						while ((p = next_arg(optarg, ',')))
						{
							if (str_startswith(optarg, "remote"))
								flags |= RDP_LOGON_LEAVE_AUDIO;

							if (str_startswith(optarg, "local"))
#ifdef WITH_RDPSND
							{
								rdpsnd_optarg =
									next_arg(optarg, ':');
								g_rdpsnd = True;
							}

#else
								warning("Not compiled with sound support\n");
#endif

							if (str_startswith(optarg, "off"))
#ifdef WITH_RDPSND
								g_rdpsnd = False;
#else
								warning("Not compiled with sound support\n");
#endif

							optarg = p;
						}
					}
					else
					{
#ifdef WITH_RDPSND
						g_rdpsnd = True;
#else
						warning("Not compiled with sound support\n");
#endif
					}
				}
				else if (str_startswith(optarg, "disk"))
				{
					/* -r disk:h:=/mnt/floppy */
					disk_enum_devices(&g_num_devices, optarg + 4);
				}
				else if (str_startswith(optarg, "comport"))
				{
					serial_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "lspci"))
				{
					g_lspci_enabled = True;
				}
				else if (str_startswith(optarg, "lptport"))
				{
					parallel_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "printer"))
				{
					printer_enum_devices(&g_num_devices, optarg + 7);
				}
				else if (str_startswith(optarg, "clientname"))
				{
					g_rdpdr_clientname = xmalloc(strlen(optarg + 11) + 1);
					strcpy(g_rdpdr_clientname, optarg + 11);
				}
				else if (str_startswith(optarg, "clipboard"))
				{
					optarg += 9;

					if (*optarg == ':')
					{
						optarg++;

						if (str_startswith(optarg, "off"))
							g_rdpclip = False;
						else
							cliprdr_set_mode(optarg);
					}
					else
						g_rdpclip = True;
				}
				else if (strncmp("scard", optarg, 5) == 0)
				{
#ifdef WITH_SCARD
					scard_enum_devices(&g_num_devices, optarg + 5);
#else
					warning("Not compiled with smartcard support\n");
#endif
				}
				else
				{
					warning("Unknown -r argument\n\n\tPossible arguments are: comport, disk, lptport, printer, sound, clipboard, scard\n");
				}
				break;

			case '0':
				g_console_session = True;
				break;

			case '4':
				g_use_rdp5 = False;
				break;

			case '5':
				g_use_rdp5 = True;
				break;

			case 'h':
			case '?':
			default:
				usage(argv[0]);
				return EX_USAGE;
		}
	}

	if (argc - optind != 1)
	{
		usage(argv[0]);
		return EX_USAGE;
	}

	STRNCPY(server, argv[optind], sizeof(server));
	parse_server_and_port(server);

	if (g_seamless_rdp)
	{
		if (g_win_button_size)
		{
			error("You cannot use -S and -A at the same time\n");
			return EX_USAGE;
		}
		g_rdp5_performanceflags &= ~RDP5_NO_FULLWINDOWDRAG;
		if (geometry_option)
		{
			error("You cannot use -g and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_fullscreen)
		{
			error("You cannot use -f and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_hide_decorations)
		{
			error("You cannot use -D and -A at the same time\n");
			return EX_USAGE;
		}
		if (g_embed_wnd)
		{
			error("You cannot use -X and -A at the same time\n");
			return EX_USAGE;
		}
		if (!g_use_rdp5)
		{
			error("You cannot use -4 and -A at the same time\n");
			return EX_USAGE;
		}
		g_sizeopt = -100;
		g_grab_keyboard = False;
	}

	if (!username_option)
	{
		pw = getpwuid(getuid());
		if ((pw == NULL) || (pw->pw_name == NULL))
		{
			error("could not determine username, use -u\n");
			return EX_OSERR;
		}
		/* +1 for trailing \0 */
		int pwlen = strlen(pw->pw_name) + 1;
		g_username = (char *) xmalloc(pwlen);
		STRNCPY(g_username, pw->pw_name, pwlen);
	}

#ifdef HAVE_ICONV
	if (g_codepage[0] == 0)
	{
		if (setlocale(LC_CTYPE, ""))
		{
			STRNCPY(g_codepage, nl_langinfo(CODESET), sizeof(g_codepage));
		}
		else
		{
			STRNCPY(g_codepage, DEFAULT_CODEPAGE, sizeof(g_codepage));
		}
	}
#endif

	if (g_hostname[0] == 0)
	{
		if (gethostname(fullhostname, sizeof(fullhostname)) == -1)
		{
			error("could not determine local hostname, use -n\n");
			return EX_OSERR;
		}

		p = strchr(fullhostname, '.');
		if (p != NULL)
			*p = 0;

		STRNCPY(g_hostname, fullhostname, sizeof(g_hostname));
	}

	if (g_keymapname[0] == 0)
	{
		if (locale && xkeymap_from_locale(locale))
		{
			fprintf(stderr, "Autoselected keyboard map %s\n", g_keymapname);
		}
		else
		{
			STRNCPY(g_keymapname, "en-us", sizeof(g_keymapname));
		}
	}
	if (locale)
		xfree(locale);


	if (prompt_password && read_password(password, sizeof(password)))
		flags |= RDP_LOGON_AUTO;

	if (g_title[0] == 0)
	{
		strcpy(g_title, "rdesktop - ");
		strncat(g_title, server, sizeof(g_title) - sizeof("rdesktop - "));
	}

    agent_init();

#ifdef RDP2VNC
	rdp2vnc_connect(server, flags, domain, password, shell, directory);
	return EX_OK;
#else

	if (!ui_init())
		return EX_OSERR;

#ifdef WITH_RDPSND
	if (g_rdpsnd)
	{
		if (!rdpsnd_init(rdpsnd_optarg))
			warning("Initializing sound-support failed!\n");
	}
#endif

	if (g_lspci_enabled)
		lspci_init();

	rdpdr_init();

	while (1)
	{
		rdesktop_reset_state();

		if (g_redirect)
		{
			STRNCPY(domain, g_redirect_domain, sizeof(domain));
			xfree(g_username);
			g_username = (char *) xmalloc(strlen(g_redirect_username) + 1);
			STRNCPY(g_username, g_redirect_username, sizeof(g_username));
			STRNCPY(password, g_redirect_password, sizeof(password));
			STRNCPY(server, g_redirect_server, sizeof(server));
			flags |= RDP_LOGON_AUTO;
		}

		ui_init_connection();
		if (!rdp_connect(server, flags, domain, password, shell, directory, g_redirect))
			return EX_PROTOCOL;

		/* By setting encryption to False here, we have an encrypted login 
		   packet but unencrypted transfer of other packets */
		if (!g_packet_encryption)
			g_encryption = False;


		DEBUG(("Connection successful.\n"));
		memset(password, 0, sizeof(password));

		if (!g_redirect)
			if (!ui_create_window())
				return EX_OSERR;

		g_redirect = False;
		rdp_main_loop(&deactivated, &ext_disc_reason);

		DEBUG(("Disconnecting...\n"));
		rdp_disconnect();

		if (g_redirect)
			continue;

		ui_seamless_end();
		ui_destroy_window();
		if (g_pending_resize)
		{
			/* If we have a pending resize, reconnect using the new size, rather than exit */
			g_pending_resize = False;
			continue;
		}
		break;
	}

	cache_save_state();
	ui_deinit();

	if (g_user_quit)
		return EXRD_WINDOW_CLOSED;

	return handle_disconnect_reason(deactivated, ext_disc_reason);

#endif
	if (g_redirect_username)
		xfree(g_redirect_username);

	xfree(g_username);
}
コード例 #24
0
/* langinfo */
static int _langinfo(char const * progname, nl_item item)
{
	printf("%s: nl_langinfo(%lu) returns \"%s\"\n", progname, item,
			nl_langinfo(item));
	return 0;
}
コード例 #25
0
ファイル: formatstring.c プロジェクト: eburuschkin/rlib
gint rlib_number_sprintf(rlib *r, gchar **woot_dest, gchar *fmtstr, const struct rlib_value *rval, gint special_format, gchar *infix, gint line_number) {
	gint dec=0;
	gint left_padzero=0;
	gint left_pad=0;
	gint right_padzero=1;
	gint right_pad=0;
	gint where=0;
	gint commatize=0;
	gchar *c;
	gchar *radixchar = nl_langinfo(RADIXCHAR);
	GString *dest = g_string_sized_new(MAX_NUMBER);
	gint slen;
	
	for(c=fmtstr;*c && (*c != 'd');c++) {
		if(*c=='$') {
			commatize=1;
		}
		if(*c=='%') {
			where=0;
		} else if(*c=='.') {
			dec=1;
			where=1;
		} else if(isdigit(*c)) {		
			if(where==0) {
				if(left_pad == 0 && (*c-'0') == 0)
					left_padzero = 1;
				left_pad *= 10;
				left_pad += (*c-'0');
			} else {
				right_pad *= 10;
				right_pad += (*c-'0');
			}
		}	
	}
	if (!left_pad)
		left_padzero = 1;
	if (!right_pad)
		right_padzero = 1;
	if(rval != NULL) {
		gchar fleft[MAX_FORMAT_STRING];
		gchar fright[MAX_FORMAT_STRING];
		gchar left_holding[MAX_NUMBER];
		gchar right_holding[MAX_NUMBER];
		gint ptr=0;
		gint64 left=0, right=0;
		
		if(left_pad > MAX_FORMAT_STRING) {
			r_error(r, "LINE %d FORMATTING ERROR: %s\n", line_number, infix);
			r_error(r, "FORMATTING ERROR:  LEFT PAD IS WAY TO BIG! (%d)\n", left_pad);
			left_pad = MAX_FORMAT_STRING;
		} 
		if(right_pad > MAX_FORMAT_STRING) {
			r_error(r, "LINE %d FORMATTING ERROR: %s\n", line_number, infix);
			r_error(r, "FORMATTING ERROR:  LEFT PAD IS WAY TO BIG! (%d)\n", right_pad);			
			right_pad = MAX_FORMAT_STRING;
		} 
		
		left = RLIB_VALUE_GET_AS_NUMBER(rval) / RLIB_DECIMAL_PRECISION;
		if(special_format)
			left = llabs(left);
		fleft[ptr++]='%';
		if(left_padzero)
			fleft[ptr++]='0';
		if(left_pad)
			if(commatize) {
				sprintf(fleft +ptr, "%d'" PRId64, left_pad);
			} else
				sprintf(fleft +ptr, "%d" PRId64, left_pad);
		else {
			char	*int64fmt = PRId64;
			int	i;

			if(commatize)
				fleft[ptr++] = '\'';
			for (i = 0; int64fmt[i]; i++)
				fleft[ptr++] = int64fmt[i];
			fleft[ptr++] = '\0';
		}
		if(left_pad == 0 && left == 0) {
			gint spot=0;
			if(RLIB_VALUE_GET_AS_NUMBER(rval) < 0)
				left_holding[spot++] = '-';
			left_holding[spot++] = '0';
			left_holding[spot++] = 0;			
		} else {
			sprintf(left_holding, fleft, left);
		}
		dest = g_string_append(dest, left_holding);
		if(dec) {
			ptr=0;
			right = llabs(RLIB_VALUE_GET_AS_NUMBER(rval)) % RLIB_DECIMAL_PRECISION;
			fright[ptr++]='%';
			if(right_padzero)
				fright[ptr++]='0';
			if(right_pad)
				sprintf(&fright[ptr], "%d" PRId64, right_pad);
			else {
				char	*int64fmt = PRId64;
				int	i;

				for (i = 0; int64fmt[i]; i++)
					fright[ptr++] = int64fmt[i];
				fright[ptr++] = '\0';
			}
			right /= tentothe(RLIB_FXP_PRECISION-right_pad);
			sprintf(right_holding, fright, right);
			dest = g_string_append(dest, radixchar);
			dest = g_string_append(dest, right_holding);
		}
	}
	*woot_dest = dest->str;
	change_radix_character(r, *woot_dest);
	slen = dest->len;
	g_string_free(dest, FALSE);
	return slen;
}
コード例 #26
0
ファイル: localcharset.c プロジェクト: kkodani/cs35L
STATIC
#endif
const char *
locale_charset ()
{
    const char *codeset;
    const char *aliases;

#if !(defined WIN32 || defined OS2)

# if HAVE_LANGINFO_CODESET

    /* Most systems support nl_langinfo (CODESET) nowadays.  */
    codeset = nl_langinfo (CODESET);

# else

    /* On old systems which lack it, use setlocale or getenv.  */
    const char *locale = NULL;

    /* But most old systems don't have a complete set of locales.  Some
       (like SunOS 4 or DJGPP) have only the C locale.  Therefore we don't
       use setlocale here; it would return "C" when it doesn't support the
       locale name the user has set.  */
#  if HAVE_SETLOCALE && 0
    locale = setlocale (LC_CTYPE, NULL);
#  endif
    if (locale == NULL || locale[0] == '\0')
    {
        locale = getenv ("LC_ALL");
        if (locale == NULL || locale[0] == '\0')
        {
            locale = getenv ("LC_CTYPE");
            if (locale == NULL || locale[0] == '\0')
                locale = getenv ("LANG");
        }
    }

    /* On some old systems, one used to set locale = "iso8859_1". On others,
       you set it to "language_COUNTRY.charset". In any case, we resolve it
       through the charset.alias file.  */
    codeset = locale;

# endif

#elif defined WIN32

    static char buf[2 + 10 + 1];

    /* Woe32 has a function returning the locale's codepage as a number.  */
    sprintf (buf, "CP%u", GetACP ());
    codeset = buf;

#elif defined OS2

    const char *locale;
    static char buf[2 + 10 + 1];
    ULONG cp[3];
    ULONG cplen;

    /* Allow user to override the codeset, as set in the operating system,
       with standard language environment variables.  */
    locale = getenv ("LC_ALL");
    if (locale == NULL || locale[0] == '\0')
    {
        locale = getenv ("LC_CTYPE");
        if (locale == NULL || locale[0] == '\0')
            locale = getenv ("LANG");
    }
    if (locale != NULL && locale[0] != '\0')
    {
        /* If the locale name contains an encoding after the dot, return it.  */
        const char *dot = strchr (locale, '.');

        if (dot != NULL)
        {
            const char *modifier;

            dot++;
            /* Look for the possible @... trailer and remove it, if any.  */
            modifier = strchr (dot, '@');
            if (modifier == NULL)
                return dot;
            if (modifier - dot < sizeof (buf))
            {
                memcpy (buf, dot, modifier - dot);
                buf [modifier - dot] = '\0';
                return buf;
            }
        }

        /* Resolve through the charset.alias file.  */
        codeset = locale;
    }
    else
    {
        /* OS/2 has a function returning the locale's codepage as a number.  */
        if (DosQueryCp (sizeof (cp), cp, &cplen))
            codeset = "";
        else
        {
            sprintf (buf, "CP%u", cp[0]);
            codeset = buf;
        }
    }

#endif

    if (codeset == NULL)
        /* The canonical name cannot be determined.  */
        codeset = "";

    /* Resolve alias. */
    for (aliases = get_charset_aliases ();
            *aliases != '\0';
            aliases += strlen (aliases) + 1, aliases += strlen (aliases) + 1)
        if (strcmp (codeset, aliases) == 0
                || (aliases[0] == '*' && aliases[1] == '\0'))
        {
            codeset = aliases + strlen (aliases) + 1;
            break;
        }

    /* Don't return an empty string.  GNU libc and GNU libiconv interpret
       the empty string as denoting "the locale's character encoding",
       thus GNU libiconv would call this function a second time.  */
    if (codeset[0] == '\0')
        codeset = "ASCII";

    return codeset;
}
コード例 #27
0
struct lconv* ThreadSafeLocaleHandler::localeconv() {
  // glibc does not have localeconv_l, and so we need to do some shenanigans.
  struct lconv *ptr = g_thread_safe_localeconv_data.get();

  ptr->decimal_point = nl_langinfo(DECIMAL_POINT);
  ptr->thousands_sep = nl_langinfo(THOUSANDS_SEP);
  ptr->grouping = nl_langinfo(GROUPING);
  ptr->int_curr_symbol = nl_langinfo(INT_CURR_SYMBOL);
  ptr->currency_symbol = nl_langinfo(CURRENCY_SYMBOL);
  ptr->mon_decimal_point = nl_langinfo(MON_DECIMAL_POINT);
  ptr->mon_thousands_sep = nl_langinfo(MON_THOUSANDS_SEP);
  ptr->mon_grouping = nl_langinfo(MON_GROUPING);
  ptr->positive_sign = nl_langinfo(POSITIVE_SIGN);
  ptr->negative_sign = nl_langinfo(NEGATIVE_SIGN);
  ptr->int_frac_digits = nl_langinfo(INT_FRAC_DIGITS)[0];
  ptr->frac_digits = nl_langinfo(FRAC_DIGITS)[0];
  ptr->p_cs_precedes = nl_langinfo(P_CS_PRECEDES)[0];
  ptr->p_sep_by_space = nl_langinfo(P_SEP_BY_SPACE)[0];
  ptr->n_cs_precedes = nl_langinfo(N_CS_PRECEDES)[0];
  ptr->n_sep_by_space = nl_langinfo(N_SEP_BY_SPACE)[0];
  ptr->p_sign_posn = nl_langinfo(P_SIGN_POSN)[0];
  ptr->n_sign_posn = nl_langinfo(N_SIGN_POSN)[0];

  #ifdef __USE_ISOC99
  ptr->int_p_cs_precedes = nl_langinfo(INT_P_CS_PRECEDES)[0];
  ptr->int_p_sep_by_space = nl_langinfo(INT_P_SEP_BY_SPACE)[0];
  ptr->int_n_cs_precedes = nl_langinfo(INT_N_CS_PRECEDES)[0];
  ptr->int_n_sep_by_space = nl_langinfo(INT_N_SEP_BY_SPACE)[0];
  ptr->int_p_sign_posn = nl_langinfo(INT_P_SIGN_POSN)[0];
  ptr->int_n_sign_posn = nl_langinfo(INT_N_SIGN_POSN)[0];
  #else
  ptr->__int_p_cs_precedes = nl_langinfo(INT_P_CS_PRECEDES)[0];
  ptr->__int_p_sep_by_space = nl_langinfo(INT_P_SEP_BY_SPACE)[0];
  ptr->__int_n_cs_precedes = nl_langinfo(INT_N_CS_PRECEDES)[0];
  ptr->__int_n_sep_by_space = nl_langinfo(INT_N_SEP_BY_SPACE)[0];
  ptr->__int_p_sign_posn = nl_langinfo(INT_P_SIGN_POSN)[0];
  ptr->__int_n_sign_posn = nl_langinfo(INT_N_SIGN_POSN)[0];
  #endif

  return ptr;
}
コード例 #28
0
ファイル: weechat.c プロジェクト: celeron55/weechat
void
weechat_init (int argc, char *argv[], void (*gui_init_cb)())
{
    weechat_first_start_time = time (NULL); /* initialize start time        */
    gettimeofday (&weechat_current_start_timeval, NULL);

    weechat_locale_ok = (setlocale (LC_ALL, "") != NULL);   /* init gettext */
#ifdef ENABLE_NLS
    bindtextdomain (PACKAGE, LOCALEDIR);
    bind_textdomain_codeset (PACKAGE, "UTF-8");
    textdomain (PACKAGE);
#endif

#ifdef HAVE_LANGINFO_CODESET
    weechat_local_charset = strdup (nl_langinfo (CODESET));
#else
    weechat_local_charset = strdup ("");
#endif
    utf8_init ();

    /* catch signals */
    util_catch_signal (SIGINT, SIG_IGN);           /* signal ignored        */
    util_catch_signal (SIGQUIT, SIG_IGN);          /* signal ignored        */
    util_catch_signal (SIGPIPE, SIG_IGN);          /* signal ignored        */
    util_catch_signal (SIGSEGV, &debug_sigsegv);   /* crash dump            */
    util_catch_signal (SIGHUP, &weechat_sighup);   /* exit WeeChat          */
    util_catch_signal (SIGQUIT, &weechat_sigquit); /* exit WeeChat          */
    util_catch_signal (SIGTERM, &weechat_sigterm); /* exit WeeChat          */

    hdata_init ();                      /* initialize hdata                 */
    hook_init ();                       /* initialize hooks                 */
    debug_init ();                      /* hook signals for debug           */
    gui_color_init ();                  /* initialize colors                */
    gui_chat_init ();                   /* initialize chat                  */
    command_init ();                    /* initialize WeeChat commands      */
    completion_init ();                 /* add core completion hooks        */
    gui_key_init ();                    /* init keys                        */
    network_init_gcrypt ();             /* init gcrypt                      */
    if (!secure_init ())                /* init secured data options (sec.*)*/
        weechat_shutdown (EXIT_FAILURE, 0);
    if (!config_weechat_init ())        /* init WeeChat options (weechat.*) */
        weechat_shutdown (EXIT_FAILURE, 0);
    weechat_parse_args (argc, argv);    /* parse command line args          */
    weechat_create_home_dir ();         /* create WeeChat home directory    */
    log_init ();                        /* init log file                    */
    plugin_api_init ();                 /* create some hooks (info,hdata,..)*/
    secure_read ();                     /* read secured data options        */
    config_weechat_read ();             /* read WeeChat options             */
    network_init_gnutls ();             /* init GnuTLS                      */

    if (gui_init_cb)
        (*gui_init_cb) ();              /* init WeeChat interface           */

    if (weechat_upgrading)
    {
        upgrade_weechat_load ();        /* upgrade with session file        */
        weechat_upgrade_count++;        /* increase /upgrade count          */
    }
    weechat_welcome_message ();         /* display WeeChat welcome message  */
    gui_chat_print_lines_waiting_buffer (NULL); /* display lines waiting    */
    weechat_term_check ();              /* warnings about $TERM (if wrong)  */
    weechat_locale_check ();            /* warning about wrong locale       */
    command_startup (0);                /* command executed before plugins  */
    plugin_init (weechat_auto_load_plugins, /* init plugin interface(s)     */
                 argc, argv);
    command_startup (1);                /* commands executed after plugins  */
    if (!weechat_upgrading)
        gui_layout_window_apply (gui_layout_current, -1);
    if (weechat_upgrading)
        upgrade_weechat_end ();         /* remove .upgrade files + signal   */
}
コード例 #29
0
ファイル: pythonrun.c プロジェクト: fengsp/PyObject
void
Py_InitializeEx(int install_sigs)
{
	PyInterpreterState *interp;
	PyThreadState *tstate;
	PyObject *bimod, *sysmod;
	char *p;
#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
	char *codeset;
	char *saved_locale;
	PyObject *sys_stream, *sys_isatty;
#endif
	extern void _Py_ReadyTypes(void);

	if (initialized)
		return;
	initialized = 1;

	if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
		Py_DebugFlag = add_flag(Py_DebugFlag, p);
	if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
		Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
	if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
		Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);

	interp = PyInterpreterState_New();
	if (interp == NULL)
		Py_FatalError("Py_Initialize: can't make first interpreter");

	tstate = PyThreadState_New(interp);
	if (tstate == NULL)
		Py_FatalError("Py_Initialize: can't make first thread");
	(void) PyThreadState_Swap(tstate);

	_Py_ReadyTypes();

	if (!_PyFrame_Init())
		Py_FatalError("Py_Initialize: can't init frames");

	if (!_PyInt_Init())
		Py_FatalError("Py_Initialize: can't init ints");

	_PyFloat_Init();

	interp->modules = PyDict_New();
	if (interp->modules == NULL)
		Py_FatalError("Py_Initialize: can't make modules dictionary");

#ifdef Py_USING_UNICODE
	/* Init Unicode implementation; relies on the codec registry */
	_PyUnicode_Init();
#endif

	bimod = _PyBuiltin_Init();
	if (bimod == NULL)
		Py_FatalError("Py_Initialize: can't initialize __builtin__");
	interp->builtins = PyModule_GetDict(bimod);
	if (interp->builtins == NULL)
		Py_FatalError("Py_Initialize: can't initialize builtins dict");
	Py_INCREF(interp->builtins);

	sysmod = _PySys_Init();
	if (sysmod == NULL)
		Py_FatalError("Py_Initialize: can't initialize sys");
	interp->sysdict = PyModule_GetDict(sysmod);
	if (interp->sysdict == NULL)
		Py_FatalError("Py_Initialize: can't initialize sys dict");
	Py_INCREF(interp->sysdict);
	_PyImport_FixupExtension("sys", "sys");
	PySys_SetPath(Py_GetPath());
	PyDict_SetItemString(interp->sysdict, "modules",
			     interp->modules);

	_PyImport_Init();

	/* initialize builtin exceptions */
	_PyExc_Init();
	_PyImport_FixupExtension("exceptions", "exceptions");

	/* phase 2 of builtins */
	_PyImport_FixupExtension("__builtin__", "__builtin__");

	_PyImportHooks_Init();

	if (install_sigs)
		initsigs(); /* Signal handling stuff, including initintr() */

	initmain(); /* Module __main__ */
	if (!Py_NoSiteFlag)
		initsite(); /* Module site */

	/* auto-thread-state API, if available */
#ifdef WITH_THREAD
	_PyGILState_Init(interp, tstate);
#endif /* WITH_THREAD */

	warnings_module = PyImport_ImportModule("warnings");
	if (!warnings_module)
		PyErr_Clear();

#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
	/* On Unix, set the file system encoding according to the
	   user's preference, if the CODESET names a well-known
	   Python codec, and Py_FileSystemDefaultEncoding isn't
	   initialized by other means. Also set the encoding of
	   stdin and stdout if these are terminals.  */

	saved_locale = strdup(setlocale(LC_CTYPE, NULL));
	setlocale(LC_CTYPE, "");
	codeset = nl_langinfo(CODESET);
	if (codeset && *codeset) {
		PyObject *enc = PyCodec_Encoder(codeset);
		if (enc) {
			codeset = strdup(codeset);
			Py_DECREF(enc);
		} else {
			codeset = NULL;
			PyErr_Clear();
		}
	} else
		codeset = NULL;
	setlocale(LC_CTYPE, saved_locale);
	free(saved_locale);

	if (codeset) {
		sys_stream = PySys_GetObject("stdin");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stdin");
		}
		Py_XDECREF(sys_isatty);

		sys_stream = PySys_GetObject("stdout");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stdout");
		}
		Py_XDECREF(sys_isatty);

		sys_stream = PySys_GetObject("stderr");
		sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
		if (!sys_isatty)
			PyErr_Clear();
		if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
			if (!PyFile_SetEncoding(sys_stream, codeset))
				Py_FatalError("Cannot set codeset of stderr");
		}
		Py_XDECREF(sys_isatty);

		if (!Py_FileSystemDefaultEncoding)
			Py_FileSystemDefaultEncoding = codeset;
		else
			free(codeset);
	}
#endif
}
コード例 #30
0
static int
archive_write_zip_header(struct archive_write *a, struct archive_entry *entry)
{
	struct zip *zip;
	struct zip_local_file_header h;
	struct zip_extra_data_local e;
	struct zip_data_descriptor *d;
	struct zip_file_header_link *l;
	struct archive_string_conv *sconv;
	int ret, ret2 = ARCHIVE_OK;
	int64_t size;
	mode_t type;

	/* Entries other than a regular file or a folder are skipped. */
	type = archive_entry_filetype(entry);
	if ((type != AE_IFREG) & (type != AE_IFDIR)) {
		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
		    "Filetype not supported");
		return ARCHIVE_FAILED;
	}; 

	/* Directory entries should have a size of 0. */
	if (type == AE_IFDIR)
		archive_entry_set_size(entry, 0);

	zip = a->format_data;
	/* Setup default conversion. */
	if (zip->opt_sconv == NULL && !zip->init_default_conversion) {
		zip->sconv_default =
		    archive_string_default_conversion_for_write(&(a->archive));
		zip->init_default_conversion = 1;
	}

	if (zip->flags == 0) {
		/* Initialize the general purpose flags. */
		zip->flags = ZIP_FLAGS;
		if (zip->opt_sconv != NULL) {
			if (strcmp(archive_string_conversion_charset_name(
			    zip->opt_sconv), "UTF-8") == 0)
				zip->flags |= ZIP_FLAGS_UTF8_NAME;
#if HAVE_NL_LANGINFO
		} else if (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) {
			zip->flags |= ZIP_FLAGS_UTF8_NAME;
#endif
		}
	}
	d = &zip->data_descriptor;
	size = archive_entry_size(entry);
	zip->remaining_data_bytes = size;

	/* Append archive entry to the central directory data. */
	l = (struct zip_file_header_link *) malloc(sizeof(*l));
	if (l == NULL) {
		archive_set_error(&a->archive, ENOMEM,
		    "Can't allocate zip header data");
		return (ARCHIVE_FATAL);
	}
	l->entry = archive_entry_clone(entry);
	l->flags = zip->flags;
	if (zip->opt_sconv != NULL)
		sconv = zip->opt_sconv;
	else
		sconv = zip->sconv_default;
	if (sconv != NULL) {
		const char *p;
		size_t len;

		if (archive_entry_pathname_l(entry, &p, &len, sconv) != 0) {
			if (errno == ENOMEM) {
				archive_set_error(&a->archive, ENOMEM,
				    "Can't allocate memory for Pathname");
				return (ARCHIVE_FATAL);
			}
			archive_set_error(&a->archive,
			    ARCHIVE_ERRNO_FILE_FORMAT,
			    "Can't translate pathname '%s' to %s",
			    archive_entry_pathname(entry),
			    archive_string_conversion_charset_name(sconv));
			ret2 = ARCHIVE_WARN;
		}
		if (len > 0)
			archive_entry_set_pathname(l->entry, p);
	}
	/* If all character of a filename is ASCII, Reset UTF-8 Name flag. */
	if ((l->flags & ZIP_FLAGS_UTF8_NAME) != 0 &&
	    is_all_ascii(archive_entry_pathname(l->entry)))
		l->flags &= ~ZIP_FLAGS_UTF8_NAME;

	/* Initialize the CRC variable and potentially the local crc32(). */
	l->crc32 = crc32(0, NULL, 0);
	l->compression = zip->compression;
	l->compressed_size = 0;
	l->next = NULL;
	if (zip->central_directory == NULL) {
		zip->central_directory = l;
	} else {
		zip->central_directory_end->next = l;
	}
	zip->central_directory_end = l;

	/* Store the offset of this header for later use in central directory. */
	l->offset = zip->written_bytes;

	memset(&h, 0, sizeof(h));
	archive_le32enc(&h.signature, ZIP_SIGNATURE_LOCAL_FILE_HEADER);
	archive_le16enc(&h.version, ZIP_VERSION_EXTRACT);
	archive_le16enc(&h.flags, l->flags);
	archive_le16enc(&h.compression, zip->compression);
	archive_le32enc(&h.timedate, dos_time(archive_entry_mtime(entry)));
	archive_le16enc(&h.filename_length, (uint16_t)path_length(l->entry));

	switch (zip->compression) {
	case COMPRESSION_STORE:
		/* Setting compressed and uncompressed sizes even when specification says
		 * to set to zero when using data descriptors. Otherwise the end of the
		 * data for an entry is rather difficult to find. */
		archive_le32enc(&h.compressed_size, size);
		archive_le32enc(&h.uncompressed_size, size);
		break;
#ifdef HAVE_ZLIB_H
	case COMPRESSION_DEFLATE:
		archive_le32enc(&h.uncompressed_size, size);

		zip->stream.zalloc = Z_NULL;
		zip->stream.zfree = Z_NULL;
		zip->stream.opaque = Z_NULL;
		zip->stream.next_out = zip->buf;
		zip->stream.avail_out = zip->len_buf;
		if (deflateInit2(&zip->stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
		    -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
			archive_set_error(&a->archive, ENOMEM,
			    "Can't init deflate compressor");
			return (ARCHIVE_FATAL);
		}
		break;
#endif
	}

	/* Formatting extra data. */
	archive_le16enc(&h.extra_length, sizeof(e));
	archive_le16enc(&e.time_id, ZIP_SIGNATURE_EXTRA_TIMESTAMP);
	archive_le16enc(&e.time_size, sizeof(e.time_flag) +
	    sizeof(e.mtime) + sizeof(e.atime) + sizeof(e.ctime));
	e.time_flag[0] = 0x07;
	archive_le32enc(&e.mtime, archive_entry_mtime(entry));
	archive_le32enc(&e.atime, archive_entry_atime(entry));
	archive_le32enc(&e.ctime, archive_entry_ctime(entry));

	archive_le16enc(&e.unix_id, ZIP_SIGNATURE_EXTRA_NEW_UNIX);
	archive_le16enc(&e.unix_size, sizeof(e.unix_version) +
	    sizeof(e.unix_uid_size) + sizeof(e.unix_uid) +
	    sizeof(e.unix_gid_size) + sizeof(e.unix_gid));
	e.unix_version = 1;
	e.unix_uid_size = 4;
	archive_le32enc(&e.unix_uid, archive_entry_uid(entry));
	e.unix_gid_size = 4;
	archive_le32enc(&e.unix_gid, archive_entry_gid(entry));

	archive_le32enc(&d->uncompressed_size, size);

	ret = __archive_write_output(a, &h, sizeof(h));
	if (ret != ARCHIVE_OK)
		return (ARCHIVE_FATAL);
	zip->written_bytes += sizeof(h);

	ret = write_path(l->entry, a);
	if (ret <= ARCHIVE_OK)
		return (ARCHIVE_FATAL);
	zip->written_bytes += ret;

	ret = __archive_write_output(a, &e, sizeof(e));
	if (ret != ARCHIVE_OK)
		return (ARCHIVE_FATAL);
	zip->written_bytes += sizeof(e);

	if (ret2 != ARCHIVE_OK)
		return (ret2);
	return (ARCHIVE_OK);
}