コード例 #1
0
ファイル: primary_transform.hpp プロジェクト: Albermg7/boost
unsigned find_sort_syntax(const traits* pt, charT* delim)
{
   //
   // compare 'a' with 'A' to see how similar they are,
   // should really use a-accute but we can't portably do that,
   //
   typedef typename traits::string_type string_type;
   typedef typename traits::char_type char_type;

   // Suppress incorrect warning for MSVC
   (void)pt;

   char_type a[2] = {'a', '\0', };
   string_type sa(pt->transform(a, a+1));
   if(sa == a)
   {
      *delim = 0;
      return sort_C;
   }
   char_type A[2] = { 'A', '\0', };
   string_type sA(pt->transform(A, A+1));
   char_type c[2] = { ';', '\0', };
   string_type sc(pt->transform(c, c+1));

   int pos = 0;
   while((pos <= static_cast<int>(sa.size())) && (pos <= static_cast<int>(sA.size())) && (sa[pos] == sA[pos])) ++pos;
   --pos;
   if(pos < 0)
   {
      *delim = 0;
      return sort_unknown;
   }
   //
   // at this point sa[pos] is either the end of a fixed width field
   // or the character that acts as a delimiter:
   //
   charT maybe_delim = sa[pos];
   if((pos != 0) && (count_chars(sa, maybe_delim) == count_chars(sA, maybe_delim)) && (count_chars(sa, maybe_delim) == count_chars(sc, maybe_delim)))
   {
      *delim = maybe_delim;
      return sort_delim;
   }
   //
   // OK doen't look like a delimiter, try for fixed width field:
   //
   if((sa.size() == sA.size()) && (sa.size() == sc.size()))
   {
      // note assumes that the fixed width field is less than
      // (numeric_limits<charT>::max)(), should be true for all types
      // I can't imagine 127 character fields...
      *delim = static_cast<charT>(++pos);
      return sort_fixed;
   }
   //
   // don't know what it is:
   //
   *delim = 0;
   return sort_unknown;
}
コード例 #2
0
ファイル: room_reset.c プロジェクト: KaSt/nereamud
//
// try performing a mobile load, based on the reset data we have
bool try_reset_load_mobile(RESET_DATA *reset, void *initiator, 
			   int initiator_type, const char *locale) {
  const char *fullkey = get_fullkey_relative(resetGetArg(reset), locale);
  PROTO_DATA   *proto = worldGetType(gameworld, "mproto", fullkey);
  // if there's no prototype, break out
  if(proto == NULL || protoIsAbstract(proto))
    return FALSE;

  // see if we're already at our max
  if(resetGetMax(reset) != 0 && 
     count_chars(NULL, mobile_list, NULL, fullkey, FALSE) >= resetGetMax(reset))
    return FALSE;
  if(initiator_type == INITIATOR_ROOM && resetGetRoomMax(reset) != 0 &&
     (count_chars(NULL, roomGetCharacters(initiator), NULL, fullkey,
		  FALSE) >= resetGetRoomMax(reset)))
    return FALSE;

  CHAR_DATA *mob = protoMobRun(proto);
  if(mob == NULL)
    return FALSE;

  // to the room
  if(initiator_type == INITIATOR_ROOM)
    char_to_room(mob, initiator);
  // to a seat
  else if(initiator_type == INITIATOR_ON_OBJ) {
    if(!objIsType(initiator, "furniture") || objGetRoom(initiator)==NULL) {
      extract_mobile(mob);
      return FALSE;
    }
    char_to_room(mob, objGetRoom(initiator));
    char_to_furniture(mob, initiator);
    charSetPos(mob, POS_SITTING);
  }
  // after an object
  else if(initiator_type == INITIATOR_THEN_OBJ) {
    if(objGetRoom(initiator) == NULL) {
      extract_mobile(mob);
      return FALSE;
    }
    char_to_room(mob, objGetRoom(initiator));
  }
  // after another mob
  else if(initiator_type == INITIATOR_THEN_MOB)
    char_to_room(mob, charGetRoom(initiator));
  // we shouldn't get this far
  else {
    extract_mobile(mob);
    return FALSE;
  }

  // now, run all of our followup stuff
  resetRunOn(reset->on,   mob, INITIATOR_ON_MOB,   locale);
  resetRunOn(reset->in,   mob, INITIATOR_IN_MOB,   locale);
  resetRunOn(reset->then, mob, INITIATOR_THEN_MOB, locale);

  return TRUE;
}
コード例 #3
0
ファイル: charcount-test.c プロジェクト: HackLinux/misc-tests
int main(void)
{
	unsigned long count = count_chars(string + 14, 'o');
	if (count != 3)
		return count + 1;
	return 0;
}
コード例 #4
0
ファイル: E9_match_chars.c プロジェクト: Mugurell/Learning
int main(void)
{
    char string1[100] = { "" };
    char string2[100] = { "" };
    int buffer;

    puts("Say something nice, please:");
    fgets(string1, 100, stdin);
    puts("Once more please (pref other saying):");
    fgets(string2, 100, stdin);
    puts("Now I'm gonna compare your 2 strings");
    puts("  and search for matching characters");

    for(int x = 0; x<3; x++) {
    	printf("\t...");
    	sleep(1);
    }
   
    printf("\n\n\t");

    buffer = count_chars(string1, string2);
    if (buffer == 0)
        puts("Sorry to dissapoint, but found no matches :-(\n");
    else
        printf("There are %d matches !!!\n\n", buffer);

    return 0;
}
コード例 #5
0
static int parse_identifier(lcc_connection_t *c, const char *value,
                            lcc_identifier_t *ident) {
    char hostname[1024];
    char ident_str[1024] = "";
    int n_slashes;

    int status;

    n_slashes = count_chars(value, '/');
    if (n_slashes == 1) {
        /* The user has omitted the hostname part of the identifier
         * (there is only one '/' in the identifier)
         * Let's add the local hostname */
        if (gethostname(hostname, sizeof(hostname)) != 0) {
            fprintf(stderr, "ERROR: Failed to get local hostname: %s",
                    strerror(errno));
            return (-1);
        }
        hostname[sizeof(hostname) - 1] = '\0';

        snprintf(ident_str, sizeof(ident_str), "%s/%s", hostname, value);
        ident_str[sizeof(ident_str) - 1] = '\0';
    } else {
        strncpy(ident_str, value, sizeof(ident_str));
        ident_str[sizeof(ident_str) - 1] = '\0';
    }

    status = lcc_string_to_identifier(c, ident, ident_str);
    if (status != 0) {
        fprintf(stderr, "ERROR: Failed to parse identifier ``%s'': %s.\n",
                ident_str, lcc_strerror(c));
        return (-1);
    }
    return (0);
} /* parse_identifier */
コード例 #6
0
ファイル: CSA.cpp プロジェクト: anuragkh/ds-lib
CSA::TCodeEntry * CSA::node::makecodetable(uchar *text, ulong n)
{
    TCodeEntry *result = new TCodeEntry[ 256 ];
    
    count_chars( text, n, result );
    std::priority_queue< node, std::vector< node >, std::greater<node> > q;
//
// First I push all the leaf nodes into the queue
//
    for ( unsigned int i = 0 ; i < 256 ; i++ )
        if ( result[ i ].count )
            q.push(node( i, result[ i ].count ) );
//
// This loop removes the two smallest nodes from the
// queue.  It creates a new internal node that has
// those two nodes as children. The new internal node
// is then inserted into the priority queue.  When there
// is only one node in the priority queue, the tree
// is complete.
//

    while ( q.size() > 1 ) {
        node *child0 = new node( q.top() );
        q.pop();
        node *child1 = new node( q.top() );
        q.pop();
        q.push( node( child0, child1 ) );
    }
//
// Now I compute and return the codetable
//
    q.top().maketable(0u,0u, result);
    q.pop();
    return result;
}
コード例 #7
0
ファイル: fswatch.c プロジェクト: kallsey/fswatch-1
// write out some info when there's any change in watched files
void callback( 
    ConstFSEventStreamRef streamRef, 
    void *clientCallBackInfo, 
    size_t numEvents, 
    void *eventPaths, 
    const FSEventStreamEventFlags eventFlags[], 
    const FSEventStreamEventId eventIds[]) 
{ 
  pid_t pid;
  int   status;

  for (int i=0; i<numEvents; ++i) {
	const char* path = ((char **)eventPaths)[i];
	int extra = count_chars(path, ' ');
	if (extra) { // produce escaped spaces in the paths
		char * z = malloc(strlen(path)+1+extra);
		int cur = 0, zcur = 0;
		while (*path) {
			if (*path == ' ')
				z[zcur++] = '\\';
			z[zcur++] = path[cur++];
		}
		printf("%x %s, ", eventFlags[i], z);
	} else {
		printf("%x %s, ", eventFlags[i], path);
	}
  }
  printf("\n");
  fflush(stdout);
} 
コード例 #8
0
ファイル: config.c プロジェクト: inteos/WBSAirback
/*
 * Returns:
 *  # of 'type' tokens in 'str'.
 */
static unsigned _count_tokens(const char *str, unsigned len, int type)
{
	char c;

	c = _token_type_to_char(type);

	return count_chars(str, len, c);
}
コード例 #9
0
ファイル: character_count.c プロジェクト: kunwarshivam/CSE323
void make_frames(int num_words){
	int i=0;
	printf("\nThe Transmitted Data is:\n\t");
	
for(;i<num_words;i++)
		printf("%d%s",(count_chars(i)+1),input[i]);

	printf("\n\n");
}
コード例 #10
0
ファイル: 3.c プロジェクト: eyalav/ece759
int main (int argc, char *argv[]) {
if (argc < 2) { 
	printf("Usage: %s \"Input String\"\n", argv[0]);
	exit(1);
}
else {
	printf("String length = %d\n", count_chars(argc, argv));
	return 0;
}
}
コード例 #11
0
ファイル: glsltexteditor.cpp プロジェクト: BtbN/crimson-core
void GLSLTextEditor::on_document_contentChanged(int position, int charsRemoved, int charsAdded)
{
	if (charsAdded == 1)
		{
			QTextDocument* doc = document ();
			QString text = doc->toPlainText();
      if (text.length () <= position)
        {
          return;
        }
			if (text.at(position) == '\n')
				{
          unsigned openBraces = count_chars(text, "{", position) - count_chars(text, "}", position);
					if (!openBraces)
						{
							return;
						}

					QString add;
					for (unsigned i=0; i<openBraces; i++)
						{
							add.append("  ");
						}
					blockSignals(true);
					insertPlainText(add);
					blockSignals(false);
				}
			else if (text.at(position) == '}')
				{
					if (text.at(position-1) == ' ' && text.at(position-2) == ' ')
						{
							QTextCursor cursor = textCursor();
							cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1);
							cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, 2);
							cursor.insertText("");
							cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
						}
				}
		}

	fflush(stdout);
}
コード例 #12
0
ファイル: lvm-string.c プロジェクト: ErisBlastar/osfree
/*
 * <vg>-<lv>-<layer> or if !layer just <vg>-<lv>.
 */
char *build_dm_name(struct dm_pool *mem, const char *vgname,
		    const char *lvname, const char *layer)
{
	size_t len = 1;
	int hyphens = 1;
	char *r, *out;

	count_chars(vgname, &len, &hyphens, '-');
	count_chars(lvname, &len, &hyphens, '-');

	if (layer && *layer) {
		count_chars(layer, &len, &hyphens, '-');
		hyphens++;
	}

	len += hyphens;

	if (!(r = dm_pool_alloc(mem, len))) {
		log_error("build_dm_name: Allocation failed for %" PRIsize_t
			  " for %s %s %s.", len, vgname, lvname, layer);
		return NULL;
	}

	out = r;
	_quote_hyphens(&out, vgname);
	*out++ = '-';
	_quote_hyphens(&out, lvname);

	if (layer && *layer) {
		/* No hyphen if the layer begins with _ e.g. _mlog */
		if (*layer != '_')
			*out++ = '-';
		_quote_hyphens(&out, layer);
	}
	*out = '\0';

	return r;
}
コード例 #13
0
ファイル: encoding.c プロジェクト: SumiTomohiko/Yog
YogVal
YogEncoding_conv_to_yog(YogEnv* env, YogHandle* self, const char* begin, const char* end)
{
    uint_t chars_num = count_chars(env, self, begin, end);
    YogVal s = YogString_of_size(env, chars_num);
    uint_t i;
    const char* pc = begin;
    for (i = 0; i < chars_num; i++) {
        YogChar c = HDL_AS(YogEncoding, self)->conv_char_to_yog(env, self, pc);
        STRING_CHARS(s)[i] = c;
        pc += HDL_AS(YogEncoding, self)->get_char_bytes(env, self, pc);
    }
    STRING_SIZE(s) = chars_num;

    return s;
}
コード例 #14
0
TCodeEntry *makecodetable(uchar *text, ulong n)
{
    TCodeEntry *result = new TCodeEntry[ size_uchar ];
    
    count_chars( text, n, result );
/*    ulong count=0;
    for (int i=0;i<256; i++) {
       count += result[i].count;
       if (result[i].count>0)
          printf("%c,%d: %d\n",i , i,result[i].count);
    }
    printf("count=%d\n",count);*/
    priority_queue< node, vector< node >, greater<node> > q;
//
// First I push all the leaf nodes into the queue
//
    for ( ulong i = 0 ; i < size_uchar ; i++ )
        if ( result[ i ].count )
            q.push(node( i, result[ i ].count ) );
//
// This loop removes the two smallest nodes from the
// queue.  It creates a new internal node that has
// those two nodes as children. The new internal node
// is then inserted into the priority queue.  When there
// is only one node in the priority queue, the tree
// is complete.
//

    while ( q.size() > 1 ) {
        node *child0 = new node( q.top() );
        q.pop();
        node *child1 = new node( q.top() );
        q.pop();
        q.push( node( child0, child1 ) );
    }
//
// Now I compute and return the codetable
//
    //cout << "Char  Symbol   Code" << endl;
    //q.top().traverse();
    q.top().maketable(0u,0u, result);
    q.top().deleteme();
    q.pop();
    return result;
}
コード例 #15
0
int main()
{
  std::vector<std::string> words;

  std::string word;
  std::string line;
  std::getline(std::cin,line);
  std::istringstream iss(line);
  while(iss >> word)
    {
      words.push_back(word);
    }

  count_chars(words);
  std::cout << "longest: " << longest_string(words) << '\n';
  std::cout << "shortest: " << shortest_string(words) << '\n';
  std::cout << "lexico_first: " << lexico_first(words) << '\n';
  std::cout << "lexico_last: " << lexico_last(words) << '\n';
  std::cout << "finished \n";
  return 0;
}
コード例 #16
0
ファイル: sharesec.c プロジェクト: jameshilliard/WECB-BH-GPL
static SEC_DESC* parse_acl_string(TALLOC_CTX *mem_ctx, const char *szACL, size_t *sd_size )
{
	SEC_DESC *sd = NULL;
	SEC_ACE *ace;
	SEC_ACL *acl;
	int num_ace;
	const char *pacl;
	int i;
	
	if ( !szACL )
		return NULL;

	pacl = szACL;
	num_ace = count_chars( pacl, ',' ) + 1;
	
	if ( !(ace = TALLOC_ZERO_ARRAY( mem_ctx, SEC_ACE, num_ace )) ) 
		return NULL;
	
	for ( i=0; i<num_ace; i++ ) {
		char *end_acl = strchr_m( pacl, ',' );
		fstring acl_string;

		strncpy( acl_string, pacl, MIN( PTR_DIFF( end_acl, pacl ), sizeof(fstring)-1) );
		acl_string[MIN( PTR_DIFF( end_acl, pacl ), sizeof(fstring)-1)] = '\0';
		
		if ( !parse_ace( &ace[i], acl_string ) )
			return NULL;

		pacl = end_acl;
		pacl++;
	}
	
	if ( !(acl = make_sec_acl( mem_ctx, NT4_ACL_REVISION, num_ace, ace )) )
		return NULL;
		
	sd = make_sec_desc( mem_ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, 
		NULL, NULL, NULL, acl, sd_size);

	return sd;
}
コード例 #17
0
int validate_opts(void)
{
        size_t i;
        int ret = 0;

        /* classification */
        if (opt_class == NULL) {
                fprintf(stderr, "Error: Classification required. See --help.\n");
                return ret;

        }
        i = strlen(opt_class);

        if ((i == 0) || (i > 120)) {
                fprintf(stderr, "Error: Valid size for classification "
                        "is 1-120 chars\n");
                return ret;
        }

        if (!g_str_is_ascii(opt_class)) {
                fprintf(stderr, "Error: Non-ascii characters detected "
                        "in classification - aborting\n");
                return ret;
        }

        if (count_chars(opt_class, '/') != 2) {
                fprintf(stderr, "Error: Classification needs to be in "
                        "most/to/least specific format, 2 \'/\' required.\n");
                return ret;
        }

        /* Severity */
        if ((severity) < 1 || (severity > 4)) {
                fprintf(stderr, "Error: Valid range for severity is 1-4\n");
                return ret;
        }

        return 1;
}
コード例 #18
0
ファイル: sudoku.c プロジェクト: bogardt/sudoku-resolver
int	main(int ac, char **av)
{
  int	i;

  i = 0;
  if (ac != 10 || count_chars(av) == 0)
    fprintf(stderr, "%s\n", usage);
  else
    {
      while (++i < 10)
	{
	  if (!check_chars(av[i]))
	    {
	      fprintf(stderr, "%s\n", "sudoku need 10 row");
	      return (0);
	    }
	}
      if (resolve(av, 0))
	display_tab(av);
      else
	fprintf(stderr, "%s\n", "resolve failed");
    }
  return (0);
}
コード例 #19
0
/*
  parse a binding string into a dcerpc_binding structure
*/
_PUBLIC_ NTSTATUS dcerpc_parse_binding(TALLOC_CTX *mem_ctx, const char *s, struct dcerpc_binding **b_out)
{
	struct dcerpc_binding *b;
	char *options;
	char *p;
	int i, j, comma_count;

	b = talloc_zero(mem_ctx, struct dcerpc_binding);
	if (!b) {
		return NT_STATUS_NO_MEMORY;
	}

	p = strchr(s, '@');

	if (p && PTR_DIFF(p, s) == 36) { /* 36 is the length of a UUID */
		NTSTATUS status;
		DATA_BLOB blob = data_blob(s, 36);
		status = GUID_from_data_blob(&blob, &b->object.uuid);

		if (NT_STATUS_IS_ERR(status)) {
			DEBUG(0, ("Failed parsing UUID\n"));
			return status;
		}

		s = p + 1;
	} else {
		ZERO_STRUCT(b->object);
	}

	b->object.if_version = 0;

	p = strchr(s, ':');

	if (p == NULL) {
		b->transport = NCA_UNKNOWN;
	} else {
		char *type = talloc_strndup(mem_ctx, s, PTR_DIFF(p, s));
		if (!type) {
			return NT_STATUS_NO_MEMORY;
		}

		for (i=0;i<ARRAY_SIZE(transports);i++) {
			if (strcasecmp(type, transports[i].name) == 0) {
				b->transport = transports[i].transport;
				break;
			}
		}

		if (i==ARRAY_SIZE(transports)) {
			DEBUG(0,("Unknown dcerpc transport '%s'\n", type));
			return NT_STATUS_INVALID_PARAMETER;
		}

		talloc_free(type);

		s = p+1;
	}

	p = strchr(s, '[');
	if (p) {
		b->host = talloc_strndup(b, s, PTR_DIFF(p, s));
		options = talloc_strdup(mem_ctx, p+1);
		if (options[strlen(options)-1] != ']') {
			return NT_STATUS_INVALID_PARAMETER;
		}
		options[strlen(options)-1] = 0;
	} else {
		b->host = talloc_strdup(b, s);
		options = NULL;
	}
	if (!b->host) {
		return NT_STATUS_NO_MEMORY;
	}

	b->target_hostname = b->host;

	b->options = NULL;
	b->flags = 0;
	b->assoc_group_id = 0;
	b->endpoint = NULL;
	b->localaddress = NULL;

	if (!options) {
		*b_out = b;
		return NT_STATUS_OK;
	}

	comma_count = count_chars(options, ',');

	b->options = talloc_array(b, const char *, comma_count+2);
	if (!b->options) {
		return NT_STATUS_NO_MEMORY;
	}

	for (i=0; (p = strchr(options, ',')); i++) {
		b->options[i] = talloc_strndup(b, options, PTR_DIFF(p, options));
		if (!b->options[i]) {
			return NT_STATUS_NO_MEMORY;
		}
		options = p+1;
	}
	b->options[i] = options;
	b->options[i+1] = NULL;

	/* some options are pre-parsed for convenience */
	for (i=0;b->options[i];i++) {
		for (j=0;j<ARRAY_SIZE(ncacn_options);j++) {
			size_t opt_len = strlen(ncacn_options[j].name);
			if (strncasecmp(ncacn_options[j].name, b->options[i], opt_len) == 0) {
				int k;
				char c = b->options[i][opt_len];

				if (ncacn_options[j].flag == DCERPC_LOCALADDRESS && c == '=') {
					b->localaddress = talloc_strdup(b, &b->options[i][opt_len+1]);
				} else if (c != 0) {
					continue;
				}

				b->flags |= ncacn_options[j].flag;
				for (k=i;b->options[k];k++) {
					b->options[k] = b->options[k+1];
				}
				i--;
				break;
			}
		}
	}

	if (b->options[0]) {
		/* Endpoint is first option */
		b->endpoint = b->options[0];
		if (strlen(b->endpoint) == 0) b->endpoint = NULL;

		for (i=0;b->options[i];i++) {
			b->options[i] = b->options[i+1];
		}
	}

	if (b->options[0] == NULL)
		b->options = NULL;

	*b_out = b;
	return NT_STATUS_OK;
}
コード例 #20
0
ファイル: 7seg.c プロジェクト: pcarrier/stuff
int seven_seg_plot(char **dest, char const *msg, char seg_char,
                   char spe_char, seven_seg_size available,
                   seven_seg_size * used)
{
    int msg_len;
    int nb_stdchar = 0, nb_spechar = 0, nb_chars = 0, nb_spaces = 0;
    int stdchar_width = 0, spechar_width = 0, space_width = 0, real_width = 0;
    int line = 0, colon_line1 = 0, colon_line2 = 0, spechar_shift = 0;
    int dest_pos = 0;
    char *current_char;
    symbol_repr_t *current_repr;

    msg_len = strlen(msg);

    count_chars(msg, msg_len, &nb_stdchar, &nb_spechar);
    nb_chars = nb_stdchar + nb_spechar;
    nb_spaces = nb_chars - 1;

    if ((available.height < MIN_HEIGHT) ||
        (available.width <
         STDCHAR_MIN_WIDTH * nb_stdchar + nb_spechar + nb_spaces))
        return ENOSPC;

    if (nb_spechar || nb_stdchar) {
        stdchar_width =
            (STD2SPE_WIDTH_RATIO * (available.width - nb_spaces)) /
            (nb_spechar + nb_stdchar * STD2SPE_WIDTH_RATIO);
        spechar_width = stdchar_width / STD2SPE_WIDTH_RATIO;
    }
    if (!spechar_width)
        spechar_width++;

    if (nb_spaces)
        space_width =
            (available.width - nb_stdchar * stdchar_width -
             nb_spechar * spechar_width) / nb_spaces;
    if (!space_width)
        space_width = 1;

    real_width =
        nb_stdchar * stdchar_width + nb_spechar * spechar_width +
        nb_spaces * space_width;

    /* Clear the zone */
    for (line = 0; line < available.height; line++)
        memset((void *) (dest[line]), CHAR_EMPTY, real_width);

    spechar_shift = (spechar_width > 1) ? spechar_width / 2 - 1 : 0;
    colon_line1 = (available.height - 1) * 2 / 5;
    colon_line2 = (available.height - 1) * 4 / 5;
    if (colon_line1 >= available.height / 2)
        colon_line1--;
    if (colon_line2 - colon_line1 < 2)
        colon_line2++;

    for (current_char = (char *) msg; current_char < msg + msg_len;
         current_char++) {
        switch (*current_char) {
        case ':':
            dest[colon_line1][dest_pos + spechar_shift] = spe_char;
            dest[colon_line2][dest_pos + spechar_shift] = spe_char;
            dest_pos += (space_width + spechar_width);
            break;
        case '.':
            dest[available.height - 1][dest_pos + spechar_shift] =
                spe_char;
            dest_pos += (space_width + spechar_width);
            break;
            /* Takes the same amount of space as a : (used for blinking clocks) */
        case ';':
            dest_pos += (space_width + spechar_width);
            break;
        default:
            if ((current_repr = find_repr(*current_char))) {
                draw_repr(dest, current_repr->repr, dest_pos,
                          available.height, stdchar_width, seg_char);
                dest_pos += (space_width + stdchar_width);
            }
            break;
        }
    }

    if (used) {
        used->height = available.height;
        used->width = real_width;
    }

    return 0;
}
コード例 #21
0
int main(int argc, char *argv[]) {

  size_t buffer_size = BUFFER_SIZE_DEFAULT;

  // Read arguments
  FILE *infile = stdin;
  int quiet = 0;
  char output = 'r';
  char read_opt = '\0';
  int i;
  for (i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-h") == 0) {
      die(USAGE);
    } else if (strcmp(argv[i], "-q") == 0) {
      quiet = 1;
    } else if (strcmp(argv[i], "-o") == 0) {
      read_opt = 'o';
    } else if (strcmp(argv[i], "-B") == 0) {
      read_opt = 'B';
    } else if (read_opt == 'o') {
      if (strcmp(argv[i], "reads") == 0) {
        output = 'r';
      } else if (strcmp(argv[i], "format") == 0) {
        output = 'f';
      } else {
        die("Invalid -o output format \"%s\"", argv[i]);
      }
      read_opt = '\0';
    } else if (read_opt == 'B') {
      if (! is_int(argv[i])) {
        die("Invalid buffer size: \"%s\"", argv[i]);
      }
      buffer_size = atoi(argv[i]);
      read_opt = '\0';
    } else if (infile == stdin) {
      infile = fopen(argv[i], "r");
      if (errno) {
        die("\"%s\"", argv[i]);
      }
    } else {
      //TODO: allow any number of input files
      die("Can only process one file argument");
    }
  }

  int get_extremes = 1;
  if (quiet && output != 'f') {
    get_extremes = 0;
  }

  /*TODO: This assumes that there will be at least as many quality scores as there are sequence
   *      bases. According to Dan, we can't make that assumption.
   *      Then what do we do to tell when the quality lines have ended?
   *      Ideas for disambiguating:
   *      1. If len(qual) >= len(seq), it's a HEADER (If we've already seen enough
   *         quality values to cover the read, the QUAL lines must be over.)
   *      2. If the line plus the observed quality values so far is longer than the
   *         read, it must be a HEADER line.
   *      3. No FASTQ format uses space characters for quality scores, according to
   *         Wikipedia. If there's a space character in the line, say it's a HEADER line?
   *      But there could still conceivably be a read with truncated quality scores,
   *      followed by a HEADER line that contains no spaces and is short enough to not
   *      exceed the read length.
   *      Conclusion: Just check how BioPython does it:
   *      http://biopython.org/DIST/docs/api/Bio.SeqIO.QualityIO-pysrc.html
   *      Update: BioPython just throws an error if the number of bases != num of quality scores.
   */
  /* Notes on format requirements:
   * Empty lines are allowed, and ignored. If there's an empty line where a sequence or quality line
   * is expected, it's interpreted as 0 base/quality scores.
   * This means you can have zero-length reads.
   * Multi-line sequences (more than 4 lines per read) are allowed.
   * The number of quality scores must be >= the number of sequence bases. If there are missing
   * quality scores, this will likely fail with an error, but it could possibly succeed, giving
   * incorrect results.
   */

  char *line = malloc(buffer_size);

  Extremes extremes;
  extremes.max = 0;
  extremes.min = 256;
  long num_reads = 0;
  long seq_len = 0;
  long qual_len = 0;
  State state = HEADER;
  // fgets() reads a line at a time.
  char *result = fgets(line, buffer_size, infile);
  long line_num = 0;
  while (result != NULL) {
    line_num++;
    if (state == HEADER) {
      // Allow empty lines before the header.
      if (! line_is_empty(line)) {
        if (line[0] != '@') {
          die("Line %ld looked like a header line but does not start with \"@\".", line_num);
        }
        num_reads++;
        seq_len = 0;
        // Assume only 1 header line.
        state = SEQ;
      }
    } else if (state == SEQ) {
      if (line[0] == '+') {
        qual_len = 0;
        // End of sequence line comes when we see a line starting with "+".
        state = PLUS;
      } else {
        seq_len += count_chars(line, buffer_size);
      }
    } else if (state == PLUS || state == QUAL) {
      // If the state is PLUS, we already saw the "+" line on the last loop.
      // Assume there's only 1 "+" line, and assume we're now on a quality scores line.
      if (state == QUAL && line[0] == '@') {
        // If we're past the "first" quality scores line and we see one that starts with a "@",
        // that's very suspicious. Allow it, but raise a warning.
        fprintf(stderr, "Warning: Looking for more quality scores on line %ld but it starts with "
                        "\"@\".\nThis might be a header line and there were fewer quality scores "
                        "than bases.\n", line_num);
      }
      state = QUAL;
      if (get_extremes) {
        qual_len += count_chars_and_extremes(line, buffer_size, &extremes);
      } else {
        qual_len += count_chars(line, buffer_size);
      }
      if (qual_len >= seq_len) {
        // End of quality line comes once we've seen enough quality scores to match the sequence line.
        state = HEADER;
        if (qual_len > seq_len) {
          fprintf(stderr, "Warning on line %ld: Counted more quality scores than bases.\n", line_num);
        }
      }
    }
    result = fgets(line, buffer_size, infile);
  }

  char format_guess = '?';
  if (get_extremes) {
    format_guess = guess_quality_format(extremes, num_reads);
  }

  if (!quiet) {
    fprintf(stderr, "Quality score ascii range: %d (%c) to %d (%c)\n",
            extremes.min, (char)extremes.min, extremes.max, (char)extremes.max);
    switch (format_guess) {
      case 'S':
        fprintf(stderr, "Format: Very likely Sanger (offset 33).\n");
        break;
      case 'X':
        fprintf(stderr, "Format: Very likely Solexa (offset 64).\n");
        break;
      case 's':
        fprintf(stderr, "Format: Maybe Sanger? (offset 33)\n");
        break;
      case 'x':
        fprintf(stderr, "Format: Maybe Solexa? (offset 64)\n");
        break;
      case '?':
        fprintf(stderr, "Format: Unknown\n");
    }
  }

  if (output == 'r') {
    printf("%ld\n", num_reads);
  } else if (output == 'f') {
    switch (format_guess) {
      case 'S':
      case 's':
        printf("sanger\n");
        break;
      case 'X':
      case 'x':
        printf("solexa\n");
        break;
      default:
        printf("?\n");
    }
  }

  fclose(infile);
  return 0;
}
コード例 #22
0
ファイル: rpctorture.c プロジェクト: livebox/livebox2
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
	char *pname = argv[0];
	int opt;
	extern FILE *dbf;
	extern char *optarg;
	extern int optind;
	static pstring servicesf = CONFIGFILE;
	pstring term_code;
	BOOL got_pass = False;
	char *cmd_str="";
	enum client_action cli_action = CLIENT_NONE;
	int nprocs = 1;
	int numops = 100;
	pstring logfile;

	struct client_info cli_info;

	out_hnd = stdout;

	rpcclient_init();

#ifdef KANJI
	pstrcpy(term_code, KANJI);
#else /* KANJI */
	*term_code = 0;
#endif /* KANJI */

	if (!lp_load(servicesf,True, False, False))
	{
		fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
	}

	codepage_initialise(lp_client_code_page());

	DEBUGLEVEL = 0;

	cli_info.put_total_size = 0;
	cli_info.put_total_time_ms = 0;
	cli_info.get_total_size = 0;
	cli_info.get_total_time_ms = 0;

	cli_info.dir_total = 0;
	cli_info.newer_than = 0;
	cli_info.archive_level = 0;
	cli_info.print_mode = 1;

	cli_info.translation = False;
	cli_info.recurse_dir = False;
	cli_info.lowercase = False;
	cli_info.prompt = True;
	cli_info.abort_mget = True;

	cli_info.dest_ip.s_addr = 0;
	cli_info.name_type = 0x20;

	pstrcpy(cli_info.cur_dir , "\\");
	pstrcpy(cli_info.file_sel, "");
	pstrcpy(cli_info.base_dir, "");
	pstrcpy(smb_cli->domain, "");
	pstrcpy(smb_cli->user_name, "");
	pstrcpy(cli_info.myhostname, "");
	pstrcpy(cli_info.dest_host, "");

	pstrcpy(cli_info.svc_type, "A:");
	pstrcpy(cli_info.share, "");
	pstrcpy(cli_info.service, "");

	ZERO_STRUCT(cli_info.dom.level3_sid);
	pstrcpy(cli_info.dom.level3_dom, "");
	ZERO_STRUCT(cli_info.dom.level5_sid);
	pstrcpy(cli_info.dom.level5_dom, "");

	smb_cli->nt_pipe_fnum   = 0xffff;

	setup_logging(pname, True);

	TimeInit();
	charset_initialise();

	if (!get_myname(global_myname))
	{
		fprintf(stderr, "Failed to get my hostname.\n");
	}

	password[0] = 0;

	if (argc < 2)
	{
		usage(pname);
		exit(1);
	}

	if (*argv[1] != '-')
	{
		pstrcpy(cli_info.service, argv[1]);  
		/* Convert any '/' characters in the service name to '\' characters */
		string_replace( cli_info.service, '/','\\');
		argc--;
		argv++;

		DEBUG(1,("service: %s\n", cli_info.service));

		if (count_chars(cli_info.service,'\\') < 3)
		{
			usage(pname);
			printf("\n%s: Not enough '\\' characters in service\n", cli_info.service);
			exit(1);
		}

		/*
		if (count_chars(cli_info.service,'\\') > 3)
		{
			usage(pname);
			printf("\n%s: Too many '\\' characters in service\n", cli_info.service);
			exit(1);
		}
		*/

		if (argc > 1 && (*argv[1] != '-'))
		{
			got_pass = True;
			pstrcpy(password,argv[1]);  
			memset(argv[1],'X',strlen(argv[1]));
			argc--;
			argv++;
		}

		cli_action = CLIENT_SVC;
	}

	while ((opt = getopt(argc, argv,"s:O:M:S:i:N:o:n:d:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
	{
		switch (opt)
		{
			case 'm':
			{
				/* FIXME ... max_protocol seems to be funny here */

				int max_protocol = 0;
				max_protocol = interpret_protocol(optarg,max_protocol);
				fprintf(stderr, "max protocol not currently supported\n");
				break;
			}

			case 'O':
			{
				pstrcpy(user_socket_options,optarg);
				break;	
			}

			case 'S':
			{
				pstrcpy(cli_info.dest_host,optarg);
				strupper(cli_info.dest_host);
				cli_action = CLIENT_IPC;
				break;
			}

			case 'i':
			{
				pstrcpy(scope, optarg);
				break;
			}

			case 'U':
			{
				char *lp;
				pstrcpy(smb_cli->user_name,optarg);
				if ((lp=strchr(smb_cli->user_name,'%')))
				{
					*lp = 0;
					pstrcpy(password,lp+1);
					got_pass = True;
					memset(strchr(optarg,'%')+1,'X',strlen(password));
				}
				break;
			}

			case 'W':
			{
				pstrcpy(smb_cli->domain,optarg);
				break;
			}

			case 'E':
			{
				dbf = stderr;
				break;
			}

			case 'I':
			{
				cli_info.dest_ip = *interpret_addr2(optarg);
				if (zero_ip(cli_info.dest_ip))
				{
					exit(1);
				}
				break;
			}

			case 'N':
			{
				nprocs = atoi(optarg);
				break;
			}

			case 'o':
			{
				numops = atoi(optarg);
				break;
			}

			case 'n':
			{
				fstrcpy(global_myname, optarg);
				break;
			}

			case 'd':
			{
				if (*optarg == 'A')
					DEBUGLEVEL = 10000;
				else
					DEBUGLEVEL = atoi(optarg);
				break;
			}

			case 'l':
			{
				slprintf(logfile, sizeof(logfile)-1,
				         "%s.client",optarg);
				lp_set_logfile(logfile);
				break;
			}

			case 'c':
			{
				cmd_str = optarg;
				got_pass = True;
				break;
			}

			case 'h':
			{
				usage(pname);
				exit(0);
				break;
			}

			case 's':
			{
				pstrcpy(servicesf, optarg);
				break;
			}

			case 't':
			{
				pstrcpy(term_code, optarg);
				break;
			}

			default:
			{
				usage(pname);
				exit(1);
				break;
			}
		}
	}

	if (cli_action == CLIENT_NONE)
	{
		usage(pname);
		exit(1);
	}

	strupper(global_myname);
	fstrcpy(cli_info.myhostname, global_myname);

	DEBUG(3,("%s client started (version %s)\n",timestring(False),VERSION));

	if (*smb_cli->domain == 0)
	{
		pstrcpy(smb_cli->domain,lp_workgroup());
	}
	strupper(smb_cli->domain);

	load_interfaces();

	if (cli_action == CLIENT_IPC)
	{
		pstrcpy(cli_info.share, "IPC$");
		pstrcpy(cli_info.svc_type, "IPC");
	}

	fstrcpy(cli_info.mach_acct, cli_info.myhostname);
	strupper(cli_info.mach_acct);
	fstrcat(cli_info.mach_acct, "$");

	/* set the password cache info */
	if (got_pass)
	{
		if (password[0] == 0)
		{
			pwd_set_nullpwd(&(smb_cli->pwd));
		}
		else
		{
			pwd_make_lm_nt_16(&(smb_cli->pwd), password); /* generate 16 byte hashes */
		}
	}
	else 
	{
		char *pwd = getpass("Enter Password:");
		safe_strcpy(password, pwd, sizeof(password));
		pwd_make_lm_nt_16(&(smb_cli->pwd), password); /* generate 16 byte hashes */
	}

	create_procs(nprocs, numops, &cli_info, smb_cli, run_enums_test);

	if (password[0] != 0)
	{
		create_procs(nprocs, numops, &cli_info, smb_cli, run_ntlogin_test);
	}

	fflush(out_hnd);

	return(0);
}
コード例 #23
0
ファイル: xpath_locator.c プロジェクト: JATS4R/xml.js
int
main(int argc, char **argv) {
#else
int
xpath_locator(int argc, char **argv) {
#endif

    if (argc < 2) {
        fprintf(stderr, "Need to specify an input filename.\n"
            "Usage: xpath_locator file.xml xpath1 xpath2 ...\n");
        exit(1);
    }
    char *xml_filename = argv[1];

    num_xpaths = argc - 2;

    xpath_finders = (XPathFinder *) mmalloc(num_xpaths * sizeof(XPathFinder));

    for (int xpath_num = 0; xpath_num < num_xpaths; ++xpath_num) {
        xmlChar *xpath_expr = (xmlChar *) argv[xpath_num + 2];
        XPathFinder *xpath_finder = &xpath_finders[xpath_num];
        xpath_finder->original = new_string(xpath_expr);
        xpath_finder->current_level = 0;
        xpath_finder->line_number = 0;
        xpath_finder->column_number = 0;


        escape_uri_slashes(xpath_expr, TRUE);
        int num_segs = xpath_finder->num_segs = count_chars(xpath_expr, '/');

        XPathSegFinder *seg_finders = 
            (XPathSegFinder *) mmalloc(num_segs * sizeof(XPathSegFinder));
        xpath_finder->seg_finders = seg_finders;

        /* Extract each XPath segment */
        xmlChar *seg = xstrtok(xpath_expr, "/");
        int seg_num = 0;
        while (seg != NULL) {
            XPathSegFinder *seg_finder = &seg_finders[seg_num];
            seg_finder->count = 0;

            escape_uri_slashes(seg, FALSE);
            seg_finder->original = new_string(seg);

            // Get the element local name
            xmlChar *lns = starts_with(seg, (const xmlChar *) "*:") ? seg + 2 : seg;
            const xmlChar *bracket = xstrchr(seg, '[');
            if (!bracket) 
                xpath_error(xpath_num, xpath_finder, seg_num, "No bracket found");
            int local_name_len = bracket - lns;
            xmlChar *local_name = seg_finder->local_name = 
                new_string_n(lns, local_name_len);

            if (starts_with(bracket + 1, (const xmlChar *) "namespace-uri()=")) {
                const xmlChar *ns_start = bracket + 18;
                const xmlChar *ns_end = xstrchr(ns_start, '\'');
                if (!ns_end) 
                    xpath_error(xpath_num, xpath_finder, seg_num, 
                        "No end to the namespace URI");
                seg_finder->namespace_uri = new_string_n(ns_start, ns_end - ns_start);
                bracket = xstrchr(ns_end, '[');
                if (!bracket) 
                    xpath_error(xpath_num, xpath_finder, seg_num, "No position found");
            }
            else {
                seg_finder->namespace_uri = NULL;
            }

            const xmlChar *pos_start = bracket + 1;
            const xmlChar *pos_end = xstrchr(pos_start, ']');
            if (!pos_end) 
                xpath_error(xpath_num, xpath_finder, seg_num, "No closing bracket found");
            size_t pos_str_len = pos_end - pos_start;
            char pos_str[10];
            strncpy(pos_str, (const char *) pos_start, pos_str_len);
            pos_str[pos_str_len] = 0;
            seg_finder->position = strtol(pos_str, NULL, 10);
            if (seg_finder->position <= 0) 
                xpath_error(xpath_num, xpath_finder, seg_num, "Bad position argument");

            seg = xstrtok(NULL, "/");
            seg_num++;
        }
    }


    // Initialize default handler structure for SAX 2
    xmlSAXVersion(handlers, 2);
    handlers->startElementNs = my_startElementNs;
    handlers->endElementNs = my_endElementNs;

    parser_level = 0;  // [c] parser_level is safe
    int res = xmlSAXUserParseFile(handlers, NULL, xml_filename);

    // Output the results
    for (int xpath_num = 0; xpath_num < num_xpaths; ++xpath_num) {
        XPathFinder *xpath_finder = &xpath_finders[xpath_num];
        printf("%d:%d\n", xpath_finder->line_number, xpath_finder->column_number);
    }    


    for (int xpath_num = 0; xpath_num < num_xpaths; ++xpath_num) {
        XPathFinder *xpath_finder = &xpath_finders[xpath_num];
        int num_segs = xpath_finder->num_segs;
        XPathSegFinder *seg_finders = xpath_finder->seg_finders;
        for (int seg_num = 0; seg_num < num_segs; ++seg_num) {
            XPathSegFinder *seg_finder = &seg_finders[seg_num];
            ffree(seg_finder->original);
            ffree(seg_finder->local_name);
            ffree(seg_finder->namespace_uri);
        }

        ffree(xpath_finder->seg_finders);
        ffree(xpath_finder->original);
    }
    ffree(xpath_finders);

    return 0;
}
コード例 #24
0
ファイル: dcerpc_util.c プロジェクト: hanwoody/winexe
/*
  parse a binding string into a dcerpc_binding structure
*/
NTSTATUS dcerpc_parse_binding(TALLOC_CTX *mem_ctx, const char *s, struct dcerpc_binding **b_out)
{
	struct dcerpc_binding *b;
	char *options, *type;
	char *p;
	int i, j, comma_count;

	b = talloc(mem_ctx, struct dcerpc_binding);
	if (!b) {
		return NT_STATUS_NO_MEMORY;
	}

	p = strchr(s, '@');

	if (p && PTR_DIFF(p, s) == 36) { /* 36 is the length of a UUID */
		NTSTATUS status;

		status = GUID_from_string(s, &b->object.uuid);

		if (NT_STATUS_IS_ERR(status)) {
			DEBUG(0, ("Failed parsing UUID\n"));
			return status;
		}

		s = p + 1;
	} else {
		ZERO_STRUCT(b->object);
	}

	b->object.if_version = 0;

	p = strchr(s, ':');
	if (!p) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	type = talloc_strndup(mem_ctx, s, PTR_DIFF(p, s));
	if (!type) {
		return NT_STATUS_NO_MEMORY;
	}

	for (i=0;i<ARRAY_SIZE(transports);i++) {
		if (strcasecmp(type, transports[i].name) == 0) {
			b->transport = transports[i].transport;
			break;
		}
	}
	if (i==ARRAY_SIZE(transports)) {
		DEBUG(0,("Unknown dcerpc transport '%s'\n", type));
		return NT_STATUS_INVALID_PARAMETER;
	}
	
	s = p+1;

	p = strchr(s, '[');
	if (p) {
		b->host = talloc_strndup(b, s, PTR_DIFF(p, s));
		options = talloc_strdup(mem_ctx, p+1);
		if (options[strlen(options)-1] != ']') {
			return NT_STATUS_INVALID_PARAMETER;
		}
		options[strlen(options)-1] = 0;
	} else {
		b->host = talloc_strdup(b, s);
		options = NULL;
	}
	if (!b->host) {
		return NT_STATUS_NO_MEMORY;
	}

	b->target_hostname = b->host;

	b->options = NULL;
	b->flags = 0;
	b->endpoint = NULL;

	if (!options) {
		*b_out = b;
		return NT_STATUS_OK;
	}

	comma_count = count_chars(options, ',');

	b->options = talloc_array(b, const char *, comma_count+2);
	if (!b->options) {
		return NT_STATUS_NO_MEMORY;
	}

	for (i=0; (p = strchr(options, ',')); i++) {
		b->options[i] = talloc_strndup(b, options, PTR_DIFF(p, options));
		if (!b->options[i]) {
			return NT_STATUS_NO_MEMORY;
		}
		options = p+1;
	}
	b->options[i] = options;
	b->options[i+1] = NULL;

	/* some options are pre-parsed for convenience */
	for (i=0;b->options[i];i++) {
		for (j=0;j<ARRAY_SIZE(ncacn_options);j++) {
			if (strcasecmp(ncacn_options[j].name, b->options[i]) == 0) {
				int k;
				b->flags |= ncacn_options[j].flag;
				for (k=i;b->options[k];k++) {
					b->options[k] = b->options[k+1];
				}
				i--;
				break;
			}
		}
	}

	if (b->options[0]) {
		/* Endpoint is first option */
		b->endpoint = b->options[0];
		if (strlen(b->endpoint) == 0) b->endpoint = NULL;

		for (i=0;b->options[i];i++) {
			b->options[i] = b->options[i+1];
		}
	}

	if (b->options[0] == NULL)
		b->options = NULL;
	
	*b_out = b;
	return NT_STATUS_OK;
}
コード例 #25
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
  fstring base_directory;
  char *pname = argv[0];
  int opt;
  extern FILE *dbf;
  extern char *optarg;
  extern int optind;
  pstring query_host;
  BOOL nt_domain_logon = False;
  static pstring servicesf = CONFIGFILE;
  pstring term_code;
  char *p;

#ifdef KANJI
  pstrcpy(term_code, KANJI);
#else /* KANJI */
  *term_code = 0;
#endif /* KANJI */

  *query_host = 0;
  *base_directory = 0;

  DEBUGLEVEL = 2;

  setup_logging(pname,True);

  TimeInit();
  charset_initialise();

  pid = getpid();
  uid = getuid();
  gid = getgid();
  mid = pid + 100;
  myumask = umask(0);
  umask(myumask);

  if (getenv("USER"))
  {
    pstrcpy(username,getenv("USER"));

    /* modification to support userid%passwd syntax in the USER var
       25.Aug.97, [email protected] */

    if ((p=strchr(username,'%')))
    {
      *p = 0;
      pstrcpy(password,p+1);
      got_pass = True;
      memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
    }
    strupper(username);
  }

 /* modification to support PASSWD environmental var
  25.Aug.97, [email protected] */

  if (getenv("PASSWD"))
    pstrcpy(password,getenv("PASSWD"));

  if (*username == 0 && getenv("LOGNAME"))
    {
      pstrcpy(username,getenv("LOGNAME"));
      strupper(username);
    }

  if (argc < 2)
    {
      usage(pname);
      exit(1);
    }
  
  if (*argv[1] != '-')
    {

      pstrcpy(service, argv[1]);  
      /* Convert any '/' characters in the service name to '\' characters */
      string_replace( service, '/','\\');
      argc--;
      argv++;

      if (count_chars(service,'\\') < 3)
	{
	  usage(pname);
	  printf("\n%s: Not enough '\\' characters in service\n",service);
	  exit(1);
	}

      if (argc > 1 && (*argv[1] != '-'))
	{
	  got_pass = True;
	  pstrcpy(password,argv[1]);  
	  memset(argv[1],'X',strlen(argv[1]));
	  argc--;
	  argv++;
	}
    }

  while ((opt = 
	  getopt(argc, argv,"s:B:O:M:S:i:Nn:d:Pp:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
    switch (opt)
      {
      case 'm':
	max_protocol = interpret_protocol(optarg,max_protocol);
	break;
      case 'O':
	pstrcpy(user_socket_options,optarg);
	break;	
      case 'S':
	pstrcpy(desthost,optarg);
	strupper(desthost);
	nt_domain_logon = True;
	break;
      case 'B':
	iface_set_default(NULL,optarg,NULL);
	break;
      case 'D':
	pstrcpy(base_directory,optarg);
	break;
      case 'i':
	pstrcpy(scope,optarg);
	break;
      case 'U':
	{
	  char *lp;
	pstrcpy(username,optarg);
	if ((lp=strchr(username,'%')))
	  {
	    *lp = 0;
	    pstrcpy(password,lp+1);
	    got_pass = True;
	    memset(strchr(optarg,'%')+1,'X',strlen(password));
	  }
	}
	    
	break;
      case 'W':
	pstrcpy(workgroup,optarg);
	break;
      case 'E':
	dbf = stderr;
	break;
      case 'I':
	{
	  dest_ip = *interpret_addr2(optarg);
	  if (zero_ip(dest_ip)) exit(1);
	  have_ip = True;
	}
	break;
      case 'n':
	pstrcpy(myname,optarg);
	break;
      case 'N':
	got_pass = True;
	break;
      case 'd':
	if (*optarg == 'A')
	  DEBUGLEVEL = 10000;
	else
	  DEBUGLEVEL = atoi(optarg);
	break;
      case 'l':
	slprintf(debugf,sizeof(debugf)-1,"%s.client",optarg);
	break;
      case 'p':
	port = atoi(optarg);
	break;
      case 'c':
	cmdstr = optarg;
	got_pass = True;
	break;
      case 'h':
	usage(pname);
	exit(0);
	break;
      case 's':
	pstrcpy(servicesf, optarg);
	break;
      case 't':
        pstrcpy(term_code, optarg);
	break;
      default:
	usage(pname);
	exit(1);
      }

  if (!*query_host && !*service)
    {
      usage(pname);
      exit(1);
    }


  DEBUG(3,("%s client started (version %s)\n",timestring(),VERSION));

  if(!get_myname(myhostname,NULL))
  {
    DEBUG(0,("Failed to get my hostname.\n"));
  }

  if (!lp_load(servicesf,True)) {
    fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
  }

  codepage_initialise(lp_client_code_page());

  interpret_coding_system(term_code);

  if (*workgroup == 0)
    pstrcpy(workgroup,lp_workgroup());

  load_interfaces();
  get_myname((*myname)?NULL:myname,NULL);  
  strupper(myname);

#ifdef NTDOMAIN

	if (nt_domain_logon)
	{
		int ret = 0;
		slprintf(service,sizeof(service), "\\\\%s\\IPC$",query_host);
		strupper(service);
		connect_as_ipc = True;

		DEBUG(5,("NT Domain Logon.  Service: %s\n", service));

		if (cli_open_sockets(port))
		{
			if (!cli_send_login(NULL,NULL,True,True,NULL)) return(1);

			do_nt_login(desthost, myhostname, Client, cnum);

			cli_send_logout();
			close_sockets();
		}

		return(ret);
	}
#endif 

  if (cli_open_sockets(port))
    {
      if (!process(base_directory))
	{
	  close_sockets();
	  return(1);
	}
      close_sockets();
    }
  else
    return(1);

  return(0);
}
コード例 #26
0
ファイル: rpcclient.c プロジェクト: AllardJ/Tomato
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
	BOOL interactive = True;

	int opt;
	extern FILE *dbf;
	extern char *optarg;
	extern int optind;
	static pstring servicesf = CONFIGFILE;
	pstring term_code;
	char *p;
	BOOL got_pass = False;
	char *cmd_str="";
	mode_t myumask = 0755;
	enum client_action cli_action = CLIENT_NONE;

	struct client_info cli_info;

	pstring password; /* local copy only, if one is entered */

	out_hnd = stdout;
	fstrcpy(debugf, argv[0]);

	rpcclient_init();

#ifdef KANJI
	pstrcpy(term_code, KANJI);
#else /* KANJI */
	*term_code = 0;
#endif /* KANJI */

	DEBUGLEVEL = 2;

	cli_info.put_total_size = 0;
	cli_info.put_total_time_ms = 0;
	cli_info.get_total_size = 0;
	cli_info.get_total_time_ms = 0;

	cli_info.dir_total = 0;
	cli_info.newer_than = 0;
	cli_info.archive_level = 0;
	cli_info.print_mode = 1;

	cli_info.translation = False;
	cli_info.recurse_dir = False;
	cli_info.lowercase = False;
	cli_info.prompt = True;
	cli_info.abort_mget = True;

	cli_info.dest_ip.s_addr = 0;
	cli_info.name_type = 0x20;

	pstrcpy(cli_info.cur_dir , "\\");
	pstrcpy(cli_info.file_sel, "");
	pstrcpy(cli_info.base_dir, "");
	pstrcpy(smb_cli->domain, "");
	pstrcpy(smb_cli->user_name, "");
	pstrcpy(cli_info.myhostname, "");
	pstrcpy(cli_info.dest_host, "");

	pstrcpy(cli_info.svc_type, "A:");
	pstrcpy(cli_info.share, "");
	pstrcpy(cli_info.service, "");

	ZERO_STRUCT(cli_info.dom.level3_sid);
	ZERO_STRUCT(cli_info.dom.level5_sid);
	fstrcpy(cli_info.dom.level3_dom, "");
	fstrcpy(cli_info.dom.level5_dom, "");

	smb_cli->nt_pipe_fnum   = 0xffff;

	TimeInit();
	charset_initialise();

	myumask = umask(0);
	umask(myumask);

	if (!get_myname(global_myname))
	{
		fprintf(stderr, "Failed to get my hostname.\n");
	}

	if (getenv("USER"))
	{
		pstrcpy(smb_cli->user_name,getenv("USER"));

		/* modification to support userid%passwd syntax in the USER var
		25.Aug.97, [email protected] */

		if ((p=strchr(smb_cli->user_name,'%')))
		{
			*p = 0;
			pstrcpy(password,p+1);
			got_pass = True;
			memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
		}
		strupper(smb_cli->user_name);
	}

	password[0] = 0;

	/* modification to support PASSWD environmental var
	   25.Aug.97, [email protected] */
	if (getenv("PASSWD"))
	{
		pstrcpy(password,getenv("PASSWD"));
	}

	if (*smb_cli->user_name == 0 && getenv("LOGNAME"))
	{
		pstrcpy(smb_cli->user_name,getenv("LOGNAME"));
		strupper(smb_cli->user_name);
	}

	if (argc < 2)
	{
		usage(argv[0]);
		exit(1);
	}

	if (*argv[1] != '-')
	{

		pstrcpy(cli_info.service, argv[1]);  
		/* Convert any '/' characters in the service name to '\' characters */
		string_replace( cli_info.service, '/','\\');
		argc--;
		argv++;

		fprintf(out_hnd, "service: %s\n", cli_info.service);

		if (count_chars(cli_info.service,'\\') < 3)
		{
			usage(argv[0]);
			printf("\n%s: Not enough '\\' characters in service\n", cli_info.service);
			exit(1);
		}

		/*
		if (count_chars(cli_info.service,'\\') > 3)
		{
			usage(pname);
			printf("\n%s: Too many '\\' characters in service\n", cli_info.service);
			exit(1);
		}
		*/

		if (argc > 1 && (*argv[1] != '-'))
		{
			got_pass = True;
			pstrcpy(password,argv[1]);  
			memset(argv[1],'X',strlen(argv[1]));
			argc--;
			argv++;
		}

		cli_action = CLIENT_SVC;
	}

	while ((opt = getopt(argc, argv,"s:O:M:S:i:N:n:d:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
	{
		switch (opt)
		{
			case 'm':
			{
				/* FIXME ... max_protocol seems to be funny here */

				int max_protocol = 0;
				max_protocol = interpret_protocol(optarg,max_protocol);
				fprintf(stderr, "max protocol not currently supported\n");
				break;
			}

			case 'O':
			{
				pstrcpy(user_socket_options,optarg);
				break;	
			}

			case 'S':
			{
				pstrcpy(cli_info.dest_host,optarg);
				strupper(cli_info.dest_host);
				cli_action = CLIENT_IPC;
				break;
			}

			case 'i':
			{
				extern pstring global_scope;
				pstrcpy(global_scope, optarg);
				strupper(global_scope);
				break;
			}

			case 'U':
			{
				char *lp;
				pstrcpy(smb_cli->user_name,optarg);
				if ((lp=strchr(smb_cli->user_name,'%')))
				{
					*lp = 0;
					pstrcpy(password,lp+1);
					got_pass = True;
					memset(strchr(optarg,'%')+1,'X',strlen(password));
				}
				break;
			}

			case 'W':
			{
				pstrcpy(smb_cli->domain,optarg);
				break;
			}

			case 'E':
			{
				dbf = stderr;
				break;
			}

			case 'I':
			{
				cli_info.dest_ip = *interpret_addr2(optarg);
				if (zero_ip(cli_info.dest_ip))
				{
					exit(1);
				}
				break;
			}

			case 'n':
			{
				fstrcpy(global_myname, optarg);
				break;
			}

			case 'N':
			{
				got_pass = True;
				break;
			}

			case 'd':
			{
				if (*optarg == 'A')
					DEBUGLEVEL = 10000;
				else
					DEBUGLEVEL = atoi(optarg);
				break;
			}

			case 'l':
			{
				slprintf(debugf, sizeof(debugf)-1,
				         "%s.client", optarg);
				interactive = False;
				break;
			}

			case 'c':
			{
				cmd_str = optarg;
				got_pass = True;
				break;
			}

			case 'h':
			{
				usage(argv[0]);
				exit(0);
				break;
			}

			case 's':
			{
				pstrcpy(servicesf, optarg);
				break;
			}

			case 't':
			{
				pstrcpy(term_code, optarg);
				break;
			}

			default:
			{
				usage(argv[0]);
				exit(1);
				break;
			}
		}
	}

	setup_logging(debugf, interactive);

	if (cli_action == CLIENT_NONE)
	{
		usage(argv[0]);
		exit(1);
	}

	strupper(global_myname);
	fstrcpy(cli_info.myhostname, global_myname);

	DEBUG(3,("%s client started (version %s)\n",timestring(False),VERSION));

	if (!lp_load(servicesf,True, False, False))
	{
		fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
	}

	codepage_initialise(lp_client_code_page());

	if (*smb_cli->domain == 0) pstrcpy(smb_cli->domain,lp_workgroup());

	load_interfaces();

	if (cli_action == CLIENT_IPC)
	{
		pstrcpy(cli_info.share, "IPC$");
		pstrcpy(cli_info.svc_type, "IPC");
	}

	fstrcpy(cli_info.mach_acct, cli_info.myhostname);
	strupper(cli_info.mach_acct);
	fstrcat(cli_info.mach_acct, "$");

	/* set the password cache info */
	if (got_pass)
	{
		if (password[0] == 0)
		{
			pwd_set_nullpwd(&(smb_cli->pwd));
		}
		else
		{
			pwd_make_lm_nt_16(&(smb_cli->pwd), password); /* generate 16 byte hashes */
		}
	}
	else 
	{
		pwd_read(&(smb_cli->pwd), "Enter Password:"******"rpcclient_connect: smb_cli->fd:%d\n", smb_cli->fd));
	if (smb_cli->fd <= 0)
	{
		fprintf(stderr, "warning: connection could not be established to %s<%02x>\n",
		                 cli_info.dest_host, cli_info.name_type);
		fprintf(stderr, "this version of smbclient may crash if you proceed\n");
		exit(-1);
	}

	switch (cli_action)
	{
		case CLIENT_IPC:
		{
			process(&cli_info, cmd_str);
			break;
		}

		default:
		{
			fprintf(stderr, "unknown client action requested\n");
			break;
		}
	}

	rpcclient_stop();

	return(0);
}
コード例 #27
0
ファイル: winbindd_acct.c プロジェクト: hajuuk/R7000
static WINBINDD_GR* string2group( char *string )
{
	static WINBINDD_GR grp;
	char *p, *str;
	char *fields[NUM_GRP_FIELDS];
	int i;
	char **gr_members = NULL;
	int num_gr_members = 0;
	
	if ( !string )
		return NULL;
		
	ZERO_STRUCTP( &grp );
	
	DEBUG(10,("string2group: converting \"%s\"\n", string));
	
	ZERO_STRUCT( fields );
	
	for ( i=0, str=string; i<NUM_GRP_FIELDS-1; i++ ) {
		if ( !(p = strchr( str, ':' )) ) {
			DEBUG(0,("string2group: parsing failure\n"));
			return NULL;
		}
		*p = '\0';
		if ( str )
			fields[i] = str;
		str = p + 1;
	}
	
	/* group members */
	
	if ( *str ) {
		/* we already know we have a non-empty string */

		num_gr_members = count_chars(str, ',') + 1;
		
		/* if there was at least one comma, then there 
		   are n+1 members */
		if ( num_gr_members ) {
			fstring buffer;
			
			gr_members = SMB_XMALLOC_ARRAY(char*, num_gr_members+1);
			
			i = 0;
			while ( next_token(&str, buffer, ",", sizeof(buffer)) && i<num_gr_members ) {
				gr_members[i++] = smb_xstrdup(buffer);
			}

			gr_members[i]   = NULL;
		}
	}

	
	/* copy fields */
	
	fstrcpy( grp.gr_name,   fields[0] );
	fstrcpy( grp.gr_passwd, fields[1] );
	grp.gr_gid = atoi(      fields[2] );
	
	grp.num_gr_mem = num_gr_members;
	grp.gr_mem     = gr_members;
	
	/* last minute sanity checks */
	
	if ( grp.gr_gid == 0 ) {
		DEBUG(0,("string2group: Failure! gid==%lu\n", (unsigned long)grp.gr_gid));
		SAFE_FREE( gr_members );
		return NULL;
	}
	
	DEBUG(10,("string2group: Success\n"));

	return &grp;
}
コード例 #28
0
ファイル: sharesec.c プロジェクト: AllardJ/Tomato
BOOL parse_usershare_acl(TALLOC_CTX *ctx, const char *acl_str, SEC_DESC **ppsd)
{
	size_t s_size = 0;
	const char *pacl = acl_str;
	int num_aces = 0;
	SEC_ACE *ace_list = NULL;
	SEC_ACL *psa = NULL;
	SEC_DESC *psd = NULL;
	size_t sd_size = 0;
	int i;

	*ppsd = NULL;

	/* If the acl string is blank return "Everyone:R" */
	if (!*acl_str) {
		SEC_DESC *default_psd = get_share_security_default(ctx, &s_size, GENERIC_READ_ACCESS);
		if (!default_psd) {
			return False;
		}
		*ppsd = default_psd;
		return True;
	}

	num_aces = 1;

	/* Add the number of ',' characters to get the number of aces. */
	num_aces += count_chars(pacl,',');

	ace_list = TALLOC_ARRAY(ctx, SEC_ACE, num_aces);
	if (!ace_list) {
		return False;
	}

	for (i = 0; i < num_aces; i++) {
		SEC_ACCESS sa;
		uint32 g_access;
		uint32 s_access;
		DOM_SID sid;
		fstring sidstr;
		uint8 type = SEC_ACE_TYPE_ACCESS_ALLOWED;

		if (!next_token(&pacl, sidstr, ":", sizeof(sidstr))) {
			DEBUG(0,("parse_usershare_acl: malformed usershare acl looking "
				"for ':' in string '%s'\n", pacl));
			return False;
		}

		if (!string_to_sid(&sid, sidstr)) {
			DEBUG(0,("parse_usershare_acl: failed to convert %s to sid.\n",
				sidstr ));
			return False;
		}

		switch (*pacl) {
			case 'F': /* Full Control, ie. R+W */
			case 'f': /* Full Control, ie. R+W */
				s_access = g_access = GENERIC_ALL_ACCESS;
				break;
			case 'R': /* Read only. */
			case 'r': /* Read only. */
				s_access = g_access = GENERIC_READ_ACCESS;
				break;
			case 'D': /* Deny all to this SID. */
			case 'd': /* Deny all to this SID. */
				type = SEC_ACE_TYPE_ACCESS_DENIED;
				s_access = g_access = GENERIC_ALL_ACCESS;
				break;
			default:
				DEBUG(0,("parse_usershare_acl: unknown acl type at %s.\n",
					pacl ));
				return False;
		}

		pacl++;
		if (*pacl && *pacl != ',') {
			DEBUG(0,("parse_usershare_acl: bad acl string at %s.\n",
				pacl ));
			return False;
		}
		pacl++; /* Go past any ',' */

		se_map_generic(&s_access, &file_generic_mapping);
		init_sec_access(&sa, g_access | s_access );
		init_sec_ace(&ace_list[i], &sid, type, sa, 0);
	}

	if ((psa = make_sec_acl(ctx, NT4_ACL_REVISION, num_aces, ace_list)) != NULL) {
		psd = make_sec_desc(ctx, SEC_DESC_REVISION, SEC_DESC_SELF_RELATIVE, NULL, NULL, NULL, psa, &sd_size);
	}

	if (!psd) {
		DEBUG(0,("parse_usershare_acl: Failed to make SEC_DESC.\n"));
		return False;
	}

	*ppsd = psd;
	return True;
}
コード例 #29
0
ファイル: hangman.c プロジェクト: redsoukas/hangman-C
catList *newCat(catList *head, char letter, char*v[])  {
   
	int i, j, max, count;
	catList *root, *curr, *maxNode;
	root = head;
	curr = root;
	char *tempVector[head->wordsNum], tempAgent[atoi(v[1])], **adress = NULL;
	
	
	
	
	/*Temporary vector with pointers to words of dictionary list */
	for(i=0; i<head->wordsNum; i++)  {
	  
		tempVector[i] = head->vector[i];
	}
	
	
	
	
	
	/* If only 2 words remaining and user is one letter to go, we are looking to cheat */
	if ( (head->wordsNum == 2) && (count_chars(curr->agent, '_' ) == 1) )  {
	  
		count = 0;
		
		for(i=0; i<2; i++)  {
			if(strchr(tempVector[i], letter) == NULL)  {
				count = count + 1;
			}
		}
		
		/* Return the current node if no word has the letter */
		if (count == 2)  {
			return curr;
		}
		/* Creating final node */
		curr->nxt = malloc(sizeof(catList));
		if (curr->nxt == NULL)  {
			printf("ERROR: Memory allocation error in newCat\n");
			exit(1);
		}
		curr->nxt->prv = curr;
		curr = curr->nxt;
		curr->wordsNum = 1;
		curr->vector = (char**)malloc(sizeof(char *));
		if (curr->vector == NULL) {
			printf("ERROR: Memory allocation error in newCat\n");
			exit(1);
		}
		curr->agent = (char*)malloc((sizeof(char))*atoi(v[1])+1);
		if (curr->agent == NULL) {
			printf("ERROR: Memory allocation error in newCat\n");
			exit(1);
		}
		/* From the 2 remaining words, store the one that doesn't have the letter
		in the missing position */
		for(i=0; i<2; i++)  {
			if(strchr(tempVector[i], letter) == NULL)  {
				curr->vector[0] = tempVector[i];
				strcpy(curr->agent, head->agent);
				
				
			}
		}
		
		curr->nxt = NULL;
		return curr;
	}







	/* Creating the node with the words that don't have the letter user gave */
	curr->nxt = malloc(sizeof(catList));
	if (curr->nxt == NULL) {
		printf("ERROR: Memory allocation error in newCat\n");
		exit(1);
	}
	root = curr->nxt;
	curr->nxt->prv = curr;
	curr = curr->nxt;
	curr->wordsNum = 0;
	curr->vector = NULL;
	curr->agent = malloc((sizeof(char))*atoi(v[1])+1);
	if (curr->agent == NULL) {
		printf("ERROR: Memory allocation error in newCat\n");
		exit(1);
	}
	/* Representative is still the initial, since no word here has the letter user gave */
	strcpy(curr->agent, head->agent);
	
	count = 0;
	for(i=0; i<head->wordsNum; i++)  {
	  
		/*Storing the pointers to words that dont have the letter, in the dynamic array */
		if(strchr(tempVector[i], letter) == NULL)  {
			
			count = count +1;
			curr->wordsNum = count;
			curr->vector = (char **)realloc(adress, curr->wordsNum*sizeof(char *));
			if (curr->vector == NULL) {
				printf("ERROR: Memory allocation error in newCat\n");
				exit(1);
			}
			curr->vector[count-1] = tempVector[i];
			adress = curr->vector;
		}
	}
		
		
		
	/* Running the temporary vector */
	for(i=0; i<head->wordsNum; i++)  {

		/* We are looking for words that HAVE the letter */
		if ( (tempVector[i] != NULL)  && (strchr(tempVector[i], letter) != NULL) )  {
			
			
			/* For the first word that has the letter we create new category */
			curr->nxt = malloc(sizeof(catList));
			if (curr->nxt == NULL) {
				printf("ERROR: Memory allocation error in newCat\n");
				exit(1);
			}
			curr->nxt->prv = curr;
			curr = curr->nxt;
			curr->agent = malloc((sizeof(char))*atoi(v[1])+1);
			if (curr->agent == NULL) {
				printf("ERROR: Memory allocation error in newCat\n");
				exit(1);
			}
			/* Representative is the initial representative with 'letter' in same position(s) as word */
			strcpy(curr->agent, head->agent);
			copyChar(curr->agent, tempVector[i], letter);
			curr->vector = (char **)malloc(sizeof(char *));
			if (curr->vector == NULL) {
				printf("ERROR: Memory allocation error in newCat\n");
				exit(1);
			}
			curr->vector[0] = tempVector[i];
			curr->wordsNum = 1;
			
			/* We fill that category with all words below,
			that have the letter in the exact same position(s) */
			for(j=i+1; j<head->wordsNum; j++)  {
			
				
				if(tempVector[j] != NULL)  {
					  
					  strcpy(tempAgent, head->agent);
					  copyChar(tempAgent, tempVector[j], letter);
					  if(strcmp(curr->agent, tempAgent) == 0)  {
					
						curr->wordsNum = curr->wordsNum + 1;
						curr->vector = realloc(curr->vector, curr->wordsNum*sizeof(char *));
						if (curr->vector == NULL) {
							printf("ERROR: Memory allocation error in newCat\n");
							exit(1);
						}
						curr->vector[curr->wordsNum-1] = tempVector[j];
						/* Mark as NULL the pointers to words already categorized so we dont use them again */
						tempVector[j] = NULL;
						
  
					}
					
					
				}
			
				
			}
			
		}
		
		
	}
	curr->nxt = NULL;
	

	
	
	/* Running the category list from the second node and so,  to find the most crowded one */
	curr = root;
	max = curr->wordsNum;
	while(curr != NULL)  {
		if(curr->wordsNum>max)  {max = curr->wordsNum;}

		curr = curr->nxt;
	}
	
	
	/* Function will return the last node that has "max" words */
	curr = root;
	while(curr != NULL)  {
		if(curr->wordsNum == max)  {maxNode = curr;}
		curr = curr->nxt;
	}
 
 
 
  
	
	return maxNode;
 


}
コード例 #30
0
ファイル: 9.9.c プロジェクト: mixiaojiong/PointersOnC
int main(void) {
    char string[] = "helloalb";
    char chars[] = "loab";
    int x = count_chars(string, chars);
    printf("%d", x);
}