void SB_SkipWhite (StrBuf* B) /* Skip whitespace in the string buffer */ { while (IsBlank (SB_Peek (B))) { SB_Skip (B); } }
static char* SkipWhitespace (char* L) /* Ignore white space in L */ { while (IsBlank (*L)) { ++L; } return L; }
void testopts(struct user_opt *opt) { struct stat teststat; /* Test for a pcap file */ if (IsBlank(opt->pcapfile)) { usage("Must supply a pcap file with -r"); exit(-1); } if (opt->checkonly == 1) { /* Special case where we only need pcap file */ return; } /* test for required parameters */ if (IsBlank(opt->dictfile) && IsBlank(opt->hashfile)) { usage("Must supply a list of passphrases in a file with -f " "or a hash file\n\t with -d. " "Use \"-f -\" to accept words on stdin."); exit(-1); } if (IsBlank(opt->ssid)) { usage("Must supply the SSID for the network with -s"); exit(-1); } /* Test that the files specified exist and are greater than 0 bytes */ if (!IsBlank(opt->hashfile) && strncmp(opt->hashfile, "-", 1) != 0) { if (stat(opt->hashfile, &teststat)) { usage("Could not stat hashfile. Check file path."); exit(-1); } else if (teststat.st_size == 0) { usage("Empty hashfile (0 bytes). Check file contents."); exit(-1); } } if (!IsBlank(opt->dictfile) && strncmp(opt->dictfile, "-", 1) != 0) { if (stat(opt->dictfile, &teststat)) { usage ("Could not stat the dictionary file. Check file path."); exit(-1); } else if (teststat.st_size == 0) { usage ("Empty dictionary file (0 bytes). Check file contents."); exit(-1); } } if (stat(opt->pcapfile, &teststat) && strncmp(opt->hashfile, "-", 1) != 0) { usage("Could not stat the pcap file. Check file path."); exit(-1); } else if (teststat.st_size == 0) { usage("Empty pcap file (0 bytes). Check file contents."); exit(-1); } }
int BinaryBoard::QuickSplitVertically(Rect originRect, Rect output[2]) const { Rect tOrigin = QuickCrop(originRect); Border b = (tOrigin / blockSize).ToOuterBorder(); int splitAt = -1; for (int y = b.bottom - 2; y > b.top; --y) { bool blank = true; for (int x = b.left; x < b.right; ++x) { if (!IsBlank(x, y)) { blank = false; break; } } if (blank) { splitAt = y * blockSize; break; } } if (splitAt == -1) { output[0] = tOrigin; return 1; } b = tOrigin.ToOuterBorder(); b.top = splitAt; output[0] = QuickCrop(Rect::FromOuterBorder(b)); b = tOrigin.ToOuterBorder(); b.bottom = splitAt; output[1] = QuickCrop(Rect::FromOuterBorder(b)); return 2; }
void EditWorkspace(System *sys) { VMVALUE lineNumber; char *token; BufInit(); VM_printf("ebasic 0.001\n"); for (;; ) { VM_getline(sys->lineBuf, sizeof(sys->lineBuf)); sys->linePtr = sys->lineBuf; if ((token = NextToken(sys)) != NULL) { if (ParseNumber(token, &lineNumber)) { if (IsBlank(sys->linePtr)) { if (!BufDeleteLineN(lineNumber)) VM_printf("no line %d\n", lineNumber); } else if (!BufAddLineN(lineNumber, sys->linePtr)) VM_printf("out of edit buffer space\n"); } else { int i; for (i = 0; cmds[i].name != NULL; ++i) if (strcasecmp(token, cmds[i].name) == 0) break; if (cmds[i].handler) { (*cmds[i].handler)(sys); VM_printf("OK\n"); } else VM_printf("unknown command: %s\n", token); } } } }
static int exec(FILE* fp, ENC_INFO* einfo) { #define NCOL 8 int c, val, enc; enc = einfo->num; fprintf(fp, "static const unsigned short Enc%s_CtypeTable[256] = {\n", einfo->name); for (c = 0; c < 256; c++) { val = 0; if (IsNewline(enc, c)) val |= BIT_CTYPE_NEWLINE; if (IsAlpha (enc, c)) val |= (BIT_CTYPE_ALPHA | BIT_CTYPE_ALNUM); if (IsBlank (enc, c)) val |= BIT_CTYPE_BLANK; if (IsCntrl (enc, c)) val |= BIT_CTYPE_CNTRL; if (IsDigit (enc, c)) val |= (BIT_CTYPE_DIGIT | BIT_CTYPE_ALNUM); if (IsGraph (enc, c)) val |= BIT_CTYPE_GRAPH; if (IsLower (enc, c)) val |= BIT_CTYPE_LOWER; if (IsPrint (enc, c)) val |= BIT_CTYPE_PRINT; if (IsPunct (enc, c)) val |= BIT_CTYPE_PUNCT; if (IsSpace (enc, c)) val |= BIT_CTYPE_SPACE; if (IsUpper (enc, c)) val |= BIT_CTYPE_UPPER; if (IsXDigit(enc, c)) val |= BIT_CTYPE_XDIGIT; if (IsWord (enc, c)) val |= BIT_CTYPE_WORD; if (IsAscii (enc, c)) val |= BIT_CTYPE_ASCII; if (c % NCOL == 0) fputs(" ", fp); fprintf(fp, "0x%04x", val); if (c != 255) fputs(",", fp); if (c != 0 && c % NCOL == (NCOL-1)) fputs("\n", fp); else fputs(" ", fp); } fprintf(fp, "};\n"); return 0; }
int main(int argc, char **argv) { struct user_opt opt; struct crack_data cdata; struct capture_data capdata; struct wpa_eapol_key *eapkeypacket; u8 eapolkey_nomic[99]; struct timeval start, end; int ret; char passphrase[MAXPASSLEN + 1]; printf("%s %s - WPA-PSK dictionary attack. <*****@*****.**>\n", PROGNAME, VER); memset(&opt, 0, sizeof(struct user_opt)); memset(&capdata, 0, sizeof(struct capture_data)); memset(&cdata, 0, sizeof(struct crack_data)); memset(&eapolkey_nomic, 0, sizeof(eapolkey_nomic)); /* Collect and test command-line arguments */ parseopts(&opt, argc, argv); testopts(&opt); printf("\n"); /* Populate capdata struct */ strncpy(capdata.pcapfilename, opt.pcapfile, sizeof(capdata.pcapfilename)); if (openpcap(&capdata) != 0) { printf("Unsupported or unrecognized pcap file.\n"); exit(-1); } /* populates global *packet */ while (getpacket(&capdata) > 0) { if (opt.verbose > 2) { lamont_hdump(packet, h->len); } /* test packet for data that we are looking for */ if (memcmp(&packet[capdata.l2type_offset], DOT1X_LLCTYPE, 2) == 0 && (h->len > capdata.l2type_offset + sizeof(struct wpa_eapol_key))) { /* It's a dot1x frame, process it */ handle_dot1x(&cdata, &capdata, &opt); if (cdata.aaset && cdata.spaset && cdata.snonceset && cdata.anonceset && cdata.keymicset && cdata.eapolframeset) { /* We've collected everything we need. */ break; } } } if (!(cdata.aaset && cdata.spaset && cdata.snonceset && cdata.anonceset && cdata.keymicset && cdata.eapolframeset)) { cdata.aaset = 0; cdata.spaset = 0; cdata.snonceset = 0; cdata.anonceset = 0; cdata.keymicset = 0; cdata.eapolframeset = 0; opt.nonstrict = 1; memset(&capdata, 0, sizeof(struct capture_data)); memset(&cdata, 0, sizeof(struct crack_data)); memset(&eapolkey_nomic, 0, sizeof(eapolkey_nomic)); /* Populate capdata struct */ strncpy(capdata.pcapfilename, opt.pcapfile, sizeof(capdata.pcapfilename)); if (openpcap(&capdata) != 0) { printf("Unsupported or unrecognized pcap file.\n"); exit(-1); } /* populates global *packet */ while (getpacket(&capdata) > 0) { if (opt.verbose > 2) { lamont_hdump(packet, h->len); } /* test packet for data that we are looking for */ if (memcmp(&packet[capdata.l2type_offset], DOT1X_LLCTYPE, 2) == 0 && (h->len >capdata.l2type_offset + sizeof(struct wpa_eapol_key))) { /* It's a dot1x frame, process it */ handle_dot1x(&cdata, &capdata, &opt); if (cdata.aaset && cdata.spaset && cdata.snonceset && cdata.anonceset && cdata.keymicset && cdata.eapolframeset) { if (cdata.replay_counter1 != 0 && cdata.replay_counter2 != 0) { if (memcmp (cdata.replay_counter1, cdata.replay_counter2, 8) == 0) { cdata.counters = 1; /* We've collected everything we need. */ break; } } if (cdata.replay_counter3 != 0 && cdata.replay_counter4 != 0) { if (memcmp (cdata.replay_counter3, cdata.replay_counter4, 8) == 0) { cdata.counters = 1; /* We've collected everything we need. */ break; } } } } } } closepcap(&capdata); if (!(cdata.aaset && cdata.spaset && cdata.snonceset && cdata.anonceset && cdata.keymicset && cdata.eapolframeset && cdata.counters)) { printf("End of pcap capture file, incomplete four-way handshake " "exchange. Try using a\ndifferent capture.\n"); exit(-1); } else { if (cdata.ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) { printf("Collected all necessary data to mount crack" " against WPA2/PSK passphrase.\n"); } else if (cdata.ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) { printf("Collected all necessary data to mount crack" " against WPA/PSK passphrase.\n"); } } if (opt.verbose > 1) { dump_all_fields(cdata, &opt); } if (opt.checkonly) { /* Don't attack the PSK, just return non-error return code */ return 0; } /* Zero mic and length data for hmac-md5 calculation */ eapkeypacket = (struct wpa_eapol_key *)&cdata.eapolframe[EAPDOT1XOFFSET]; memset(&eapkeypacket->key_mic, 0, sizeof(eapkeypacket->key_mic)); if (opt.nonstrict == 0) { eapkeypacket->key_data_length = 0; } printf("Starting dictionary attack. Please be patient.\n"); fflush(stdout); signal(SIGINT, cleanup); signal(SIGTERM, cleanup); signal(SIGQUIT, cleanup); gettimeofday(&start, 0); if (!IsBlank(opt.hashfile)) { ret = hashfile_attack(&opt, passphrase, &cdata); } else if (!IsBlank(opt.dictfile)) { ret = dictfile_attack(&opt, passphrase, &cdata); } else { usage("Must specify dictfile or hashfile (-f or -d)"); exit(-1); } if (ret == 0) { printf("\nThe PSK is \"%s\".\n", passphrase); gettimeofday(&end, 0); printstats(start, end, wordstested); return 0; } else { printf("Unable to identify the PSK from the dictionary file. " "Try expanding your\npassphrase list, and double-check" " the SSID. Sorry it didn't work out.\n"); gettimeofday(&end, 0); printstats(start, end, wordstested); return 1; } return 1; }
void AsmInc (const char* Filename, char CommentStart, int IgnoreUnknown) /* Read an assembler include file */ { char Buf[1024]; char* L; const char* Comment; unsigned Line; unsigned Len; long Val; unsigned DVal; int Sign; unsigned Base; unsigned Digits; StrBuf Ident = STATIC_STRBUF_INITIALIZER; /* Try to open the file for reading */ FILE* F = fopen (Filename, "r"); if (F == 0) { Error ("Cannot open asm include file \"%s\": %s", Filename, strerror (errno)); } /* Read line by line, check for NAME = VALUE lines */ Line = 0; while ((L = fgets (Buf, sizeof (Buf), F)) != 0) { /* One more line read */ ++Line; /* Ignore leading white space */ while (IsBlank (*L)) { ++L; } /* Remove trailing whitespace */ Len = strlen (L); while (Len > 0 && IsSpace (L[Len-1])) { --Len; } L[Len] = '\0'; /* If the line is empty or starts with a comment char, ignore it */ if (*L == '\0' || *L == CommentStart) { continue; } /* Read an identifier */ SB_Clear (&Ident); if (IsAlpha (*L) || *L == '_') { SB_AppendChar (&Ident, *L++); while (IsAlNum (*L) || *L == '_') { SB_AppendChar (&Ident, *L++); } SB_Terminate (&Ident); } else { if (!IgnoreUnknown) { Error ("%s(%u): Syntax error", Filename, Line); } continue; } /* Ignore white space */ L = SkipWhitespace (L); /* Check for := or = */ if (*L == '=') { ++L; } else if (*L == ':' && *++L == '=') { ++L; } else { if (!IgnoreUnknown) { Error ("%s(%u): Missing `='", Filename, Line); } continue; } /* Allow white space once again */ L = SkipWhitespace (L); /* A number follows. Read the sign. */ if (*L == '-') { Sign = -1; ++L; } else { Sign = 1; if (*L == '+') { ++L; } } /* Determine the base of the number. Allow $ and % as prefixes for * hex and binary numbers respectively. */ if (*L == '$') { Base = 16; ++L; } else if (*L == '%') { Base = 2; ++L; } else { Base = 10; } /* Decode the number */ Digits = 0; Val = 0; while (IsXDigit (*L) && (DVal = DigitVal (*L)) < Base) { Val = (Val * Base) + DVal; ++Digits; ++L; } /* Must have at least one digit */ if (Digits == 0) { if (!IgnoreUnknown) { Error ("%s(%u): Error in number format", Filename, Line); } continue; } /* Skip whitespace again */ L = SkipWhitespace (L); /* Check for a comment */ if (*L == CommentStart) { Comment = SkipWhitespace (L+1); if (*Comment == '\0') { Comment = 0; } } else { Comment = 0; } /* Check for a comment character or end of line */ if (*L != CommentStart && *L != '\0') { if (!IgnoreUnknown) { Error ("%s(%u): Trailing garbage", Filename, Line); } continue; } /* Apply the sign */ Val *= Sign; /* Define the symbol and the comment */ AddExtLabel (Val, SB_GetConstBuf (&Ident)); SetComment (Val, Comment); } /* Delete the string buffer contents */ SB_Done (&Ident); /* Close the include file ignoring errors (we were just reading). */ (void) fclose (F); }
bool BasisSet::ReadMolDenBasisSet(BufferFile * Buffer, long NumAtoms) { bool result = true; // bool use5D=false, use7F=false, use10G=false; char LineText[kMaxLineLength]; long shellCount = 0; Buffer->SkipnLines(1); for (int i=0; i<NumAtoms; i++) { long shellStart = shellCount; long atomNum=-1; Buffer->GetLine(LineText); sscanf(LineText, "%ld", &atomNum); if (atomNum != (i+1)) return false; //incorrect order? Need to log a message... Buffer->GetLine(LineText); while (!IsBlank(LineText)) { char token[kMaxLineLength]; int numPrims; if (sscanf(LineText, "%s %d", token, &numPrims) == 2) { short ShellType; if (strlen(token) == 1) { switch (toupper(token[0])) { case 'S': ShellType = SShell; break; case 'P': ShellType = PShell; break; case 'D': ShellType = DShell; break; case 'F': ShellType = FShell; break; case 'G': ShellType = GShell; break; case 'H': ShellType = HShell; break; case 'I': ShellType = IShell; break; default: wxString msg; msg.Printf(_("Unknown shell type encountered, shell label = %s"), token); wxLogMessage(msg); return false; //invalid type } } else if (strlen(token) == 2) { if ((toupper(token[0])=='S')&&(toupper(token[1])=='P')) ShellType = -1; else return false; } else return false; //invalid shell type if (numPrims <= 0) return false; BasisShell t; Shells.push_back(t); Shells[shellCount].NumPrims = numPrims; Shells[shellCount].ShellType = ShellType; std::vector<float> & Exponent = Shells[shellCount].Exponent; std::vector<float> & NormCoef = Shells[shellCount].NormCoef; std::vector<float> & InputCoef = Shells[shellCount].InputCoef; Exponent.reserve(numPrims); if (ShellType >= 0) { NormCoef.reserve(numPrims); InputCoef.reserve(numPrims); } else { NormCoef.reserve(2*numPrims); InputCoef.reserve(2*numPrims); } for (long iprim=0; iprim<numPrims; iprim++) { InputCoef.push_back(0.0); NormCoef.push_back(0.0); if (ShellType<0) { InputCoef.push_back(0.0); NormCoef.push_back(0.0); } Exponent.push_back(0.0); } for (long iprim=0; iprim<numPrims; iprim++) { float fexp, fcoef, fcoefp; Buffer->GetLine(LineText); ConvertExponentStyle(LineText); if (ShellType >= 0) { if (sscanf(LineText, "%f %f", &fexp, &fcoef) != 2) return false; } else { if (sscanf(LineText, "%f %f %f", &fexp, &fcoef, &fcoefp) == 3) { InputCoef[iprim+numPrims] = fcoefp; } else return false; } Exponent[iprim] = fexp; InputCoef[iprim] = fcoef; } NumFuncs += Shells[shellCount].GetNumFuncs(false); NumShells ++; shellCount ++; } else return false; Buffer->GetLine(LineText); } BasisMap[2*i] = shellStart; BasisMap[2*i+1] = shellCount - 1; } return result; }
void NextRawTok (void) /* Read the next raw token from the input stream */ { Macro* M; /* If we've a forced end of assembly, don't read further */ if (ForcedEnd) { CurTok.Tok = TOK_EOF; return; } Restart: /* Check if we have tokens from another input source */ if (InputFromStack ()) { if (CurTok.Tok == TOK_IDENT && (M = FindDefine (&CurTok.SVal)) != 0) { /* This is a define style macro - expand it */ MacExpandStart (M); goto Restart; } return; } Again: /* Skip whitespace, remember if we had some */ if ((CurTok.WS = IsBlank (C)) != 0) { do { NextChar (); } while (IsBlank (C)); } /* Mark the file position of the next token */ Source->Func->MarkStart (Source); /* Clear the string attribute */ SB_Clear (&CurTok.SVal); /* Generate line info for the current token */ NewAsmLine (); /* Hex number or PC symbol? */ if (C == '$') { NextChar (); /* Hex digit must follow or DollarIsPC must be enabled */ if (!IsXDigit (C)) { if (DollarIsPC) { CurTok.Tok = TOK_PC; return; } else { Error ("Hexadecimal digit expected"); } } /* Read the number */ CurTok.IVal = 0; while (1) { if (UnderlineInNumbers && C == '_') { while (C == '_') { NextChar (); } if (!IsXDigit (C)) { Error ("Number may not end with underline"); } } if (IsXDigit (C)) { if (CurTok.IVal & 0xF0000000) { Error ("Overflow in hexadecimal number"); CurTok.IVal = 0; } CurTok.IVal = (CurTok.IVal << 4) + DigitVal (C); NextChar (); } else { break; } } /* This is an integer constant */ CurTok.Tok = TOK_INTCON; return; } /* Binary number? */ if (C == '%') { NextChar (); /* 0 or 1 must follow */ if (!IsBDigit (C)) { Error ("Binary digit expected"); } /* Read the number */ CurTok.IVal = 0; while (1) { if (UnderlineInNumbers && C == '_') { while (C == '_') { NextChar (); } if (!IsBDigit (C)) { Error ("Number may not end with underline"); } } if (IsBDigit (C)) { if (CurTok.IVal & 0x80000000) { Error ("Overflow in binary number"); CurTok.IVal = 0; } CurTok.IVal = (CurTok.IVal << 1) + DigitVal (C); NextChar (); } else { break; } } /* This is an integer constant */ CurTok.Tok = TOK_INTCON; return; } /* Number? */ if (IsDigit (C)) { char Buf[16]; unsigned Digits; unsigned Base; unsigned I; long Max; unsigned DVal; /* Ignore leading zeros */ while (C == '0') { NextChar (); } /* Read the number into Buf counting the digits */ Digits = 0; while (1) { if (UnderlineInNumbers && C == '_') { while (C == '_') { NextChar (); } if (!IsXDigit (C)) { Error ("Number may not end with underline"); } } if (IsXDigit (C)) { /* Buf is big enough to allow any decimal and hex number to ** overflow, so ignore excess digits here, they will be detected ** when we convert the value. */ if (Digits < sizeof (Buf)) { Buf[Digits++] = C; } NextChar (); } else { break; } } /* Allow zilog/intel style hex numbers with a 'h' suffix */ if (C == 'h' || C == 'H') { NextChar (); Base = 16; Max = 0xFFFFFFFFUL / 16; } else { Base = 10; Max = 0xFFFFFFFFUL / 10; } /* Convert the number using the given base */ CurTok.IVal = 0; for (I = 0; I < Digits; ++I) { if (CurTok.IVal > Max) { Error ("Number out of range"); CurTok.IVal = 0; break; } DVal = DigitVal (Buf[I]); if (DVal >= Base) { Error ("Invalid digits in number"); CurTok.IVal = 0; break; } CurTok.IVal = (CurTok.IVal * Base) + DVal; } /* This is an integer constant */ CurTok.Tok = TOK_INTCON; return; } /* Control command? */ if (C == '.') { /* Remember and skip the dot */ NextChar (); /* Check if it's just a dot */ if (!IsIdStart (C)) { /* Just a dot */ CurTok.Tok = TOK_DOT; } else { /* Read the remainder of the identifier */ SB_AppendChar (&CurTok.SVal, '.'); ReadIdent (); /* Dot keyword, search for it */ CurTok.Tok = FindDotKeyword (); if (CurTok.Tok == TOK_NONE) { /* Not found */ if (!LeadingDotInIdents) { /* Invalid pseudo instruction */ Error ("'%m%p' is not a recognized control command", &CurTok.SVal); goto Again; } /* An identifier with a dot. Check if it's a define style ** macro. */ if ((M = FindDefine (&CurTok.SVal)) != 0) { /* This is a define style macro - expand it */ MacExpandStart (M); goto Restart; } /* Just an identifier with a dot */ CurTok.Tok = TOK_IDENT; } } return; } /* Indirect op for sweet16 cpu. Must check this before checking for local ** symbols, because these may also use the '@' symbol. */ if (CPU == CPU_SWEET16 && C == '@') { NextChar (); CurTok.Tok = TOK_AT; return; } /* Local symbol? */ if (C == LocalStart) { /* Read the identifier. */ ReadIdent (); /* Start character alone is not enough */ if (SB_GetLen (&CurTok.SVal) == 1) { Error ("Invalid cheap local symbol"); goto Again; } /* A local identifier */ CurTok.Tok = TOK_LOCAL_IDENT; return; } /* Identifier or keyword? */ if (IsIdStart (C)) { /* Read the identifier */ ReadIdent (); /* Check for special names. Bail out if we have identified the type of ** the token. Go on if the token is an identifier. */ switch (SB_GetLen (&CurTok.SVal)) { case 1: switch (toupper (SB_AtUnchecked (&CurTok.SVal, 0))) { case 'A': if (C == ':') { NextChar (); CurTok.Tok = TOK_OVERRIDE_ABS; } else { CurTok.Tok = TOK_A; } return; case 'F': if (C == ':') { NextChar (); CurTok.Tok = TOK_OVERRIDE_FAR; return; } break; case 'S': if ((CPU == CPU_4510) || (CPU == CPU_65816)) { CurTok.Tok = TOK_S; return; } break; case 'X': CurTok.Tok = TOK_X; return; case 'Y': CurTok.Tok = TOK_Y; return; case 'Z': if (C == ':') { NextChar (); CurTok.Tok = TOK_OVERRIDE_ZP; return; } else { if (CPU == CPU_4510) { CurTok.Tok = TOK_Z; return; } } break; default: break; } break; case 2: if ((CPU == CPU_4510) && (toupper (SB_AtUnchecked (&CurTok.SVal, 0)) == 'S') && (toupper (SB_AtUnchecked (&CurTok.SVal, 1)) == 'P')) { CurTok.Tok = TOK_S; return; } /* FALL THROUGH */ default: if (CPU == CPU_SWEET16 && (CurTok.IVal = Sweet16Reg (&CurTok.SVal)) >= 0) { /* A sweet16 register number in sweet16 mode */ CurTok.Tok = TOK_REG; return; } } /* Check for define style macro */ if ((M = FindDefine (&CurTok.SVal)) != 0) { /* Macro - expand it */ MacExpandStart (M); goto Restart; } else { /* An identifier */ CurTok.Tok = TOK_IDENT; } return; } /* Ok, let's do the switch */ CharAgain: switch (C) { case '+': NextChar (); CurTok.Tok = TOK_PLUS; return; case '-': NextChar (); CurTok.Tok = TOK_MINUS; return; case '/': NextChar (); if (C != '*') { CurTok.Tok = TOK_DIV; } else if (CComments) { /* Remember the position, then skip the '*' */ Collection LineInfos = STATIC_COLLECTION_INITIALIZER; GetFullLineInfo (&LineInfos); NextChar (); do { while (C != '*') { if (C == EOF) { LIError (&LineInfos, "Unterminated comment"); ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); goto CharAgain; } NextChar (); } NextChar (); } while (C != '/'); NextChar (); ReleaseFullLineInfo (&LineInfos); DoneCollection (&LineInfos); goto Again; } return; case '*': NextChar (); CurTok.Tok = TOK_MUL; return; case '^': NextChar (); CurTok.Tok = TOK_XOR; return; case '&': NextChar (); if (C == '&') { NextChar (); CurTok.Tok = TOK_BOOLAND; } else { CurTok.Tok = TOK_AND; } return; case '|': NextChar (); if (C == '|') { NextChar (); CurTok.Tok = TOK_BOOLOR; } else { CurTok.Tok = TOK_OR; } return; case ':': NextChar (); switch (C) { case ':': NextChar (); CurTok.Tok = TOK_NAMESPACE; break; case '-': CurTok.IVal = 0; do { --CurTok.IVal; NextChar (); } while (C == '-'); CurTok.Tok = TOK_ULABEL; break; case '+': CurTok.IVal = 0; do { ++CurTok.IVal; NextChar (); } while (C == '+'); CurTok.Tok = TOK_ULABEL; break; case '=': NextChar (); CurTok.Tok = TOK_ASSIGN; break; default: CurTok.Tok = TOK_COLON; break; } return; case ',': NextChar (); CurTok.Tok = TOK_COMMA; return; case ';': NextChar (); while (C != '\n' && C != EOF) { NextChar (); } goto CharAgain; case '#': NextChar (); CurTok.Tok = TOK_HASH; return; case '(': NextChar (); CurTok.Tok = TOK_LPAREN; return; case ')': NextChar (); CurTok.Tok = TOK_RPAREN; return; case '[': NextChar (); CurTok.Tok = TOK_LBRACK; return; case ']': NextChar (); CurTok.Tok = TOK_RBRACK; return; case '{': NextChar (); CurTok.Tok = TOK_LCURLY; return; case '}': NextChar (); CurTok.Tok = TOK_RCURLY; return; case '<': NextChar (); if (C == '=') { NextChar (); CurTok.Tok = TOK_LE; } else if (C == '<') { NextChar (); CurTok.Tok = TOK_SHL; } else if (C == '>') { NextChar (); CurTok.Tok = TOK_NE; } else { CurTok.Tok = TOK_LT; } return; case '=': NextChar (); CurTok.Tok = TOK_EQ; return; case '!': NextChar (); CurTok.Tok = TOK_BOOLNOT; return; case '>': NextChar (); if (C == '=') { NextChar (); CurTok.Tok = TOK_GE; } else if (C == '>') { NextChar (); CurTok.Tok = TOK_SHR; } else { CurTok.Tok = TOK_GT; } return; case '~': NextChar (); CurTok.Tok = TOK_NOT; return; case '\'': /* Hack: If we allow ' as terminating character for strings, read ** the following stuff as a string, and check for a one character ** string later. */ if (LooseStringTerm) { ReadStringConst ('\''); if (SB_GetLen (&CurTok.SVal) == 1) { CurTok.IVal = SB_AtUnchecked (&CurTok.SVal, 0); CurTok.Tok = TOK_CHARCON; } else { CurTok.Tok = TOK_STRCON; } } else { /* Always a character constant */ NextChar (); if (C == EOF || IsControl (C)) { Error ("Illegal character constant"); goto CharAgain; } CurTok.IVal = C; CurTok.Tok = TOK_CHARCON; NextChar (); if (C != '\'') { if (!MissingCharTerm) { Error ("Illegal character constant"); } } else { NextChar (); } } return; case '\"': ReadStringConst ('\"'); CurTok.Tok = TOK_STRCON; return; case '\\': /* Line continuation? */ if (LineCont) { NextChar (); /* Next char should be a LF, if not, will result in an error later */ if (C == '\n') { /* Ignore the '\n' */ NextChar (); goto Again; } else { /* Make it clear what the problem is: */ Error ("EOL expected."); } } break; case '\n': NextChar (); CurTok.Tok = TOK_SEP; return; case EOF: CheckInputStack (); /* In case of the main file, do not close it, but return EOF. */ if (Source && Source->Next) { DoneCharSource (); goto Again; } else { CurTok.Tok = TOK_EOF; } return; } /* If we go here, we could not identify the current character. Skip it ** and try again. */ Error ("Invalid input character: 0x%02X", C & 0xFF); NextChar (); goto Again; }
int CBoxScript::ParseScriptText(LPCSTR pstrText, int nCount, CStringA& strScriptText, int nIncludeFlagIndex) { CStringA strTempText; if(nCount >= 2 && (BYTE)pstrText[0] == 0xff && (BYTE)pstrText[1] == 0xfe) { /* int _nTempCount = WideCharToMultiByte(_AtlGetConversionACP(), 0, LPWSTR(pstrText + 2), (nCount - 2) / 2, NULL, 0, NULL, NULL); LPSTR _pstr = strTempText.GetBuffer(_nTempCount); WideCharToMultiByte(_AtlGetConversionACP(), 0, LPWSTR(pstrText + 2), (nCount - 2) / 2, _pstr, _nTempCount, NULL, NULL); strTempText.ReleaseBuffer(_nTempCount); */ //发现是Unicode则检查是否已经存在CodePage,存在就转换到当前CodePage,否则转换成UTF8同时设定m_CodePage为65001 if (m_uiCodePage == 0) m_uiCodePage = CP_UTF8; int _nTempCount = WideCharToMultiByte(m_uiCodePage, 0, LPWSTR(pstrText + 2), (nCount - 2) / 2, NULL, 0, NULL, NULL); LPSTR _pstr = strTempText.GetBuffer(_nTempCount); WideCharToMultiByte(m_uiCodePage, 0, LPWSTR(pstrText + 2), (nCount - 2) / 2, _pstr, _nTempCount, NULL, NULL); strTempText.ReleaseBuffer(_nTempCount); pstrText = strTempText; nCount = strTempText.GetLength(); } else if(nCount >= 3 && (BYTE)pstrText[0] == 0xEF && (BYTE)pstrText[1] == 0xBB && (BYTE)pstrText[2] == 0xBF) { pstrText += 3; nCount -= 3; if (m_uiCodePage && m_uiCodePage != CP_UTF8) { CStringW strTempTextW; int _nTempCount = MultiByteToWideChar(CP_UTF8, 0, pstrText, nCount, NULL, 0); LPWSTR _pstrW = strTempTextW.GetBuffer(_nTempCount); MultiByteToWideChar(CP_UTF8, 0, pstrText, nCount, _pstrW, _nTempCount); strTempTextW.ReleaseBuffer(_nTempCount); _nTempCount = WideCharToMultiByte(m_uiCodePage, 0, strTempTextW, strTempTextW.GetLength(), NULL, 0, NULL, NULL); LPSTR _pstr = strTempText.GetBuffer(_nTempCount); WideCharToMultiByte(m_uiCodePage, 0, strTempTextW, strTempTextW.GetLength(), _pstr, _nTempCount, NULL, NULL); strTempText.ReleaseBuffer(_nTempCount); pstrText = strTempText; nCount = strTempText.GetLength(); } else m_uiCodePage = CP_UTF8; } else { UINT uiCodePage = ParseScriptTextCodePage(pstrText, nCount); if (uiCodePage == 0) uiCodePage = GetACP(); //if (m_uiCodePage == 0) // m_uiCodePage = CP_UTF8; if (m_uiCodePage && m_uiCodePage != uiCodePage) { CStringW strTempTextW; int _nTempCount = MultiByteToWideChar(uiCodePage, 0, pstrText, nCount, NULL, 0); LPWSTR _pstrW = strTempTextW.GetBuffer(_nTempCount); MultiByteToWideChar(uiCodePage, 0, pstrText, nCount, _pstrW, _nTempCount); strTempTextW.ReleaseBuffer(_nTempCount); _nTempCount = WideCharToMultiByte(m_uiCodePage, 0, strTempTextW, strTempTextW.GetLength(), NULL, 0, NULL, NULL); LPSTR _pstr = strTempText.GetBuffer(_nTempCount); WideCharToMultiByte(m_uiCodePage, 0, strTempTextW, strTempTextW.GetLength(), _pstr, _nTempCount, NULL, NULL); strTempText.ReleaseBuffer(_nTempCount); pstrText = strTempText; nCount = strTempText.GetLength(); } else { m_uiCodePage = uiCodePage; } } static struct { char *pstrName; int nSize; }CmdName[] = { {"#include", 8}, {"#language", 9}, {"#debug", 6}, {"#timeout", 8}, {"#transaction", 12}, {"#codepage", 9} }; #define CMD_COUNT (sizeof(CmdName) / sizeof(CmdName[0])) int i; LPCSTR pstrTemp, pstrTemp1; int nTempCount; int nLineCount = 1; while(nCount > 0 && IsBlank(pstrText[0])) { if(pstrText[0] == '\n') nLineCount ++; pstrText ++; nCount --; } while(nCount > 0 && pstrText[0] == '#') { for(i = 0; i < CMD_COUNT; i ++) if(nCount > CmdName[i].nSize && !_strnicmp(pstrText, CmdName[i].pstrName, CmdName[i].nSize) && IsBlankChar(pstrText[CmdName[i].nSize])) break; if(i == CMD_COUNT) break; pstrText += CmdName[i].nSize; nCount -= CmdName[i].nSize; while(nCount > 0 && IsBlankChar(pstrText[0])) { pstrText ++; nCount --; } if(nCount > 0 && pstrText[0] == '\"') { pstrText ++; nCount --; } pstrTemp = pstrText; nTempCount = nCount; while(nTempCount > 0 && !IsLineChar(pstrTemp[0])) { pstrTemp ++; nTempCount --; } pstrTemp1 = pstrTemp; while(pstrTemp1 > pstrText && IsBlankChar(pstrTemp1[0])) pstrTemp1 --; if(pstrTemp1 > pstrText && pstrTemp1[-1] == '\"') pstrTemp1 --; CStringA strValue; strValue.SetString(pstrText, (int)(pstrTemp1 - pstrText)); pstrText = pstrTemp; nCount = nTempCount; switch(i) { case 0: strValue.MakeLower(); if(LoadScriptFile(BOX_CA2CT(strValue), strScriptText, nLineCount)) return 500; break; case 1: m_strLanguage = strValue; break; case 2: m_bEnableDebug = !strValue.CompareNoCase("on") || !strValue.CompareNoCase("true"); if(!strValue.CompareNoCase("step")) m_bStepDebug = TRUE; break; case 3: m_pHost->m_nTimeout = atoi(strValue); break; case 4: if(!strValue.CompareNoCase("Required")) m_nTransaction = 3; else if(!strValue.CompareNoCase("Requires_New")) m_nTransaction = 2; else if(!strValue.CompareNoCase("Supported")) m_nTransaction = 1; else if(!strValue.CompareNoCase("Not_Supported")) m_nTransaction = 0; break; case 5: //(uiCodePage) break; } while(nCount > 0 && IsBlank(pstrText[0])) { if(pstrText[0] == '\n') nLineCount ++; pstrText ++; nCount --; } } AddLineMap(nIncludeFlagIndex, nLineCount); strScriptText.Append(pstrText, nCount); strScriptText += _T("\r\n"); m_nScriptLine ++; pstrTemp = pstrText; nTempCount = nCount; while(nTempCount > 0) { if(pstrTemp[0] == '\n') m_nScriptLine ++; pstrTemp ++; nTempCount --; } return 0; }
int BPA_DYNAMICMODELINFO::Area_ReadBPALine(char* PFLine) { int i, k, AreaNo; float BaseKv; char Name[_MaxNameLen], Zone[_MaxNameLen], tArea[_MaxNameLen]; GetItemFromLine(PFLine, tArea, AREA_Para[0], AREA_Loca[0]); ReplaceName(tArea, _MaxNameLen); tArea[_MaxNameLen - 1] = '\0'; if (strlen(PFLine) > 3 && PFLine[2] == '+') {//续卡 k = cpGetAreaInfo()->iGetAreaNo(tArea); if (k >= cpGetAreaInfo()->iGetAreaTotal()) { sprintf(ErrorMessage[0], "A+卡没有对应的A卡 '%s' 不存在, 忽略该卡:", tArea); strcpy(ErrorMessage[1], PFLine); cpGetErrorInfo()->PrintWarning(0, 2); return 0; } AreaNo = k; } else{ AREABASE *tempArea; tempArea = new AREABASE; tempArea->ZoneTotal = 0; GetItemFromLine(PFLine, Name, AREA_Para[1], AREA_Loca[1]); GetItemFromLine(PFLine, &BaseKv, AREA_Para[2], AREA_Loca[2]); if (BaseKv<0 || BaseKv>99999.) { sprintf(ErrorMessage[0], " 节点 %s的基准电压为0,程序缺省将其设为100.0KV", Name); cpGetErrorInfo()->PrintWarning(0, 1); BaseKv = 100.0f; } ReplaceName(Name, _MaxNameLen); ResetBPAName(Name, BaseKv); strcpy(tempArea->SlackBusName, Name); strcpy(tempArea->AreaName, tArea); GetItemFromLine(PFLine, &(tempArea->AreaPower), AREA_Para[3], AREA_Loca[3]); AreaNo = cpGetAreaInfo()->AddNewArea(tempArea); if (AreaNo < 0) { sprintf(ErrorMessage[0], "区域数目超过设定值%d,忽略该卡:", _MaxAreaNo); strcpy(ErrorMessage[1], PFLine); cpGetErrorInfo()->PrintWarning(6, 2); return 0; } } i = 0; while ((int)(strlen(PFLine)) > (AREA_Loca[4] + 3 * i + 2)) {//这个地方能不限制长度,只要有就可以继续读入 GetItemFromLine(PFLine, Zone, AREA_Para[4], AREA_Loca[4] + 3 * i); i++; if (IsBlank(Zone, _MaxNameLen))continue; if (cpGetAreaInfo()->cpGetArea(AreaNo)->ZoneTotal >= _MaxAreaZoneNo) { sprintf(ErrorMessage[0], "区域%s数目超过设定值%d,忽略多余的Zone:%s", cpGetAreaInfo()->cpGetArea(AreaNo)->ZoneName, _MaxAreaZoneNo, Zone); cpGetErrorInfo()->PrintWarning(0, 1); continue; } strcpy(cpGetAreaInfo()->cpGetArea(AreaNo)->ZoneName[cpGetAreaInfo()->cpGetArea(AreaNo)->ZoneTotal], Zone); cpGetAreaInfo()->cpGetArea(AreaNo)->ZoneTotal++; } return 1; }
bool ElfParser::ParseFileText( const QStringList &strs, const QStringList §ionStrs, const QStringList &symbolStrs, ElfParser::File &file ) { quint32 cnt = strs.size(); quint32 fOff = 0; quint32 fStart = 0; QString name; QString pattern; QList< SymRef > refs; //DBG << file.Name() << sectionStrs.size() << symbolStrs.size() << strs.size(); QMap< QString, QByteArray >sections = ParseSectionText( sectionStrs ); QList< SymAlias > aliases = ParseSymbolTable( symbolStrs ); //DBG << file.Name() << sections.size() << aliases.size(); for( quint32 i = 0; i < cnt; i++ ) { const QString &str = strs.at( i ); /*if( name == "WII_Initialize" ) { qDebug() << str; }*/ // start a new funciton if( IsFunctionStart( str, &fStart ) ) { // add this function to the list if( !name.isEmpty() && fOff ) { Function fun( name ); fun.references = refs; fun.pattern = pattern; fun.file = &file; file.functions << fun; //qDebug() << "pattern:" << pattern; } //qDebug() << GetFunctionName( str ); name = GetFunctionName( str ); //DBG << name; if( fOff != (quint32)pattern.size() / 2 ) { qDebug() << "size bad"; exit( 0 ); } fOff = 0; pattern.clear(); refs.clear(); sections.remove( name );// remove functions from the section list continue; } if( name.isEmpty() ) { continue; } if( IsBlank( str ) ) { //qDebug() << str << "is blank"; continue; } if( IsSymbolLine( str ) ) { //qDebug() << str << "IsSymbolLine"; continue; } QString hex; QString oper; QString symbol; quint32 refOff = 0xdeadbeef; if( !ParseOpLine( str, hex, oper ) ) { qDebug() << str << strs.at( i - 1 ); return false; } /*if( name == "WII_Initialize" ) { qDebug() << "hex" << hex; }*/ if( ( i < cnt - 1 ) && IsSymbolLine( strs.at( i + 1 ) ) ) { SymRef::Type refType; symbol = GetNonOperRef( strs.at( i + 1 ), &refOff, &refType ); if( refOff < fStart ) { WRN << "refOff < fStart" << str; return false; } SymRef ref; quint32 deRef; ref.name = DeReferenceSymbol( symbol, &deRef ); ref.symOff = deRef; switch( refType ) { case SymRef::R_PPC_ADDR16_HA: case SymRef::R_PPC_ADDR16_HI: case SymRef::R_PPC_ADDR16_LO: { hex[ 4 ] = '.'; hex[ 5 ] = '.'; hex[ 6 ] = '.'; hex[ 7 ] = '.'; } break; case SymRef::R_PPC_REL24: case SymRef::R_PPC_EMB_SDA21: { hex[ 1 ] = '.'; hex[ 2 ] = '.'; hex[ 3 ] = '.'; hex[ 4 ] = '.'; hex[ 5 ] = '.'; hex[ 6 ] = '.'; hex[ 7 ] = '.'; } break; case SymRef::R_PPC_SDAREL16: { hex = "........"; } break; default: WRN << "unhandled reference type"; return false; break; } ref.type = refType; ref.off = refOff - fStart; refs << ref; if( ref.off & 0xff000000 ) { qDebug() << "ref.off is busted 1" << name << str; qDebug() << ::hex << refOff << fStart; exit( 0 ); } } else if( OpNeedsWildCard( oper ) ) { //DBG << "bl called without symbol reference\n" << str; hex = "........"; if( symbol.isEmpty() ) { symbol = GetOpersymRef( str ); } SymRef ref; ref.name = symbol; ref.off = (quint32)(pattern.size()); ref.type = SymRef::R_PPC_REL24; refs << ref; if( ref.off & 0xff000000 ) { DBG << "ref.off is busted 2" << name << str; exit( 0 ); } } pattern += hex.toUpper(); /*if( name == "WII_Initialize" ) { qDebug() << "hex" << pattern; }*/ fOff += 4; } if( !name.isEmpty() ) { Function fun( name ); fun.references = refs; fun.pattern = pattern; fun.file = &file; file.functions << fun; } file.sections = sections; file.aliases = aliases; return true; }
bool Parser::FeedChar(Environment &env, char ch) { BeginPushbackRegion(ch); //::printf("%p ch=%c, stat=%d\n", this, ch, _stat); switch (_stat) { case STAT_Init: { if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0') { // nothing to do } else { Pushback(ch); _str.clear(); _stat = STAT_String; } break; } case STAT_String: { if (ch == '\0') { FlushElemString(_str.c_str()); _str.clear(); } else if (IsCommandMark(ch)) { _cmdName.clear(); _stat = STAT_AcceptCommandInString; } else { _str += ch; } break; } case STAT_AcceptCommandInString: { if (IsCommandEnd(_cmdName, ch)) { if (_cmdName.empty()) { env.SetError(ERR_SyntaxError, "command name is not specified"); return false; } const CommandFormat *pCmdFmt = CommandFormat::Lookup(_cmdName.c_str()); if (pCmdFmt == nullptr) { // custom command FlushElemString(_str.c_str()); _stat = STAT_CommandCustom; } else { // special command if (pCmdFmt->IsVisual() || !IsBlank(_str.c_str())) { FlushElemString(_str.c_str()); } _pElemCmdCur.reset(new Elem_Command(pCmdFmt)); _stat = STAT_CommandSpecial; } _str.clear(); Pushback(ch); } else { _cmdName += ch; } break; } case STAT_AcceptCommandInArgLine: case STAT_AcceptCommandInArgPara: { if (_pParserChild.get() != nullptr) { if (!_pParserChild->FeedChar(env, ch)) return false; if (_pParserChild->IsComplete()) { AutoPtr<Elem_Text> pElemResult( new Elem_Text(_pParserChild->GetElemOwner().Reference())); _pElemArg->GetElemChildren().AddElem(pElemResult->ReduceContent()->Reference()); _pParserChild.reset(); _stat = (_stat == STAT_AcceptCommandInArgLine)? STAT_ArgLine : STAT_ArgPara; } } else if (IsCommandEnd(_cmdName, ch)) { if (_cmdName.empty()) { env.SetError(ERR_SyntaxError, "command name is not specified"); return false; } const CommandFormat *pCmdFmt = CommandFormat::Lookup(_cmdName.c_str()); if (pCmdFmt == nullptr) { // custom command _pParserChild.reset(new Parser(_pAliases, this)); _pParserChild->SetCommandCustom(_cmdName.c_str()); Pushback(ch); } else if (pCmdFmt->IsSectionIndicator()) { if (_stat == STAT_AcceptCommandInArgLine || _stat == STAT_AcceptCommandInArgCustom) { env.SetError(ERR_SyntaxError, "section indicator can not appear in line argument"); return false; } // finish the previous command if (!_strArg.empty()) { _pElemArg->GetElemChildren().AddElem(new Elem_String(_strArg)); _strArg.clear(); } _pElemCmdCur->GetElemArgs().AddElem(_pElemArg->ReduceContent()->Reference()); FlushElemCommand(_pElemCmdCur.release()); // special command (section indicator) _pElemCmdCur.reset(new Elem_Command(pCmdFmt)); Pushback(ch); _stat = STAT_CommandSpecial; } else { // special command (not section indicator) _pParserChild.reset(new Parser(_pAliases, this)); _pParserChild->SetCommandSpecial(pCmdFmt); } } else { _cmdName += ch; } break; } case STAT_AcceptCommandInArgCustom: { if (_pParserChild.get() != nullptr) { if (!_pParserChild->FeedChar(env, ch)) return false; if (_pParserChild->IsComplete()) { _strArg += _pParserChild->GetString(); _pParserChild.reset(); _stat = STAT_ArgCustom; } } else if (IsCommandEnd(_cmdName, ch)) { if (_cmdName.empty()) { env.SetError(ERR_SyntaxError, "command name is not specified"); return false; } const CommandFormat *pCmdFmt = CommandFormat::Lookup(_cmdName.c_str()); if (pCmdFmt == nullptr) { // custom command _pParserChild.reset(new Parser(_pAliases, this)); _pParserChild->SetCommandCustom(_cmdName); Pushback(ch); } else { // special command _strArg += _chAhead; _strArg += _cmdName; _stat = STAT_ArgCustom; } } else { _cmdName += ch; } break; } case STAT_CommandSpecial: { Pushback(ch); _strArg.clear(); _stat = STAT_NextArg; break; } case STAT_NextArg: { if (_pElemCmdCur->HasCompletedArg()) { FlushElemCommand(_pElemCmdCur.release()); Pushback(ch); _str.clear(); _stat = IsTopLevel()? STAT_String : STAT_Complete; break; } const CommandFormat::Arg *pArg = _pElemCmdCur->GetCurrentArg(); Pushback(ch); _stat = (pArg->IsWord() || pArg->IsWordOpt())? STAT_ArgWordPre : pArg->IsBracket()? STAT_ArgBracketPre : (pArg->IsLine() || pArg->IsLineOpt())? STAT_ArgLinePre : (pArg->IsQuote() || pArg->IsQuoteOpt())? STAT_ArgQuotePre : (pArg->IsBrace() || pArg->IsBraceOpt())? STAT_ArgBracePre : pArg->IsPara()? STAT_ArgParaPre : STAT_Complete; // this must not happen break; } case STAT_ArgWordPre: { if (ch == ' ' || ch == '\t') { // nothing to do } else if (ch == '\n' || ch == '\0' || IsCommandMark(ch)) { const CommandFormat::Arg *pArg = _pElemCmdCur->GetCurrentArg(); if (pArg->IsWord()) { env.SetError(ERR_SyntaxError, "argument %s doesn't exist", pArg->GetName()); return false; } Pushback(ch); _pElemCmdCur->GetElemArgs().AddElem(new Elem_Empty()); _stat = STAT_NextArg; } else if (ch == '"') { _strArg.clear(); _stat = STAT_ArgWordQuote; } else { _strArg.clear(); Pushback(ch); _stat = STAT_ArgWord; } break; } case STAT_ArgWord: { if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0' || IsCommandMark(ch)) { Pushback(ch); _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else if (ch == '.' || ch == ',' || ch == ';' || ch == '?' || ch == '!') { _chAhead = ch; _stat = STAT_ArgWord_Punctuation; } else { _strArg += ch; } break; } case STAT_ArgWord_Punctuation: { if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0' || IsCommandMark(ch)) { Pushback(ch); Pushback(_chAhead); _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else { Pushback(ch); _strArg += _chAhead; _stat = STAT_ArgWord; } break; } case STAT_ArgWordQuote: { if (ch == '\n' || ch == '\0') { Pushback(ch); _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else if (ch == '"') { _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else { _strArg += ch; } break; } case STAT_ArgBracketPre: { if (ch == ' ' || ch == '\t') { // nothing to do } else if (ch == '[') { _strArg.clear(); _stat = STAT_ArgBracket; } else { // including '\0' Pushback(ch); _pElemCmdCur->GetElemArgs().AddElem(new Elem_Empty()); _stat = STAT_NextArg; } break; } case STAT_ArgBracket: { if (ch == '\n' || ch == '\0' || IsCommandMark(ch)) { env.SetError(ERR_SyntaxError, "unmatched brakcet mark"); return false; } else if (ch == ']') { _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else { _strArg += ch; } break; } case STAT_ArgLinePre: { if (ch == ' ' || ch == '\t') { // nothing to do } else { _pElemArg.reset(new Elem_Text()); Pushback(ch); _strArg.clear(); _stat = STAT_ArgLine; } break; } case STAT_ArgLine: { if (ch == '\n' || ch == '\0') { if (ch == '\0') Pushback(ch); String str = Strip(_strArg.c_str()); if (!str.empty()) { _pElemArg->GetElemChildren().AddElem(new Elem_String(str)); } _strArg.clear(); _pElemCmdCur->GetElemArgs().AddElem(_pElemArg->ReduceContent()->Reference()); _stat = STAT_NextArg; } else if (IsCommandMark(ch)) { String str = Strip(_strArg.c_str()); if (!str.empty()) { _pElemArg->GetElemChildren().AddElem(new Elem_String(str)); } _strArg.clear(); _cmdName.clear(); _stat = STAT_AcceptCommandInArgLine; } else { _strArg += ch; } break; } case STAT_ArgQuotePre: { if (ch == ' ' || ch == '\t') { // nothing to do } else if (ch == '"') { _strArg.clear(); _stat = STAT_ArgQuote; } else { // including '\0' const CommandFormat::Arg *pArg = _pElemCmdCur->GetCurrentArg(); if (pArg->IsQuote()) { env.SetError(ERR_SyntaxError, "quoted string is expected"); return false; } Pushback(ch); if (_chPrev == ' ' || _chPrev == '\t') Pushback(_chPrev); _pElemCmdCur->GetElemArgs().AddElem(new Elem_Empty()); _stat = STAT_NextArg; } break; } case STAT_ArgQuote: { if (ch == '\n' || ch == '\0') { env.SetError(ERR_SyntaxError, "quoted string doesn't end correctly"); return false; } else if (ch == '"') { _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else { _strArg += ch; } break; } case STAT_ArgBracePre: { if (ch == ' ' || ch == '\t') { // nothing to do } else if (ch == '{') { _strArg.clear(); _stat = STAT_ArgBrace; } else { // include '\0' const CommandFormat::Arg *pArg = _pElemCmdCur->GetCurrentArg(); if (pArg->IsBrace()) { env.SetError(ERR_SyntaxError, "braced string is expected"); return false; } Pushback(ch); _pElemCmdCur->GetElemArgs().AddElem(new Elem_Empty()); _stat = STAT_NextArg; } break; } case STAT_ArgBrace: { if (ch == '\n' || ch == '\0') { env.SetError(ERR_SyntaxError, "braced string doesn't end correctly"); return false; } else if (ch == '}') { _pElemCmdCur->GetElemArgs().AddElem(new Elem_String(_strArg)); _strArg.clear(); _stat = STAT_NextArg; } else { _strArg += ch; } break; } case STAT_ArgParaPre: { if (ch == ' ' || ch == '\t') { // nothing to do } else { _pElemArg.reset(new Elem_Text()); Pushback(ch); _strArg.clear(); _stat = STAT_ArgPara; } break; } case STAT_ArgPara: { if (ch == '\n') { _strArg += ch; _strAhead.clear(); _stat = STAT_ArgParaNewline; } else if (ch == '\0') { Pushback(ch); if (!_strArg.empty()) { _pElemArg->GetElemChildren().AddElem(new Elem_String(_strArg)); _strArg.clear(); } _pElemCmdCur->GetElemArgs().AddElem(_pElemArg->ReduceContent()->Reference()); _stat = STAT_NextArg; } else if (IsCommandMark(ch)) { if (!_strArg.empty()) { _pElemArg->GetElemChildren().AddElem(new Elem_String(_strArg)); _strArg.clear(); } _cmdName.clear(); _stat = STAT_AcceptCommandInArgPara; } else { _strArg += ch; } break; } case STAT_ArgParaNewline: { if (ch == '\n') { // detected a blank line if (!_strArg.empty()) { _pElemArg->GetElemChildren().AddElem(new Elem_String(_strArg)); _strArg.clear(); } _pElemCmdCur->GetElemArgs().AddElem(_pElemArg->ReduceContent()->Reference()); _stat = STAT_NextArg; } else if (ch == ' ' || ch == '\t') { _strAhead += ch; } else { // including '\0' _strArg += _strAhead; Pushback(ch); _stat = STAT_ArgPara; } break; } case STAT_CommandCustom: { if (ch == '{') { _strArg.clear(); _stat = STAT_ArgCustom; } else { _strArg.clear(); String rtn = EvaluateCustomCommand(env); if (env.IsSignalled()) return false; _strArgs.clear(); _strArg.clear(); _str.clear(); _stat = STAT_String; foreach (String, p, rtn) { if (!FeedChar(env, *p)) return false; } if (!IsTopLevel()) _stat = STAT_Complete; Pushback(ch); } break; } case STAT_ArgCustom: { if (ch == '}') { _strArgs.push_back(_strArg); String rtn = EvaluateCustomCommand(env); if (env.IsSignalled()) return false; _strArgs.clear(); _strArg.clear(); _str.clear(); _stat = STAT_String; foreach (String, p, rtn) { if (!FeedChar(env, *p)) return false; } if (!IsTopLevel()) _stat = STAT_Complete; } else if (ch == ',') { _strArgs.push_back(_strArg); _strArg.clear(); } else if (ch == '\\') { _stat = STAT_ArgCustom_Backslash; } else if (IsCommandMark(ch)) { _cmdName.clear(); _chAhead = ch; _stat = STAT_AcceptCommandInArgCustom; } else if (ch == '\0') { // nothing to do } else { _strArg += ch; } break; }
void parseopts(struct user_opt *opt, int argc, char **argv) { int c; #ifdef FPGA while ((c = getopt(argc, argv, "f:r:s:d:hF:vV")) != EOF) { #else while ((c = getopt(argc, argv, "f:r:s:d:hvV")) != EOF) { #endif switch (c) { case 'f': strncpy(opt->dictfile, optarg, sizeof(opt->dictfile)); break; case 'r': strncpy(opt->pcapfile, optarg, sizeof(opt->pcapfile)); break; case 's': strncpy(opt->ssid, optarg, sizeof(opt->ssid)); break; case 'd': strncpy(opt->hashfile, optarg, sizeof(opt->hashfile)); break; case 'h': usage(""); exit(0); break; #ifdef FPGA case 'F': piconum = atoi(optarg); picodev = NULL; usefpga = 1; break; #endif case 'v': opt->verbose++; break; case 'V': printf ("$Id: cowpatty.c,v 1.2 2007-08-20 01:49:19 jspence Exp $\n"); exit(0); break; default: usage(""); exit(1); } } } void testopts(struct user_opt *opt) { struct stat teststat; /* test for required parameters */ if (IsBlank(opt->dictfile) && IsBlank(opt->hashfile)) { usage("Must supply a list of passphrases in a file with -f " "or a hash file\n\t with -d. " "Use \"-f -\" to accept words on stdin."); exit(1); } if (IsBlank(opt->ssid)) { usage("Must supply the SSID for the network with -s"); exit(1); } if (IsBlank(opt->pcapfile)) { usage("Must supply a pcap file with -r"); exit(1); } /* Test that the files specified exist and are greater than 0 bytes */ if (!IsBlank(opt->hashfile)) { if (stat(opt->hashfile, &teststat)) { usage("Could not stat hashfile. Check file path."); exit(1); } else if (teststat.st_size == 0) { usage("Empty hashfile (0 bytes). Check file contents."); exit(1); } } if (!IsBlank(opt->dictfile) && strncmp(opt->dictfile, "-", 1) != 0) { if (stat(opt->dictfile, &teststat)) { usage ("Could not stat the dictionary file. Check file path."); exit(1); } else if (teststat.st_size == 0) { usage ("Empty dictionary file (0 bytes). Check file contents."); exit(1); } } if (stat(opt->pcapfile, &teststat)) { usage("Could not stat the pcap file. Check file path."); exit(1); } else if (teststat.st_size == 0) { usage("Empty pcap file (0 bytes). Check file contents."); exit(1); } } int openpcap(struct capture_data *capdata) { /* Assume for now it's a libpcap file */ p = pcap_open_offline(capdata->pcapfilename, errbuf); if (p == NULL) { perror("Unable to open capture file"); return (-1); } /* Determine link type */ capdata->pcaptype = pcap_datalink(p); /* Determine offset to EAP frame based on link type */ switch (capdata->pcaptype) { case DLT_NULL: case DLT_EN10MB: /* Standard ethernet header */ capdata->dot1x_offset = 14; capdata->l2type_offset = 12; capdata->dstmac_offset = 0; capdata->srcmac_offset = 6; break; case DLT_IEEE802_11: /* 24 bytes 802.11 header, 8 for 802.2 header */ capdata->dot1x_offset = 32; capdata->l2type_offset = 30; capdata->dstmac_offset = 4; capdata->srcmac_offset = 10; break; case DLT_PRISM_HEADER: /* 802.11 frames with AVS header, AVS header is 144 bytes */ capdata->dot1x_offset = 32 + 144; capdata->l2type_offset = 30 + 144; capdata->dstmac_offset = 4 + 144; capdata->srcmac_offset = 10 + 144; break; default: /* Unknown/unsupported pcap type */ return (1); } return (0); }
int dictfile_attack(struct user_opt *opt, char *passphrase, struct crack_data *cdata) { FILE *fp; int fret; u8 pmk[32]; u8 ptk[64]; u8 keymic[16]; struct wpa_ptk *ptkset; #ifdef FPGA // int i; opt_g = opt; cdata_g = cdata; if(usefpga) initfpga(); #endif /* Open the dictionary file */ if (*opt->dictfile == '-') { printf("Using STDIN for words.\n"); fp = stdin; } else { fp = fopen(opt->dictfile, "r"); if (fp == NULL) { perror("fopen"); exit(-1); } } while (feof(fp) == 0 && sig == 0) { /* Populate "passphrase" with the next word */ fret = nextdictword(passphrase, fp); if (fret < 0) { break; } if (opt->verbose > 1) { printf("Testing passphrase: %s\n", passphrase); } /* * Test length of word. IEEE 802.11i indicates the passphrase * must be at least 8 characters in length, and no more than 63 * characters in length. */ if (fret < 8 || fret > 63) { if (opt->verbose) { printf("Invalid passphrase length: %s (%d).\n", passphrase, strlen(passphrase)); } continue; } else { /* This word is good, increment the words tested counter */ wordstested++; } /* Status display */ #ifdef FPGA if ((wordstested % 100) == 0) { #else if ((wordstested % 1000) == 0) { #endif printf("key no. %ld: %s\n", wordstested, passphrase); fflush(stdout); } if (opt->verbose > 1) { printf("Calculating PMK for \"%s\".\n", passphrase); } pbkdf2_sha1(passphrase, opt->ssid, strlen(opt->ssid), 4096, pmk, sizeof(pmk), USECACHED); #ifdef FPGA if (!usefpga) { #endif if (opt->verbose > 2) { printf("PMK is"); lamont_hdump(pmk, sizeof(pmk)); } if (opt->verbose > 1) { printf("Calculating PTK with collected data and " "PMK.\n"); } #ifdef FPGA /* for(i = 0; i < 32; i++) printf("%02x ", pmk[i]); printf("\n"); */ #endif wpa_pmk_to_ptk(pmk, cdata->aa, cdata->spa, cdata->anonce, cdata->snonce, ptk, sizeof(ptk)); if (opt->verbose > 2) { printf("Calculated PTK for \"%s\" is", passphrase); lamont_hdump(ptk, sizeof(ptk)); } ptkset = (struct wpa_ptk *)ptk; if (opt->verbose > 1) { printf("Calculating hmac-MD5 Key MIC for this " "frame.\n"); } hmac_md5(ptkset->mic_key, 16, cdata->eapolframe, sizeof(cdata->eapolframe), keymic); if (opt->verbose > 2) { printf("Calculated MIC with \"%s\" is", passphrase); lamont_hdump(keymic, sizeof(keymic)); } if (memcmp(&cdata->keymic, &keymic, sizeof(keymic)) == 0) { return 0; } else { continue; } #ifdef FPGA } #endif } #ifdef FPGA if(usefpga) { printf("waiting..."); fflush(stdout); finishreg(); printf("\ndone\n"); } #endif return 1; } int main(int argc, char **argv) { struct user_opt opt; struct crack_data cdata; struct capture_data capdata; struct wpa_eapol_key *eapkeypacket; u8 eapolkey_nomic[99]; struct timeval start, end; int ret; char passphrase[MAXPASSLEN + 1]; printf("%s %s - WPA-PSK dictionary attack. <*****@*****.**>\n", PROGNAME, VER); memset(&opt, 0, sizeof(struct user_opt)); memset(&capdata, 0, sizeof(struct capture_data)); memset(&cdata, 0, sizeof(struct crack_data)); memset(&eapolkey_nomic, 0, sizeof(eapolkey_nomic)); /* Collect and test command-line arguments */ parseopts(&opt, argc, argv); testopts(&opt); printf("\n"); /* Populate capdata struct */ strncpy(capdata.pcapfilename, opt.pcapfile, sizeof(capdata.pcapfilename)); if (openpcap(&capdata) != 0) { printf("Unsupported or unrecognized pcap file.\n"); exit(1); } /* populates global *packet */ while (getpacket(&capdata) > 0) { if (opt.verbose > 2) { lamont_hdump(packet, h->len); } /* test packet for data that we are looking for */ if (memcmp(&packet[capdata.l2type_offset], DOT1X_LLCTYPE, 2) == 0 && (h->len > capdata.l2type_offset + sizeof(struct wpa_eapol_key))) { /* It's a dot1x frame, process it */ handle_dot1x(&cdata, &capdata); if (cdata.aaset && cdata.spaset && cdata.snonceset && cdata.anonceset && cdata.keymicset && cdata.eapolframeset) { /* We've collected everything we need. */ break; } } } closepcap(&capdata); if (!(cdata.aaset && cdata.spaset && cdata.snonceset && cdata.anonceset && cdata.keymicset && cdata.eapolframeset)) { printf("End of pcap capture file, incomplete TKIP four-way " "exchange. Try using a\ndifferent capture.\n"); exit(1); } else { printf("Collected all necessary data to mount crack against " "passphrase.\n"); } if (opt.verbose > 1) { dump_all_fields(cdata); } /* Zero mic and length data for hmac-md5 calculation */ eapkeypacket = (struct wpa_eapol_key *)&cdata.eapolframe[EAPDOT1XOFFSET]; memset(&eapkeypacket->key_mic, 0, sizeof(eapkeypacket->key_mic)); eapkeypacket->key_data_length = 0; printf("Starting dictionary attack. Please be patient.\n"); fflush(stdout); // signal(SIGINT, cleanup); // signal(SIGTERM, cleanup); // signal(SIGQUIT, cleanup); gettimeofday(&start, NULL); #ifdef FPGA start_g = start; #endif if (!IsBlank(opt.hashfile)) { ret = hashfile_attack(&opt, passphrase, &cdata); } else if (!IsBlank(opt.dictfile)) { ret = dictfile_attack(&opt, passphrase, &cdata); } else { usage("Must specify dictfile or hashfile (-f or -d)"); exit(1); } if (ret == 0) { printf("\nThe PSK is \"%s\".\n", passphrase); } else { printf("Unable to identify the PSK from the dictionary file. " "Try expanding your\npassphrase list, and double-check" " the SSID. Sorry it didn't work out.\n"); } gettimeofday(&end, NULL); printstats(start, end, wordstested); return (1); }
UINT CBoxScript::ParseScriptTextCodePage(LPCSTR pstrText, int nCount) { static struct { char *pstrName; int nSize; }CmdName[] = { {"#codepage", 9} }; #define CMD_COUNT (sizeof(CmdName) / sizeof(CmdName[0])) int i; LPCSTR pstrTemp, pstrTemp1; int nTempCount; int nLineCount = 1; while(nCount > 0 && IsBlank(pstrText[0])) { if(pstrText[0] == '\n') nLineCount ++; pstrText ++; nCount --; } while(nCount > 0 && pstrText[0] == '#') { for(i = 0; i < CMD_COUNT; i ++) if(nCount > CmdName[i].nSize && !_strnicmp(pstrText, CmdName[i].pstrName, CmdName[i].nSize) && IsBlankChar(pstrText[CmdName[i].nSize])) break; if(i == CMD_COUNT) break; pstrText += CmdName[i].nSize; nCount -= CmdName[i].nSize; while(nCount > 0 && IsBlankChar(pstrText[0])) { pstrText ++; nCount --; } if(nCount > 0 && pstrText[0] == '\"') { pstrText ++; nCount --; } pstrTemp = pstrText; nTempCount = nCount; while(nTempCount > 0 && !IsLineChar(pstrTemp[0])) { pstrTemp ++; nTempCount --; } pstrTemp1 = pstrTemp; while(pstrTemp1 > pstrText && IsBlankChar(pstrTemp1[0])) pstrTemp1 --; if(pstrTemp1 > pstrText && pstrTemp1[-1] == '\"') pstrTemp1 --; CStringA strValue; strValue.SetString(pstrText, (int)(pstrTemp1 - pstrText)); pstrText = pstrTemp; nCount = nTempCount; if (i == 0) return atoi(strValue); while(nCount > 0 && IsBlank(pstrText[0])) { if(pstrText[0] == '\n') nLineCount ++; pstrText ++; nCount --; } } return 0; }