/**
 * Only allow certain keys. You can define the filter to be used. This makes
 *  sure no invalid keys can get into an editbox, like BELL.
 * @param key character to be checked
 * @param afilter the filter to use
 * @return true or false depending if the character is printable/valid or not
 */
bool IsValidChar(WChar key, CharSetFilter afilter)
{
	switch (afilter) {
		case CS_ALPHANUMERAL:  return IsPrintable(key);
		case CS_NUMERAL:       return (key >= '0' && key <= '9');
		case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
		case CS_ALPHA:         return IsPrintable(key) && !(key >= '0' && key <= '9');
		case CS_HEXADECIMAL:   return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F');
	}

	return false;
}
Exemple #2
0
static inline void
HexDumpLine(const char *prefix, unsigned offset,
            const uint8_t *data, size_t length)
{
  NarrowString<128> line;
  line.clear();

  for (size_t i = 0; i < length; ++i) {
    if ((i & 0x7) == 0)
      line += " ";

    line.AppendFormat(" %02x", data[i]);
  }

  for (size_t i = length; i < 0x10; ++i) {
    if ((i & 0x7) == 0)
      line += " ";

    line += "   ";
  }

  line += " ";
  for (size_t i = 0; i < length; ++i) {
    if ((i & 0x7) == 0)
      line += " ";

    char byte[2];
    byte[0] = IsPrintable(data[i]) ? (char)data[i] : '.';
    byte[1] = '\0';
    line += byte;
  }

  LogFormat("%s%04x%s", prefix, offset, line.c_str());
}
void build_hex_line( const uint8* buffer, size_t length, size_t offset, char* ret, unsigned int padding )
{
    ret += sprintf( ret, "%0*X:", padding, offset );

    char printable[17];

    for( size_t i = 0; i < 16; i++ )
    {
        if( i == 8 )
        {
            ret += sprintf( ret, " -" );
        }

        if( ( i + offset ) < length )
        {
            uint8 c = *(const uint8*)( buffer + offset + i );

            ret += sprintf( ret, " %02X", c );
            printable[i] = ( IsPrintable( c ) ? (char)c : '.' );
        }
        else
        {
            ret += sprintf( ret, "   " );
            printable[i] = 0;
        }
    }

    sprintf( ret, "  | %.16s", printable );
}
/**
 * Draw an unformatted news message truncated to a maximum length. If
 * length exceeds maximum length it will be postfixed by '...'
 * @param left  the left most location for the string
 * @param right the right most location for the string
 * @param y position of the string
 * @param colour the colour the string will be shown in
 * @param *ni NewsItem being printed
 * @param maxw maximum width of string in pixels
 */
static void DrawNewsString(uint left, uint right, int y, TextColour colour, const NewsItem *ni)
{
	char buffer[512], buffer2[512];
	StringID str;

	CopyInDParam(0, ni->params, lengthof(ni->params));
	str = ni->string_id;

	GetString(buffer, str, lastof(buffer));
	/* Copy the just gotten string to another buffer to remove any formatting
	 * from it such as big fonts, etc. */
	const char *ptr = buffer;
	char *dest = buffer2;
	WChar c_last = '\0';
	for (;;) {
		WChar c = Utf8Consume(&ptr);
		if (c == 0) break;
		/* Make a space from a newline, but ignore multiple newlines */
		if (c == '\n' && c_last != '\n') {
			dest[0] = ' ';
			dest++;
		} else if (c == '\r') {
			dest[0] = dest[1] = dest[2] = dest[3] = ' ';
			dest += 4;
		} else if (IsPrintable(c)) {
			dest += Utf8Encode(dest, c);
		}
		c_last = c;
	}

	*dest = '\0';
	/* Truncate and show string; postfixed by '...' if necessary */
	DrawString(left, right, y, buffer2, colour);
}
Exemple #5
0
static byte AskPassword (Password &password)
{
	size_t pos = 0;
	byte scanCode;
	byte asciiCode;

	Print ("Enter password");
	Print (PreventNormalSystemBoot ? " for hidden system:\r\n" : ": ");

	while (true)
	{
		asciiCode = GetKeyboardChar (&scanCode);

		switch (scanCode)
		{
		case TC_BIOS_KEY_ENTER:
			ClearBiosKeystrokeBuffer();
			PrintEndl();

			password.Length = pos;
			return scanCode;

		case TC_BIOS_KEY_BACKSPACE:
			if (pos > 0)
			{
				if (pos < MAX_PASSWORD)
					PrintBackspace();
				else
					PrintCharAtCursor (' ');

				--pos;
			}
			continue;

		default:
			if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode))
			{
				burn (password.Text, sizeof (password.Text));
				ClearBiosKeystrokeBuffer();

				PrintEndl();
				return scanCode;
			}
		}

		if (!IsPrintable (asciiCode) || pos == MAX_PASSWORD)
		{
			Beep();
			continue;
		}

		password.Text[pos++] = asciiCode;
		if (pos < MAX_PASSWORD)
			PrintChar ('*');
		else
			PrintCharAtCursor ('*');
	}
}
bool PyDumpVisitor::VisitString( const PyString *rep )
{
    if( IsPrintable( rep ) )
        _print( "%sString: '%s'", _pfx(), rep->content().c_str() );
    else
        _print( "%sString: '<binary, len=%lu>'", _pfx(), rep->content().length() );

    return true;
}
Exemple #7
0
GlyphID FreeTypeFontCache::MapCharToGlyph(WChar key)
{
	assert(IsPrintable(key));

	if (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END) {
		return this->parent->MapCharToGlyph(key);
	}

	return FT_Get_Char_Index(this->face, key);
}
bool PyDumpVisitor::VisitWString( const PyWString* rep )
{
    // how to do it correctly?
    if( IsPrintable( rep ) )
        _print( "%sWString: '%s'", _pfx(), rep->content().c_str() );
    else
        _print( "%sWstring: '<binary, len=%lu>'", _pfx(), rep->content().length() );

    return true;
}
bool IsPrintable( const char* str, size_t len )
{
    for(; len > 0; ++str, --len)
    {
        if( !IsPrintable( *str ) )
            return false;
    }

    return true;
}
/**
 * Scans the string for valid characters and if it finds invalid ones,
 * replaces them with a question mark '?' (if not ignored)
 * @param str the string to validate
 * @param last the last valid character of str
 * @param settings the settings for the string validation.
 */
void str_validate(char *str, const char *last, StringValidationSettings settings)
{
	/* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */

	char *dst = str;
	while (str <= last && *str != '\0') {
		size_t len = Utf8EncodedCharLen(*str);
		/* If the character is unknown, i.e. encoded length is 0
		 * we assume worst case for the length check.
		 * The length check is needed to prevent Utf8Decode to read
		 * over the terminating '\0' if that happens to be placed
		 * within the encoding of an UTF8 character. */
		if ((len == 0 && str + 4 > last) || str + len > last) break;

		WChar c;
		len = Utf8Decode(&c, str);
		/* It's possible to encode the string termination character
		 * into a multiple bytes. This prevents those termination
		 * characters to be skipped */
		if (c == '\0') break;

		if ((IsPrintable(c) && (c < SCC_SPRITE_START || c > SCC_SPRITE_END)) || ((settings & SVS_ALLOW_CONTROL_CODE) != 0 && c == SCC_ENCODED)) {
			/* Copy the character back. Even if dst is current the same as str
			 * (i.e. no characters have been changed) this is quicker than
			 * moving the pointers ahead by len */
			do {
				*dst++ = *str++;
			} while (--len != 0);
		} else if ((settings & SVS_ALLOW_NEWLINE) != 0  && c == '\n') {
			*dst++ = *str++;
		} else {
			if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\r' && str[1] == '\n') {
				str += len;
				continue;
			}
			/* Replace the undesirable character with a question mark */
			str += len;
			if ((settings & SVS_REPLACE_WITH_QUESTION_MARK) != 0) *dst++ = '?';

			/* In case of these two special cases assume that they really
			 * mean SETX/SETXY and also "eat" the parameter. If this was
			 * not the case the string was broken to begin with and this
			 * would not break much more. */
			if (c == SCC_SETX) {
				str++;
			} else if (c == SCC_SETXY) {
				str += 2;
			}
		}
	}

	*dst = '\0';
}
Exemple #11
0
/**
 * Retrieve keyboard layout from language string or (if set) config file.
 * Also check for invalid characters.
 */
void GetKeyboardLayout()
{
	char keyboard[2][OSK_KEYBOARD_ENTRIES * 4 + 1];
	char errormark[2][OSK_KEYBOARD_ENTRIES + 1]; // used for marking invalid chars
	bool has_error = false; // true when an invalid char is detected

	if (StrEmpty(_keyboard_opt[0])) {
		GetString(keyboard[0], STR_OSK_KEYBOARD_LAYOUT, lastof(keyboard[0]));
	} else {
		strecpy(keyboard[0], _keyboard_opt[0], lastof(keyboard[0]));
	}

	if (StrEmpty(_keyboard_opt[1])) {
		GetString(keyboard[1], STR_OSK_KEYBOARD_LAYOUT_CAPS, lastof(keyboard[1]));
	} else {
		strecpy(keyboard[1], _keyboard_opt[1], lastof(keyboard[1]));
	}

	for (uint j = 0; j < 2; j++) {
		const char *kbd = keyboard[j];
		bool ended = false;
		for (uint i = 0; i < OSK_KEYBOARD_ENTRIES; i++) {
			_keyboard[j][i] = Utf8Consume(&kbd);

			/* Be lenient when the last characters are missing (is quite normal) */
			if (_keyboard[j][i] == '\0' || ended) {
				ended = true;
				_keyboard[j][i] = ' ';
				continue;
			}

			if (IsPrintable(_keyboard[j][i])) {
				errormark[j][i] = ' ';
			} else {
				has_error = true;
				errormark[j][i] = '^';
				_keyboard[j][i] = ' ';
			}
		}
	}

	if (has_error) {
		ShowInfoF("The keyboard layout you selected contains invalid chars. Please check those chars marked with ^.");
		ShowInfoF("Normal keyboard:  %s", keyboard[0]);
		ShowInfoF("                  %s", errormark[0]);
		ShowInfoF("Caps Lock:        %s", keyboard[1]);
		ShowInfoF("                  %s", errormark[1]);
	}
}
// -----------------------------------------------------------------------------
// TSTSCharacterSetConverter::EscapedUnicodeToPrintableL
// Converts string from escaped unicode to printable string
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
HBufC8* TSTSCharacterSetConverter::EscapedUnicodeToPrintableLC(
    const TDesC& aValue) const
{
    TInt valueLength = aValue.Length();
    // returned value can never be longer than the original (it can be shorter)
    HBufC8* value = HBufC8::NewL(valueLength);
    CleanupStack::PushL(value);
    TPtr8 valueDes = value->Des();

    TLex lexer(aValue);

    while (!lexer.Eos())
    {
        TChar currentChar = lexer.Get();
        if (currentChar == '\\')
        {
            // we are escaping
            if (lexer.Eos())
            {
                User::Leave(KSTSErrInvalidCAName);
            }
            lexer.Mark();
            currentChar = lexer.Get();
            if (!IsSpecial(currentChar))
            {
                if (lexer.Eos())
                {
                    User::Leave(KSTSErrInvalidCAName);
                }
                lexer.Get();
                TLex hexPair(lexer.MarkedToken());
                TUint hexChar;
                User::LeaveIfError(hexPair.Val(hexChar, EHex));
                currentChar = hexChar;
            }
        }
        if (IsPrintable(currentChar))
        {
            valueDes.Append(currentChar);
        }
        else
        {
            User::Leave(KSTSErrInvalidCharactersInCAName);
        }
    }

    return value;
}
std::string XMLPacketGen::FNameToDef( const char* buf )
{
    std::string res;
    res += "__";

    for(; '\0' != *buf; ++buf )
    {
        if( !IsPrintable( *buf ) || *buf == '/' || *buf == '\\' || *buf == ':' || *buf == '.' || *buf == '-' )
            res += '_';
        else
            res += (char)toupper( *buf );
    }

    res += "__";
    return res;
}
void PrintHexDump (byte *mem, size_t size, uint16 *memSegment)
{
	const size_t width = 16;
	for (size_t pos = 0; pos < size; )
	{
		for (int pass = 1; pass <= 2; ++pass)
		{
			size_t i;
			for (i = 0; i < width && pos < size; ++i)
			{
				byte dataByte;
				if (memSegment)
				{
					__asm
					{
						push es
						mov si, ss:memSegment
						mov es, ss:[si]
						mov si, ss:mem
						add si, pos
						mov al, es:[si]
						mov dataByte, al
						pop es
					}
					pos++;
				}
				else
					dataByte = mem[pos++];

				if (pass == 1)
				{
					PrintHex (dataByte);
					PrintChar (' ');
				}
				else
					PrintChar (IsPrintable (dataByte) ? dataByte : '.');
			}

			if (pass == 1)
			{
				pos -= i;
				PrintChar (' ');
			}
		}

		PrintEndl ();
	}
Exemple #15
0
std::vector< std::string > IdentifierCompleter::CandidatesForQueryAndType(
  const std::string &query,
  const std::string &filetype ) const {
  ReleaseGil unlock;

  if ( !IsPrintable( query ) )
    return std::vector< std::string >();

  std::vector< Result > results;
  identifier_database_.ResultsForQueryAndType( query, filetype, results );

  std::vector< std::string > candidates;
  candidates.reserve( results.size() );

  for ( const Result & result : results ) {
    candidates.push_back( *result.Text() );
  }
  return candidates;
}
Exemple #16
0
void SCA_KeyboardSensor::AddToTargetProp(int keyIndex)
{
	if (IsPrintable(keyIndex)) {
		CValue* tprop = GetParent()->GetProperty(m_targetprop);
		
		if (tprop) {
			/* overwrite the old property */
			if (IsDelete(keyIndex)) {
				/* strip one char, if possible */
				STR_String newprop = tprop->GetText();
				int oldlength = newprop.Length();
				if (oldlength >= 1 ) {
					int newlength=oldlength;

					BLI_str_cursor_step_prev_utf8(newprop, newprop.Length(), &newlength);
					newprop.SetLength(newlength);

					CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
					GetParent()->SetProperty(m_targetprop, newstringprop);
					newstringprop->Release();
				}				
			} else {
				/* append */
				char pchar = ToCharacter(keyIndex, IsShifted());
				STR_String newprop = tprop->GetText() + pchar;
				CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);			
				GetParent()->SetProperty(m_targetprop, newstringprop);
				newstringprop->Release();
			}
		} else {
			if (!IsDelete(keyIndex)) {
				/* Make a new property. Deletes can be ignored. */
				char pchar = ToCharacter(keyIndex, IsShifted());
				STR_String newprop = pchar;
				CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);			
				GetParent()->SetProperty(m_targetprop, newstringprop);
				newstringprop->Release();
			}
		}
	}
	
}
static bool DrawScrollingStatusText(const NewsItem *ni, int scroll_pos, int left, int right, int top, int bottom)
{
	CopyInDParam(0, ni->params, lengthof(ni->params));
	StringID str = ni->string_id;

	char buf[512];
	GetString(buf, str, lastof(buf));
	const char *s = buf;

	char buffer[256];
	char *d = buffer;
	const char *last = lastof(buffer);

	for (;;) {
		WChar c = Utf8Consume(&s);
		if (c == 0) {
			break;
		} else if (c == '\n') {
			if (d + 4 >= last) break;
			d[0] = d[1] = d[2] = d[3] = ' ';
			d += 4;
		} else if (IsPrintable(c)) {
			if (d + Utf8CharLen(c) >= last) break;
			d += Utf8Encode(d, c);
		}
	}
	*d = '\0';

	DrawPixelInfo tmp_dpi;
	if (!FillDrawPixelInfo(&tmp_dpi, left, top, right - left, bottom)) return true;

	int width = GetStringBoundingBox(buffer).width;
	int pos = (_current_text_dir == TD_RTL) ? (scroll_pos - width) : (right - scroll_pos - left);

	DrawPixelInfo *old_dpi = _cur_dpi;
	_cur_dpi = &tmp_dpi;
	DrawString(pos, INT16_MAX, 0, buffer, TC_LIGHT_BLUE, SA_LEFT | SA_FORCE);
	_cur_dpi = old_dpi;

	return (_current_text_dir == TD_RTL) ? (pos < right - left) : (pos + width > 0);
}
void SCA_KeyboardSensor::AddToTargetProp(int keyIndex, int unicode)
{
	if (IsPrintable(keyIndex)) {
		CValue* tprop = GetParent()->GetProperty(m_targetprop);

		if (IsDelete(keyIndex)) {
			/* Make a new property. Deletes can be ignored. */
			if (tprop) {
				/* overwrite the old property */
				/* strip one char, if possible */
				STR_String newprop = tprop->GetText();
				int oldlength = newprop.Length();
				if (oldlength >= 1 ) {
					int newlength=oldlength;

					BLI_str_cursor_step_prev_utf8(newprop, newprop.Length(), &newlength);
					newprop.SetLength(newlength);

					CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
					GetParent()->SetProperty(m_targetprop, newstringprop);
					newstringprop->Release();
				}
			}
		}
		else {
			char utf8_buf[7];
			size_t utf8_len;

			utf8_len = BLI_str_utf8_from_unicode(unicode, utf8_buf);
			utf8_buf[utf8_len] = '\0';

			STR_String newprop = tprop ? (tprop->GetText() + utf8_buf) : utf8_buf;

			CStringValue * newstringprop = new CStringValue(newprop, m_targetprop);
			GetParent()->SetProperty(m_targetprop, newstringprop);
			newstringprop->Release();
		}
	}
}
Exemple #19
0
 static inline size_t EscapeC(unsigned char c, TNextChar next, TBufferChar r[ESCAPE_C_BUFFER_SIZE]) {
     // (1) Printable characters go as-is, except backslash and double quote.
     // (2) Characters \r, \n, \t and \0 ... \7 replaced by their simple escape characters (if possible).
     // (3) Otherwise, character is encoded using hexadecimal escape sequence (if possible), or octal.
     if (c == '\"') {
         r[0] = '\\';
         r[1] = '\"';
         return 2;
     } else if (c == '\\') {
         r[0] = '\\';
         r[1] = '\\';
         return 2;
     } else if (IsPrintable(c)) {
         r[0] = c;
         return 1;
     } else if (c == '\r') {
         r[0] = '\\';
         r[1] = 'r';
         return 2;
     } else if (c == '\n') {
         r[0] = '\\';
         r[1] = 'n';
         return 2;
     } else if (c == '\t') {
         r[0] = '\\';
         r[1] = 't';
         return 2;
    } else if (c < 8 && !IsOctDigit(next)) {
         r[0] = '\\';
         r[1] = OctDigit(c);
         return 2;
     } else if (!IsHexDigit(next)) {
         r[0] = '\\';
         r[1] = 'x';
         r[2] = HexDigit((c & 0xF0) >> 4);
         r[3] = HexDigit((c & 0x0F) >> 0);
         return 4;
     } else {
/**
 * Checks whether the given string is valid, i.e. contains only
 * valid (printable) characters and is properly terminated.
 * @param str  The string to validate.
 * @param last The last character of the string, i.e. the string
 *             must be terminated here or earlier.
 */
bool StrValid(const char *str, const char *last)
{
	/* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */

	while (str <= last && *str != '\0') {
		size_t len = Utf8EncodedCharLen(*str);
		/* Encoded length is 0 if the character isn't known.
		 * The length check is needed to prevent Utf8Decode to read
		 * over the terminating '\0' if that happens to be placed
		 * within the encoding of an UTF8 character. */
		if (len == 0 || str + len > last) return false;

		WChar c;
		len = Utf8Decode(&c, str);
		if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
			return false;
		}

		str += len;
	}

	return *str == '\0';
}
Exemple #21
0
/**
 * Construct a new line with a maximum width.
 * @param max_width The maximum width of the string.
 * @return A Line, or NULL when at the end of the paragraph.
 */
const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
{
	/* Simple idea:
	 *  - split a line at a newline character, or at a space where we can break a line.
	 *  - split for a visual run whenever a new line happens, or the font changes.
	 */
	if (this->buffer == NULL) return NULL;

	FallbackLine *l = new FallbackLine();

	if (*this->buffer == '\0') {
		/* Only a newline. */
		this->buffer = NULL;
		*l->Append() = new FallbackVisualRun(this->runs.Begin()->second, this->buffer, 0, 0);
		return l;
	}

	const WChar *begin = this->buffer;
	const WChar *last_space = NULL;
	const WChar *last_char = begin;
	int width = 0;

	int offset = this->buffer - this->buffer_begin;
	FontMap::iterator iter = this->runs.Begin();
	while (iter->first <= offset) {
		iter++;
		assert(iter != this->runs.End());
	}

	const FontCache *fc = iter->second->fc;
	const WChar *next_run = this->buffer_begin + iter->first;

	for (;;) {
		WChar c = *this->buffer;
		last_char = this->buffer;

		if (c == '\0') {
			this->buffer = NULL;
			break;
		}

		if (this->buffer == next_run) {
			int w = l->GetWidth();
			*l->Append() = new FallbackVisualRun(iter->second, begin, this->buffer - begin, w);
			iter++;
			assert(iter != this->runs.End());

			next_run = this->buffer_begin + iter->first;
			begin = this->buffer;

			last_space = NULL;
		}

		if (IsWhitespace(c)) last_space = this->buffer;

		if (IsPrintable(c) && !IsTextDirectionChar(c)) {
			int char_width = GetCharacterWidth(fc->GetSize(), c);
			width += char_width;
			if (width > max_width) {
				/* The string is longer than maximum width so we need to decide
				 * what to do with it. */
				if (width == char_width) {
					/* The character is wider than allowed width; don't know
					 * what to do with this case... bail out! */
					this->buffer = NULL;
					return l;
				}

				if (last_space == NULL) {
					/* No space has been found. Just terminate at our current
					 * location. This usually happens for languages that do not
					 * require spaces in strings, like Chinese, Japanese and
					 * Korean. For other languages terminating mid-word might
					 * not be the best, but terminating the whole string instead
					 * of continuing the word at the next line is worse. */
					last_char = this->buffer;
				} else {
					/* A space is found; perfect place to terminate */
					this->buffer = last_space + 1;
					last_char = last_space;
				}
				break;
			}
		}

		this->buffer++;
	}

	if (l->Length() == 0 || last_char - begin != 0) {
		int w = l->GetWidth();
		*l->Append() = new FallbackVisualRun(iter->second, begin, last_char - begin, w);
	}
	return l;
}
Exemple #22
0
/* Parses one AVA, starting at *pbp.  Stops at endptr.
 * Advances *pbp past parsed AVA and trailing separator (if present).
 * On any error, returns NULL and *pbp is undefined.
 * On success, returns CERTAVA allocated from arena, and (*pbp)[-1] was
 * the last character parsed.  *pbp is either equal to endptr or
 * points to first character after separator.
 */
static CERTAVA *
ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr)
{
    CERTAVA *a;
    const NameToKind *n2k;
    char *bp;
    int       vt = -1;
    int       valLen;
    SECOidTag kind  = SEC_OID_UNKNOWN;
    SECStatus rv    = SECFailure;
    SECItem   derOid = { 0, NULL, 0 };
    SECItem   derVal = { 0, NULL, 0};
    char      sep   = 0;

    char tagBuf[32];
    char valBuf[384];

    PORT_Assert(arena);
    if (SECSuccess != scanTag(pbp, endptr, tagBuf, sizeof tagBuf) ||
            !(valLen    = scanVal(pbp, endptr, valBuf, sizeof valBuf))) {
        goto loser;
    }

    bp = *pbp;
    if (bp < endptr) {
        sep = *bp++; /* skip over separator */
    }
    *pbp = bp;
    /* if we haven't finished, insist that we've stopped on a separator */
    if (sep && sep != ',' && sep != ';' && sep != '+') {
        goto loser;
    }

    /* is this a dotted decimal OID attribute type ? */
    if (!PL_strncasecmp("oid.", tagBuf, 4)) {
        rv = SEC_StringToOID(arena, &derOid, tagBuf, strlen(tagBuf));
    } else {
        for (n2k = name2kinds; n2k->name; n2k++) {
            SECOidData *oidrec;
            if (PORT_Strcasecmp(n2k->name, tagBuf) == 0) {
                kind = n2k->kind;
                vt   = n2k->valueType;
                oidrec = SECOID_FindOIDByTag(kind);
                if (oidrec == NULL)
                    goto loser;
                derOid = oidrec->oid;
                break;
            }
        }
    }
    if (kind == SEC_OID_UNKNOWN && rv != SECSuccess)
        goto loser;

    /* Is this a hex encoding of a DER attribute value ? */
    if ('#' == valBuf[0]) {
        /* convert attribute value from hex to binary */
        rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1);
        if (rv)
            goto loser;
        a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal);
    } else {
        if (kind == SEC_OID_UNKNOWN)
            goto loser;
        if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2)
            goto loser;
        if (vt == SEC_ASN1_PRINTABLE_STRING &&
                !IsPrintable((unsigned char*) valBuf, valLen))
            goto loser;
        if (vt == SEC_ASN1_DS) {
            /* RFC 4630: choose PrintableString or UTF8String */
            if (IsPrintable((unsigned char*) valBuf, valLen))
                vt = SEC_ASN1_PRINTABLE_STRING;
            else
                vt = SEC_ASN1_UTF8_STRING;
        }

        derVal.data = (unsigned char*) valBuf;
        derVal.len  = valLen;
        a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal);
    }
    return a;

loser:
    /* matched no kind -- invalid tag */
    PORT_SetError(SEC_ERROR_INVALID_AVA);
    return 0;
}
Exemple #23
0
BOOL CCLITerminal::InputStream(CLISESSION *pSession, const unsigned char *pszBuffer, int nLength)
{
	unsigned char	cc;
 	int				i, nVKey;

	if (pSession->pWorker != NULL)
	{
		// 이미 수행중인 작업이 있는 경우
		return TRUE;
	}

	for(i=0; i<nLength; i++)
	{
		cc = pszBuffer[i];

retry_loop:
		switch(pSession->nState) {
		  case TS_CR :
			   if (cc == '\n')
				  break;

			   // Do not break
			   pSession->nState = TS_DATA;

		  case TS_DATA :
			   switch(cc) {
				 case 0x00 :
					  break;
				 case IAC :
				      pSession->nState = TS_IAC;
					  break;
				 case KEY_BS :
					  ExecuteBackspace(pSession);
					  break;
				 case KEY_DEL :
					  ExecuteDelete(pSession);
					  break;
				 case KEY_TAB :
					  if (!pSession->bLogined)
						  break;
					  ExecuteTab(pSession);
					  break;
				 case '?' :
					  if (!pSession->bLogined)
						  break;
					  ExecuteInlineHelp(pSession);
					  break;
				 case KEY_ESC :
					  pSession->nState = TS_ESC;
					  break;
				 case KEY_CTRL_D :
//					  exit(0);
					  return FALSE;
				 default :
//				   	  if (!pSession->nLocalOptions[TELOPT_BINARY] && (cc == '\r'))
				   	  if (cc == '\r')
				   	  {
					      if (!ExecuteCommand(pSession))
							  return FALSE;
					   	  pSession->nState = TS_CR;
					   	  break;
				   	  }
					  if (IsPrintable(cc) && ((pSession->nCmdLength+1)<=CLIMAX_COMMAND_SIZE))
					  {
					  	  pSession->szCommand[pSession->nCmdLength] = cc;
					  	  pSession->nCmdLength++;
						  if (pSession->bNeedUser)
					  	  	   WriteChar(pSession, cc);
					  	  else WriteChar(pSession, pSession->bLogined ? cc : '*');
					  }
					  break;
			   }
			   break;

		  case TS_ESC :
			   if ((cc != '[') && (cc != 'O'))
			   {
				  pSession->nState = TS_DATA;
 				  goto retry_loop;
			   }
			   pSession->nVKeyCount = 0;
			   pSession->nState = TS_ESCSEQ;

		  case TS_ESCSEQ :
			   if (pSession->nVKeyCount >= MAX_VIRTUAL_KEY_SIZE)
			   {
				   pSession->nState = TS_DATA;
				   goto retry_loop;
			   }

			   pSession->szVKeyBuffer[pSession->nVKeyCount] = cc;
			   pSession->nVKeyCount++;
			   pSession->szVKeyBuffer[pSession->nVKeyCount] = '\0';

			   nVKey = FindVirtualKey(pSession);
			   if (nVKey >= 0)
			   {
				   ExecuteVirtualKey(pSession, nVKey);
			   	   pSession->nState = TS_DATA;
			   }
			   else if (nVKey == -1)
			   {
				   pSession->nState = TS_DATA;
				   goto retry_loop;
			   }
			   break;

		  case TS_IAC :
			   switch(cc) {
				 case BREAK :
				 case IP :
					  pSession->nState = TS_DATA;
					  break;
				 case AYT :
					  WriteStream(pSession, (char *)aytreply, strlen((char *)aytreply));
					  pSession->nState = TS_DATA;
					  break;
				 case AO :
					  WriteStream(pSession, (char *)aoreply, 2);
					  pSession->nState = TS_DATA;
					  break;
				 case EC :
					  WriteStream(pSession, "\b", 1);
					  pSession->nState = TS_DATA;
					  break;
				 case EL :
					  WriteStream(pSession, "\025", 1);
					  pSession->nState = TS_DATA;
					  break;
				 case DM :
					  pSession->nState = TS_DATA;
					  break;
				 case SB :
					  pSession->nState = TS_SB;
					  break;
				 case WILL :
					  pSession->nState = TS_WILL;
					  break;
				 case WONT :
					  pSession->nState = TS_WONT;
					  break;
				 case DO :
					  pSession->nState = TS_DO;
					  break;
				 case DONT :
					  pSession->nState = TS_DONT;
					  break;
				 case IAC :
					  WriteChar(pSession, cc);
					  pSession->nState = TS_DATA;
					  break;
				 default :
					  pSession->nState = TS_DATA;
					  break;
			   }
			   break;

		  case TS_SB :
			   if (cc == IAC)
				   pSession->nState = TS_SE;
			   break;

		  case TS_SE :
			   pSession->nState = (cc == SE) ? TS_DATA : TS_SB;
			   break; 

		  case TS_WILL :
			   //printf("IAC WILL %0d\n", cc);
			   RemoteDoOption(pSession, (int)cc, TRUE, TRUE);
			   pSession->nState = TS_DATA;
			   break;

		  case TS_WONT :
			   //printf("IAC WONT %0d\n", cc);
			   RemoteDoOption(pSession, (int)cc, FALSE, TRUE);
			   pSession->nState = TS_DATA;
			   break;

		  case TS_DO :
			   //printf("IAC DO %0d\n", cc);
			   LocalDoOption(pSession, (int)cc, TRUE, TRUE);
			   pSession->nState = TS_DATA;
			   break;

		  case TS_DONT :
			   //printf("IAC DONT %0d\n", cc);
			   LocalDoOption(pSession, (int)cc, FALSE, TRUE);
			   pSession->nState = TS_DATA;
			   break;
		}
	}

	return TRUE;
}
const Sprite *GetGlyph(FontSize size, WChar key)
{
	FT_Face face = GetFontFace(size);
	FT_GlyphSlot slot;
	GlyphEntry new_glyph;
	GlyphEntry *glyph;
	SpriteLoader::Sprite sprite;
	int width;
	int height;
	int x;
	int y;

	assert(IsPrintable(key));

	/* Bail out if no face loaded, or for our special characters */
	if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
		SpriteID sprite = GetUnicodeGlyph(size, key);
		if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');

		/* Load the sprite if it's known. */
		if (sprite != 0) return GetSprite(sprite, ST_FONT);

		/* For the 'rare' case there is no font available at all. */
		if (face == NULL) error("No sprite font and no real font either... bailing!");

		/* Use the '?' from the freetype font. */
		key = '?';
	}

	/* Check for the glyph in our cache */
	glyph = GetGlyphPtr(size, key);
	if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;

	slot = face->glyph;

	bool aa = GetFontAAState(size);

	FT_UInt glyph_index = FT_Get_Char_Index(face, key);
	if (glyph_index == 0) {
		if (key == '?') {
			/* The font misses the '?' character. Use sprite font. */
			SpriteID sprite = GetUnicodeGlyph(size, key);
			Sprite *spr = (Sprite*)GetRawSprite(sprite, ST_FONT, AllocateFont);
			assert(spr != NULL);
			new_glyph.sprite = spr;
			new_glyph.width  = spr->width + (size != FS_NORMAL);
			SetGlyphPtr(size, key, &new_glyph, false);
			return new_glyph.sprite;
		} else {
			/* Use '?' for missing characters. */
			GetGlyph(size, '?');
			glyph = GetGlyphPtr(size, '?');
			SetGlyphPtr(size, key, glyph, true);
			return glyph->sprite;
		}
	}
	FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
	FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);

	/* Despite requesting a normal glyph, FreeType may have returned a bitmap */
	aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);

	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
	width  = max(1, slot->bitmap.width + (size == FS_NORMAL));
	height = max(1, slot->bitmap.rows  + (size == FS_NORMAL));

	/* Limit glyph size to prevent overflows later on. */
	if (width > 256 || height > 256) usererror("Font glyph is too large");

	/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
	sprite.AllocateData(width * height);
	sprite.type = ST_FONT;
	sprite.width = width;
	sprite.height = height;
	sprite.x_offs = slot->bitmap_left;
	sprite.y_offs = _ascender[size] - slot->bitmap_top;

	/* Draw shadow for medium size */
	if (size == FS_NORMAL && !aa) {
		for (y = 0; y < slot->bitmap.rows; y++) {
			for (x = 0; x < slot->bitmap.width; x++) {
				if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
					sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
					sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
				}
			}
		}
	}

	for (y = 0; y < slot->bitmap.rows; y++) {
		for (x = 0; x < slot->bitmap.width; x++) {
			if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
				sprite.data[x + y * sprite.width].m = FACE_COLOUR;
				sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
			}
		}
	}

	new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
	new_glyph.width  = slot->advance.x >> 6;

	SetGlyphPtr(size, key, &new_glyph);

	return new_glyph.sprite;
}
bool IsPrintable( const std::string& str )
{
    return IsPrintable( str.c_str(), str.size() );
}
Exemple #26
0
static byte AskPassword (Password &password, int& pin)
{
	size_t pos = 0;
	byte scanCode;
	byte asciiCode;
	byte hidePassword = 1;

	pin = 0;

	Print ("Enter password");
	Print (PreventNormalSystemBoot ? " for hidden system:\r\n" : ": ");

	while (true)
	{
		asciiCode = GetKeyboardChar (&scanCode);

		switch (scanCode)
		{
		case TC_BIOS_KEY_ENTER:
			ClearBiosKeystrokeBuffer();
			PrintEndl();

			password.Length = pos;
			break;

		case TC_BIOS_KEY_BACKSPACE:
			if (pos > 0)
			{
				if (pos < MAX_PASSWORD)
					PrintBackspace();
				else
					PrintCharAtCursor (' ');

				--pos;
			}
			continue;

		case TC_BIOS_KEY_F5:
			hidePassword ^= 0x01;
			continue;

		default:
			if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode))
			{
				burn (password.Text, sizeof (password.Text));
				ClearBiosKeystrokeBuffer();

				PrintEndl();
				return scanCode;
			}
		}

		if (TC_BIOS_KEY_ENTER == scanCode)
			break;

		if (!IsPrintable (asciiCode) || pos == MAX_PASSWORD)
		{
			Beep();
			continue;
		}

		password.Text[pos++] = asciiCode;
		if (hidePassword) asciiCode = '*';
		if (pos < MAX_PASSWORD)
			PrintChar (asciiCode);
		else
			PrintCharAtCursor (asciiCode);
	}

	pos = 0;
	Print ("PIM: ");

	while (true)
	{
		asciiCode = GetKeyboardChar (&scanCode);

		switch (scanCode)
		{
		case TC_BIOS_KEY_ENTER:
			ClearBiosKeystrokeBuffer();
			PrintEndl();

			return TC_BIOS_KEY_ENTER;

		case TC_BIOS_KEY_BACKSPACE:
			if (pos > 0)
			{
				if (pos < MAX_PIM)
					PrintBackspace();
				else
					PrintCharAtCursor (' ');

				--pos;
				pin /= 10;
			}
			continue;

		default:
			if (scanCode == TC_BIOS_KEY_ESC || IsMenuKey (scanCode))
			{
				burn (password.Text, sizeof (password.Text));
				ClearBiosKeystrokeBuffer();

				PrintEndl();
				return scanCode;
			}
		}

		if (!IsDigit (asciiCode) || pos == MAX_PIM)
		{
			Beep();
			continue;
		}

		pin = 10*pin + (asciiCode - '0');
		pos++;

		if (pos < MAX_PIM)
			PrintChar (asciiCode);
		else
			PrintCharAtCursor (asciiCode);
	}
}
Exemple #27
0
bool IsPrintable( const PyString* str )
{
    return IsPrintable( str->content() );
}
Exemple #28
0
/****************************************************************************
Function        : _CliStringParser
Description     : String Parser
*****************************************************************************/
static INT32 _CliStringParser(const char *szCmdBuf, UINT32 u4ArgNum, UINT32 u4ArgLen, char * const * szArgv)
{
    INT32 i4Argc = 0;
    char cChar;
    char * pcStr;
    UINT32 u4Cnt;
    INT32 u4State; /* 1 is single quote, 2, is double quota. */

    if ((szCmdBuf == NULL) || (u4ArgNum == 0) || (u4ArgLen == 0) || (szArgv == NULL))
    {
        return 0;
    }

    cChar = *szCmdBuf;

    while (cChar != ASCII_NULL)
    {
        pcStr = szArgv[i4Argc];

        // skip space
        while (!IsPrintable(cChar) || IsSpace(cChar))
        {
            cChar = *(++szCmdBuf);
        }

        // copy non-space characters
        u4Cnt = 0;
        u4State = 0;
        while (IsPrintable(cChar) && (((u4State==0) && !IsSpace(cChar)) ||
                ((u4State==1) && (cChar!=ASCII_KEY_QUOTE)) ||
                ((u4State==2) && (cChar!=ASCII_KEY_DBL_QUOTE))))
        {

            if (cChar == ASCII_NULL)    // end of string
            {
                *pcStr = ASCII_NULL;    // end of string
                break;
            }

            if (u4Cnt >= (u4ArgLen - 1))    // maximum argument length
            {
                *pcStr = ASCII_NULL;    // end of string
                break;
            }

            if ((u4State!=2) && (cChar==0x27)) {
                if (u4State==0) {
                    u4State = 1;
                    cChar = *(++szCmdBuf);
                    u4Cnt++;
                } else if (u4State==1) {
                    u4State = 0;
                }
                continue;
            } else if ((u4State!=1) && (cChar==0x22)) {
                if (u4State==0) {
                    u4State = 2;
                    cChar = *(++szCmdBuf);
                    u4Cnt++;
                } else if (u4State==2) {
                    u4State = 0;
                }
                continue;
            }

            *pcStr = cChar;
            u4Cnt++;
            pcStr++;
            cChar = *(++szCmdBuf);
        }

        if ((cChar==ASCII_KEY_QUOTE) || (cChar==ASCII_KEY_DBL_QUOTE)) {
            cChar = *(++szCmdBuf);
            u4Cnt++;
        }

        if (u4Cnt > 0)
        {
            *pcStr = ASCII_NULL;    // end of string
            i4Argc++;
        }

        if ((UINT32)i4Argc >= u4ArgNum)
        {
            break;
        }
    }

    return i4Argc;
}
Exemple #29
0
	virtual GlyphID MapCharToGlyph(WChar key) { assert(IsPrintable(key)); return SPRITE_GLYPH | key; }
Exemple #30
0
bool IsPrintable( const PyWString* str )
{
    // how to do it correctly?
    return IsPrintable( str->content() );
}