Ejemplo n.º 1
0
/** Function used when byte ordering is important when parsing uuid
 *  ex: When we create an UUID type
 */
void formatUUID(std::reverse_iterator<const UInt8 *> src16, UInt8 * dst36)
{
    formatHex(src16 + 8, &dst36[0], 4);
    dst36[8] = '-';
    formatHex(src16 + 12, &dst36[9], 2);
    dst36[13] = '-';
    formatHex(src16 + 14, &dst36[14], 2);
    dst36[18] = '-';
    formatHex(src16, &dst36[19], 2);
    dst36[23] = '-';
    formatHex(src16 + 2, &dst36[24], 6);
}
Ejemplo n.º 2
0
void formatUUID(const UInt8 * src16, UInt8 * dst36)
{
    formatHex(&src16[0], &dst36[0], 4);
    dst36[8] = '-';
    formatHex(&src16[4], &dst36[9], 2);
    dst36[13] = '-';
    formatHex(&src16[6], &dst36[14], 2);
    dst36[18] = '-';
    formatHex(&src16[8], &dst36[19], 2);
    dst36[23] = '-';
    formatHex(&src16[10], &dst36[24], 6);
}
Ejemplo n.º 3
0
static int openPcap()
{
	char buf[PCAP_ERRBUF_SIZE], *fmt;
	struct bpf_program fcode;
	if ((hPcap = pcap_open_live(nic, 2048, 1, 1000, buf)) == NULL)
	{
//		printf("!! 打开网卡%s失败: %s\n", nic, buf);
		return -1;
	}
	fmt = formatHex(localMAC, 6);
#ifndef NO_ARP
	sprintf(buf, "((ether proto 0x888e and (ether dst %s or ether dst 01:80:c2:00:00:03)) "
			"or ether proto 0x0806) and not ether src %s", fmt, fmt);
#else
	sprintf(buf, "ether proto 0x888e and (ether dst %s or ether dst 01:80:c2:00:00:03) "
			"and not ether src %s", fmt, fmt);
#endif
	if (pcap_compile(hPcap, &fcode, buf, 0, 0xffffffff) == -1
			|| pcap_setfilter(hPcap, &fcode) == -1)
	{
//		printf("!! 设置pcap过滤器失败: %s\n", pcap_geterr(hPcap));
		return -1;
	}
	pcap_freecode(&fcode);
	return 0;
}
Ejemplo n.º 4
0
QString map::infoStr()
{
    QString mapString;

    if (!dtc) {
        if (numAxes <= 0) {
            mapString = "Map contains no axes";
        }
        else if (numAxes == 1) {
            mapString = QString::number(axes[0]->getLength()) + "x1";
            mapString += " MAP 0x" + formatHex(fileAddr);
            mapString += " AXIS 0x" + formatHex(axes[0]->getAddress());
            mapString += " (" + QString::number(axes[0]->getWordSize() * 8) + " bit)";
        }
        else if (numAxes == 2) {
            mapString = QString::number(axes[0]->getLength());
            mapString += "x" + QString::number(axes[1]->getLength());
            mapString += " MAP 0x" + formatHex(fileAddr);
            mapString += " AXIS1 0x" + formatHex(axes[0]->getAddress());
            mapString += " (" + QString::number(axes[0]->getWordSize() * 8) + " bit)";
            mapString += " AXIS2 0x" + formatHex(axes[1]->getAddress());
            mapString += " (" + QString::number(axes[1]->getWordSize() * 8) + " bit)";
        }
        else {
            mapString = "Invalid map";
        }
    }
    else {
        mapString = "DTC 0x" + formatHex(fileAddr) + " " + label;
    }

    return mapString;
}
Ejemplo n.º 5
0
static int Check(const u_char *md5Seed)	/* 客户端校验 */
{
	char final_str[129];
	int value;
	printf("** 客户端版本:\t%d.%d\n", fillBuf[0x3B], fillBuf[0x3C]);
	printf("** MD5种子:\t%s\n", formatHex(md5Seed, 16));
	value = check_init(dataFile);
	if (value == -1) {
		printf("!! 缺少8021x.exe信息,客户端校验无法继续!\n");
		return 1;
	}
	V2_check(md5Seed, final_str);
	printf("** V2校验值:\t%s\n", final_str);
	setProperty(0x17, (u_char *)final_str, 32);
	check_free();
	return 0;
}
Ejemplo n.º 6
0
static int Check(const uint8_t *md5Seed)	/* 客户端校验 */
{
	char final_str[129];
	int value;
	printf("** Client version: \t%d.%d\n", fillBuf[0x3B], fillBuf[0x3C]);
	printf("** MD5 seed: \t%s\n", formatHex(md5Seed, 16));
	value = check_init(dataFile);
	if (value == -1) {
		printf("!! 8021x.exe info is insufficient, cannot continue client authentication\n");
		return 1;
	}
	V2_check(md5Seed, final_str);
	printf("** V2 checksum: \t%s\n", final_str);
	setProperty(0x17, (uint8_t *)final_str, 32);
	check_free();
	return 0;
}
Ejemplo n.º 7
0
static int openPcap()
{
    char buf[PCAP_ERRBUF_SIZE], *fmt;
    struct bpf_program fcode;
    printf("Hill,%s\n",nic);
    if ((hPcap = pcap_open_live(nic, 2048, 1, 1000, buf)) == NULL)
    {
        printf("网卡%s打开失败,请重新设置: %s\n", nic, buf);
        return -1;
    }
    printf("Hill,%s\n",nic);
    fmt = formatHex(localMAC, 6);
    sprintf(buf, "ether proto 0x888e and (ether dst %s or ether dst 01:80:c2:00:00:03) "
            "and not ether src %s", fmt, fmt);
    if (pcap_compile(hPcap, &fcode, buf, 0, 0xffffffff) == -1
            || pcap_setfilter(hPcap, &fcode) == -1)
    {
        printf("pcap无法过滤: %s\n", pcap_geterr(hPcap));
        return -1;
    }
    pcap_freecode(&fcode);
    return 0;
}
Ejemplo n.º 8
0
static void pcap_handle(u_char *user, const struct pcap_pkthdr *h, const u_char *buf)
{
	static unsigned failCount = 0;
#ifndef NO_ARP
	if (buf[0x0c]==0x88 && buf[0x0d]==0x8e) {
#endif
		if (memcmp(destMAC, buf+6, 6)!=0 && startMode>2)	/* 服务器MAC地址不符 */
			return;
		capBuf = buf;
		if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x01) {	/* 验证用户名 */
			if (startMode < 3) {
				memcpy(destMAC, buf+6, 6);
				printf("** 认证MAC:\t%s\n", formatHex(destMAC, 6));
				startMode += 3;	/* 标记为已获取 */
			}
			if (startMode==3 && memcmp(buf+0x17, "User name", 9)==0)	/* 塞尔 */
				startMode = 5;
			switchState(ID_IDENTITY);
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x04)	/* 验证密码 */
			switchState(ID_CHALLENGE);
		else if (buf[0x0F]==0x00 && buf[0x12]==0x03) {	/* 认证成功 */
			printf(">> 认证成功!\n");
			fflush(stdout);
			failCount = 0;
			if (!(startMode%3 == 2)) {
				getEchoKey(buf);
				showRuijieMsg(buf, h->caplen);
			}
			if (dhcpMode==1 || dhcpMode==2)	/* 二次认证第一次或者认证后 */
				switchState(ID_DHCP);
			else if (startMode%3 == 2)
				switchState(ID_WAITECHO);
			else
				switchState(ID_ECHO);
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x02)	/* 显示赛尔提示信息 */
			showCernetMsg(buf);
		else if (buf[0x0F] == 0x05)	/* (赛尔)响应在线 */
			switchState(ID_ECHO);
		else if (buf[0x0F]==0x00 && buf[0x12]==0x04) {  /* 认证失败或被踢下线 */
			if (state==ID_WAITECHO || state==ID_ECHO) {
				printf(">! 认证掉线,开始重连!\n");
				fflush(stdout);
				switchState(ID_START);
			}
			else if (buf[0x1b]!=0 || startMode%3==2) {
				printf("!! 认证失败!\n");
				fflush(stdout);
				if (startMode%3 != 2)
					showRuijieMsg(buf, h->caplen);
				if (maxFail && ++failCount>=maxFail) {
					printf(">! 连续认证失败%u次,退出认证。\n", maxFail);
					fflush(stdout);
					exit(EXIT_SUCCESS);
				}
				restart();
			}
			else
				switchState(ID_START);
		}
#ifndef NO_ARP
	} else if (gateMAC[0]!=0xFE && buf[0x0c]==0x08 && buf[0x0d]==0x06) {
		if (*(u_int32_t *)(buf+0x1c) == gateway) {
			char str[50];
			if (gateMAC[0] == 0xFF) {
				memcpy(gateMAC, buf+0x16, 6);
				printf("** 网关MAC:\t%s\n", formatHex(gateMAC, 6));
				fflush(stdout);
				sprintf(str, "arp -s %s %s", formatIP(gateway), formatHex(gateMAC, 6));
				system(str);
			} else if (buf[0x15]==0x02 && *(u_int32_t *)(buf+0x26)==rip
				&& memcmp(gateMAC, buf+0x16, 6)!=0) {
				printf("** ARP欺骗:\t%s\n", formatHex(buf+0x16, 6));
				fflush(stdout);
#ifndef NO_NOTIFY
				if (showNotify) {
					sprintf(str, "欺骗源: %s", formatHex(buf+0x16, 6));
					show_notify("MentoHUST - ARP提示", str);
				}
#endif
			}
		}
	}
#endif
}
Ejemplo n.º 9
0
const QString &map::getTableText(bool colour)
{
    QStringList tableTextList;
    double min = getZValues()->at(0);
    double max = getZValues()->at(getZValues()->length() - 1);
    double diff = max - min;

    int yAxisWidth = 0;
    if (axes[1]) {
        yAxisWidth = axes[1]->getWidth();
    }
    int xAxisWidth = axes[0]->getWidth();
    int valWidth = getWidth();
    if (xAxisWidth > valWidth) {
        valWidth = xAxisWidth;
    }
    if (isDTC()) {
        valWidth = 2 * getWordSize() + 2;
    }

    QString mapText = "<b>Map    " + formatHex(getAddress(), false, true) + ": " + label;
    if (units.length() != 0) {
        mapText += " (" + units + ")";
    }
    mapText += "</b>";
    tableTextList << mapText;

    if (!axes[0]->isFixed()) {
        QString axis1Text = "<b>X-Axis " + formatHex(axes[0]->getAddress(), false, true) + ": " + axes[0]->getLabel();
        if (axes[0]->getUnits().length() != 0) {
            axis1Text += " (" + axes[0]->getUnits() + ")";
        }
        axis1Text += "</b>";
        tableTextList << axis1Text;
    }
    if (axes[1]) {
        QString axis2Text = "<b>Y-Axis " + formatHex(axes[1]->getAddress(), false, true) + ": " + axes[1]->getLabel();
        if (axes[0]->getUnits().length() != 0) {
            axis2Text += " (" + axes[1]->getUnits() + ")";
        }
        axis2Text += "</b>";
        tableTextList << axis2Text;
    }
    tableTextList << "";

    QString xLabels;
    if (yAxisWidth > 0) {
        xLabels.fill(QChar(' '), yAxisWidth + 1);
    }
    for (int i = 0; i < getXDim(); i++) {
        xLabels += QString("%1 ").arg(axisValue(0, i), valWidth, 'f', axes[0]->getDecimalPoints(), QChar(' '));
    }
    xLabels = "<span style=\"text-decoration:underline; font-weight:bold;\">" + xLabels + "</span>";
    tableTextList << xLabels;

    for (int y = 0; y < getYDim(); y++) {
        QString row;
        if (axes[1]) {
            int dp = axes[1]->getDecimalPoints();
            row = QString("%1 ").arg(axisValue(1, y), yAxisWidth, 'f', dp, QChar(' '));
            row = "<span style=\"font-weight:bold\">" + row + "</span>";
        }

        for (int x = 0; x < getXDim(); x++) {
            int dp = getDecimalPoints();
            if (isDTC()) {
                int val = getValue(x,y);
                row += "0x" + QString("%1 ").arg(val, valWidth-2, 16, QChar('0')).toUpper();
            }
            else {
                double val = getValue(x, y);
                if (colour) {
                    double temp = val - min;
                    if (diff == 0) {
                        temp = 1.0;
                    }
                    else {
                        temp /= diff;
                    }
                    int red = 255*temp;
                    int green = 255-255*temp;
                    row += "<span style=\"background-color: rgb(" + QString::number(red) + "," + QString::number(green) + ",0);\">";
                }
                else {
                    row += "<span>";
                }

                row += QString("%1 </span>").arg(val, valWidth, 'f', dp, QChar(' '));
            }
        }
        tableTextList << row;
    }

    tableText = "<pre style=\"font-size:16px; color:black\">" + tableTextList.join("\n") + "</pre>";
    return tableText;
}
Ejemplo n.º 10
0
void CertificateDialog::updateValue()
{
	const QSslCertificate certificate(m_certificates.value(m_ui->chainItemView->currentIndex().data(Qt::UserRole).toInt()));
	const CertificateField field(static_cast<CertificateField>(m_ui->detailsItemView->currentIndex().data(Qt::UserRole).toInt()));

	m_ui->valueTextEdit->clear();

	switch (field)
	{
		case ValidityField:
		case PublicKeyField:
		case ExtensionsField:
		case DigestField:
			break;
		case VersionField:
			m_ui->valueTextEdit->setPlainText(QString(certificate.version()));

			break;
		case SerialNumberField:
			m_ui->valueTextEdit->setPlainText(formatHex(QString(certificate.serialNumber()), QLatin1Char(':')));

			break;
		case SignatureAlgorithmField:
			m_ui->valueTextEdit->setPlainText(QRegularExpression(QLatin1String("Signature Algorithm:(.+)")).match(certificate.toText()).captured(1).trimmed());

			break;
		case IssuerField:
			{
				const QList<QByteArray> attributes(certificate.issuerInfoAttributes());

				for (int i = 0; i < attributes.count(); ++i)
				{
					m_ui->valueTextEdit->appendPlainText(QStringLiteral("%1 = %2").arg(QString(attributes.at(i))).arg(certificate.issuerInfo(attributes.at(i)).join(QLatin1String(", "))));
				}
			}

			break;
		case ValidityNotBeforeField:
			m_ui->valueTextEdit->setPlainText(certificate.effectiveDate().toString(QLatin1String("yyyy-MM-dd hh:mm:ss t")));

			break;
		case ValidityNotAfterField:
			m_ui->valueTextEdit->setPlainText(certificate.expiryDate().toString(QLatin1String("yyyy-MM-dd hh:mm:ss t")));

			break;
		case SubjectField:
			{
				const QList<QByteArray> attributes(certificate.subjectInfoAttributes());

				for (int i = 0; i < attributes.count(); ++i)
				{
					m_ui->valueTextEdit->appendPlainText(QStringLiteral("%1 = %2").arg(QString(attributes.at(i))).arg(certificate.subjectInfo(attributes.at(i)).join(QLatin1String(", "))));
				}
			}

			break;
		case PublicKeyValueField:
			{
				const QRegularExpression expression(QLatin1String("Public-Key:[.\\s\\S]+Modulus:([.\\s\\S]+)Exponent:(.+)"), QRegularExpression::MultilineOption);
				const QRegularExpressionMatch match(expression.match(certificate.toText()));

				if (match.hasMatch())
				{
					m_ui->valueTextEdit->setPlainText(tr("Modulus:\n%1\n\nExponent: %2").arg(formatHex(match.captured(1).trimmed().mid(3))).arg(match.captured(2).trimmed()));
				}
			}

			break;
		case PublicKeyAlgorithmField:
			m_ui->valueTextEdit->setPlainText(QRegularExpression(QLatin1String("Public Key Algorithm:(.+)")).match(certificate.toText()).captured(1).trimmed());

			break;
		case ExtensionField:
			{
				const QSslCertificateExtension extension(certificate.extensions().value(m_ui->detailsItemView->currentIndex().data(Qt::UserRole + 1).toInt()));

				m_ui->valueTextEdit->setPlainText(extension.isCritical() ? tr("Critical") : tr("Not Critical"));
				m_ui->valueTextEdit->appendPlainText(tr("OID: %1").arg(extension.oid()));

				if (!extension.value().isNull())
				{
					m_ui->valueTextEdit->appendPlainText(tr("Value:"));

					if (extension.value().type() == QVariant::List)
					{
						const QVariantList list(extension.value().toList());

						for (int i = 0; i < list.count(); ++i)
						{
							m_ui->valueTextEdit->appendPlainText(list.at(i).toString());
						}
					}
					else if (extension.value().type() == QVariant::Map)
					{
						const QVariantMap map(extension.value().toMap());
						QVariantMap::const_iterator iterator;

						for (iterator = map.constBegin(); iterator != map.constEnd(); ++iterator)
						{
							m_ui->valueTextEdit->appendPlainText(QStringLiteral("%1 = %2").arg(iterator.key()).arg(iterator.value().toString()));
						}
					}
					else
					{
						m_ui->valueTextEdit->appendPlainText(extension.value().toString());
					}
				}
			}

			break;
		case DigestSha1Field:
			m_ui->valueTextEdit->setPlainText(formatHex(QString(certificate.digest(QCryptographicHash::Sha1).toHex())));

			break;
		case DigestSha256Field:
			m_ui->valueTextEdit->setPlainText(formatHex(QString(certificate.digest(QCryptographicHash::Sha256).toHex())));

			break;
		default:
			break;
	}

	QTextCursor cursor(m_ui->valueTextEdit->textCursor());
	cursor.setPosition(0);

	m_ui->valueTextEdit->setTextCursor(cursor);
}
Ejemplo n.º 11
0
int main (int argc, char** argv)
{
  UnitTest t (264);

  // void wrapText (std::vector <std::string>& lines, const std::string& text, const int width, bool hyphenate)
  std::string text = "This is a test of the line wrapping code.";
  std::vector <std::string> lines;
  wrapText (lines, text, 10, true);
  t.is (lines.size (), (size_t) 5, "wrapText 'This is a test of the line wrapping code.' -> total 5 lines");
  t.is (lines[0], "This is a",     "wrapText line 0 -> 'This is a'");
  t.is (lines[1], "test of",       "wrapText line 1 -> 'test of'");
  t.is (lines[2], "the line",      "wrapText line 2 -> 'the line'");
  t.is (lines[3], "wrapping",      "wrapText line 3 -> 'wrapping'");
  t.is (lines[4], "code.",         "wrapText line 4 -> 'code.'");

  text = "This ☺ is a test of utf8 line extraction.";
  lines.clear ();
  wrapText (lines, text, 7, true);
  t.is (lines.size (), (size_t) 7, "wrapText 'This ☺ is a test of utf8 line extraction.' -> total 7 lines");
  t.is (lines[0], "This ☺",        "wrapText line 0 -> 'This ☺'");
  t.is (lines[1], "is a",          "wrapText line 1 -> 'is a'");
  t.is (lines[2], "test of",       "wrapText line 2 -> 'test of'");
  t.is (lines[3], "utf8",          "wrapText line 3 -> 'utf8'");
  t.is (lines[4], "line",          "wrapText line 4 -> 'line'");
  t.is (lines[5], "extrac-",       "wrapText line 5 -> 'extrac-'");
  t.is (lines[6], "tion.",         "wrapText line 6 -> 'tion.'");

  text = "one two three\n  four";
  lines.clear ();
  wrapText (lines, text, 13, true);
  t.is (lines.size (), (size_t) 2, "wrapText 'one two three\\n  four' -> 2 lines");
  t.is (lines[0], "one two three", "wrapText line 0 -> 'one two three'");
  t.is (lines[1], "  four",        "wrapText line 1 -> '  four'");

  // void extractLine (std::string& text, std::string& line, int length, bool hyphenate, unsigned int& offset)
  text = "This ☺ is a test of utf8 line extraction.";
  unsigned int offset = 0;
  std::string line;
  extractLine (line, text, 7, true, offset);
  t.is (line, "This ☺", "extractLine 7 'This ☺ is a test of utf8 line extraction.' -> 'This ☺'");

  // void extractLine (std::string& text, std::string& line, int length, bool hyphenate, unsigned int& offset)
  text = "line 1\nlengthy second line that exceeds width";
  offset = 0;
  extractLine (line, text, 10, true, offset);
  t.is (line, "line 1", "extractLine 10 'line 1\\nlengthy second line that exceeds width' -> 'line 1'");

  extractLine (line, text, 10, true, offset);
  t.is (line, "lengthy", "extractLine 10 'lengthy second line that exceeds width' -> 'lengthy'");

  extractLine (line, text, 10, true, offset);
  t.is (line, "second", "extractLine 10 'second line that exceeds width' -> 'second'");

  extractLine (line, text, 10, true, offset);
  t.is (line, "line that", "extractLine 10 'line that exceeds width' -> 'line that'");

  extractLine (line, text, 10, true, offset);
  t.is (line, "exceeds", "extractLine 10 'exceeds width' -> 'exceeds'");

  extractLine (line, text, 10, true, offset);
  t.is (line, "width", "extractLine 10 'width' -> 'width'");

  t.notok (extractLine (line, text, 10, true, offset), "extractLine 10 '' -> ''");

  // void split (std::vector<std::string>& results, const std::string& input, const char delimiter)
  std::vector <std::string> items;
  std::string unsplit = "";
  split (items, unsplit, '-');
  t.is (items.size (), (size_t) 0, "split '' '-' -> 0 items");

  unsplit = "a";
  split (items, unsplit, '-');
  t.is (items.size (), (size_t) 1, "split 'a' '-' -> 1 item");
  t.is (items[0], "a",             "split 'a' '-' -> 'a'");

  split (items, unsplit, '-');
  t.is (items.size (), (size_t) 1, "split 'a' '-' -> 1 item");
  t.is (items[0], "a",             "split 'a' '-' -> 'a'");

  unsplit = "-";
  split (items, unsplit, '-');
  t.is (items.size (), (size_t) 2, "split '-' '-' -> '' ''");
  t.is (items[0], "",              "split '-' '-' -> [0] ''");
  t.is (items[1], "",              "split '-' '-' -> [1] ''");

  split_minimal (items, unsplit, '-');
  t.is (items.size (), (size_t) 0, "split '-' '-' ->");

  unsplit = "-a-bc-def";
  split (items, unsplit, '-');
  t.is (items.size (), (size_t) 4, "split '-a-bc-def' '-' -> '' 'a' 'bc' 'def'");
  t.is (items[0], "",              "split '-a-bc-def' '-' -> [0] ''");
  t.is (items[1], "a",             "split '-a-bc-def' '-' -> [1] 'a'");
  t.is (items[2], "bc",            "split '-a-bc-def' '-' -> [2] 'bc'");
  t.is (items[3], "def",           "split '-a-bc-def' '-' -> [3] 'def'");

  split_minimal (items, unsplit, '-');
  t.is (items.size (), (size_t) 3, "split '-a-bc-def' '-' -> 'a' 'bc' 'def'");
  t.is (items[0], "a",             "split '-a-bc-def' '-' -> [1] 'a'");
  t.is (items[1], "bc",            "split '-a-bc-def' '-' -> [2] 'bc'");
  t.is (items[2], "def",           "split '-a-bc-def' '-' -> [3] 'def'");

  // void split (std::vector<std::string>& results, const std::string& input, const std::string& delimiter)
  unsplit = "";
  split (items, unsplit, "--");
  t.is (items.size (), (size_t) 0, "split '' '--' -> 0 items");

  unsplit = "a";
  split (items, unsplit, "--");
  t.is (items.size (), (size_t) 1, "split 'a' '--' -> 1 item");
  t.is (items[0], "a",             "split 'a' '-' -> 'a'");

  unsplit = "--";
  split (items, unsplit, "--");
  t.is (items.size (), (size_t) 2, "split '-' '--' -> '' ''");
  t.is (items[0], "",              "split '-' '-' -> [0] ''");
  t.is (items[1], "",              "split '-' '-' -> [1] ''");

  unsplit = "--a--bc--def";
  split (items, unsplit, "--");
  t.is (items.size (), (size_t) 4, "split '-a-bc-def' '--' -> '' 'a' 'bc' 'def'");
  t.is (items[0], "",              "split '-a-bc-def' '--' -> [0] ''");
  t.is (items[1], "a",             "split '-a-bc-def' '--' -> [1] 'a'");
  t.is (items[2], "bc",            "split '-a-bc-def' '--' -> [2] 'bc'");
  t.is (items[3], "def",           "split '-a-bc-def' '--' -> [3] 'def'");

  unsplit = "one\ntwo\nthree";
  split (items, unsplit, "\n");
  t.is (items.size (), (size_t) 3, "split 'one\\ntwo\\nthree' -> 'one', 'two', 'three'");
  t.is (items[0], "one",           "split 'one\\ntwo\\nthree' -> [0] 'one'");
  t.is (items[1], "two",           "split 'one\\ntwo\\nthree' -> [1] 'two'");
  t.is (items[2], "three",         "split 'one\\ntwo\\nthree' -> [2] 'three'");

  // void splitq (std::vector<std::string>&, const std::string&, const char);
  unsplit = "one 'two' '' 'three four' \"five six seven\" eight'nine ten'";
  splitq (items, unsplit, ' ');
  t.is (items.size () , (size_t) 6,  "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten'");
  t.is (items[0], "one",             "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten' -> [0] 'one'");
  t.is (items[1], "two",             "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten' -> [1] 'two'");
  t.is (items[2], "",                "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten' -> [2] ''");
  t.is (items[3], "three four",      "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten' -> [3] 'three four'");
  t.is (items[4], "five six seven",  "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten' -> [4] 'five six seven'");
  t.is (items[5], "eight'nine ten'", "splitq 'one \\'two\\' \\'\\' \\'three four\\' \"five six seven\" eight'nine ten' -> [4] 'eight\\'nine ten\\''");

  // void join (std::string& result, const std::string& separator, const std::vector<std::string>& items)
  std::vector <std::string> unjoined;
  std::string joined;

  join (joined, "", unjoined);
  t.is (joined.length (), (size_t) 0,  "join -> length 0");
  t.is (joined,           "",          "join -> ''");

  unjoined.push_back ("");
  unjoined.push_back ("a");
  unjoined.push_back ("bc");
  unjoined.push_back ("def");
  join (joined, "", unjoined);
  t.is (joined.length (), (size_t) 6, "join '' 'a' 'bc' 'def' -> length 6");
  t.is (joined,           "abcdef",   "join '' 'a' 'bc' 'def' -> 'abcdef'");

  join (joined, "-", unjoined);
  t.is (joined.length (), (size_t) 9,  "join '' - 'a' - 'bc' - 'def' -> length 9");
  t.is (joined,           "-a-bc-def", "join '' - 'a' - 'bc' - 'def' -> '-a-bc-def'");

  // void join (std::string& result, const std::string& separator, const std::vector<int>& items)
  std::vector <int> unjoined2;

  join (joined, "", unjoined2);
  t.is (joined.length (), (size_t) 0, "join -> length 0");
  t.is (joined,           "",         "join -> ''");

  unjoined2.push_back (0);
  unjoined2.push_back (1);
  unjoined2.push_back (2);
  join (joined, "", unjoined2);
  t.is (joined.length (), (size_t) 3, "join 0 1 2 -> length 3");
  t.is (joined,           "012",      "join 0 1 2 -> '012'");

  join (joined, "-", unjoined2);
  t.is (joined.length (), (size_t) 5, "join 0 1 2 -> length 5");
  t.is (joined,           "0-1-2",    "join 0 1 2 -> '0-1-2'");

  // std::string trimLeft (const std::string& in, const std::string& t /*= " "*/)
  t.is (trimLeft (""),                     "",            "trimLeft '' -> ''");
  t.is (trimLeft ("   "),                  "",            "trimLeft '   ' -> ''");
  t.is (trimLeft ("",              " \t"), "",            "trimLeft '' -> ''");
  t.is (trimLeft ("xxx"),                  "xxx",         "trimLeft 'xxx' -> 'xxx'");
  t.is (trimLeft ("xxx",           " \t"), "xxx",         "trimLeft 'xxx' -> 'xxx'");
  t.is (trimLeft ("  \t xxx \t  "),        "\t xxx \t  ", "trimLeft '  \\t xxx \\t  ' -> '\\t xxx \\t  '");
  t.is (trimLeft ("  \t xxx \t  ", " \t"), "xxx \t  ",    "trimLeft '  \\t xxx \\t  ' -> 'xxx \\t  '");

  // std::string trimRight (const std::string& in, const std::string& t /*= " "*/)
  t.is (trimRight (""),                     "",            "trimRight '' -> ''");
  t.is (trimRight ("   "),                  "",            "trimRight '   ' -> ''");
  t.is (trimRight ("",              " \t"), "",            "trimRight '' -> ''");
  t.is (trimRight ("xxx"),                  "xxx",         "trimRight 'xxx' -> 'xxx'");
  t.is (trimRight ("xxx",           " \t"), "xxx",         "trimRight 'xxx' -> 'xxx'");
  t.is (trimRight ("  \t xxx \t  "),        "  \t xxx \t", "trimRight '  \\t xxx \\t  ' -> '  \\t xxx \\t'");
  t.is (trimRight ("  \t xxx \t  ", " \t"), "  \t xxx",    "trimRight '  \\t xxx \\t  ' -> '  \\t xxx'");

  // std::string trim (const std::string& in, const std::string& t /*= " "*/)
  t.is (trim (""),                     "",          "trim '' -> ''");
  t.is (trim ("   "),                  "",          "trim '   ' -> ''");
  t.is (trim ("",              " \t"), "",          "trim '' -> ''");
  t.is (trim ("xxx"),                  "xxx",       "trim 'xxx' -> 'xxx'");
  t.is (trim ("xxx",           " \t"), "xxx",       "trim 'xxx' -> 'xxx'");
  t.is (trim ("  \t xxx \t  "),        "\t xxx \t", "trim '  \\t xxx \\t  ' -> '\\t xxx \\t'");
  t.is (trim ("  \t xxx \t  ", " \t"), "xxx",       "trim '  \\t xxx \\t  ' -> 'xxx'");

  // std::string unquoteText (const std::string& text)
  t.is (unquoteText (""),         "",     "unquoteText '' -> ''");
  t.is (unquoteText ("x"),        "x",    "unquoteText 'x' -> 'x'");
  t.is (unquoteText ("'x"),       "'x",   "unquoteText ''x' -> ''x'");
  t.is (unquoteText ("x'"),       "x'",   "unquoteText 'x'' -> 'x''");
  t.is (unquoteText ("\"x"),      "\"x",  "unquoteText '\"x' -> '\"x'");
  t.is (unquoteText ("x\""),      "x\"",  "unquoteText 'x\"' -> 'x\"'");
  t.is (unquoteText ("''"),       "",     "unquoteText '''' -> ''");
  t.is (unquoteText ("'''"),      "'",    "unquoteText ''''' -> '''");
  t.is (unquoteText ("\"\""),     "",     "unquoteText '\"\"' -> ''");
  t.is (unquoteText ("\"\"\""),    "\"",  "unquoteText '\"\"\"' -> '\"'");
  t.is (unquoteText ("''''"),     "''",   "unquoteText '''''' -> ''''");
  t.is (unquoteText ("\"\"\"\""), "\"\"", "unquoteText '\"\"\"\"' -> '\"\"'");
  t.is (unquoteText ("'\"\"'"),   "\"\"", "unquoteText '''\"\"' -> '\"\"'");
  t.is (unquoteText ("\"''\""),   "''",   "unquoteText '\"''\"' -> ''''");
  t.is (unquoteText ("'x'"),      "x",    "unquoteText ''x'' -> 'x'");
  t.is (unquoteText ("\"x\""),    "x",    "unquoteText '\"x\"' -> 'x'");

  // int longestWord (const std::string&)
  t.is (longestWord ("    "),                   0, "longestWord (    ) --> 0");
  t.is (longestWord ("this is a test"),         4, "longestWord (this is a test) --> 4");
  t.is (longestWord ("this is a better test"),  6, "longestWord (this is a better test) --> 6");
  t.is (longestWord ("house Çirçös clown"),     6, "longestWord (Çirçös) --> 6");

  // int longestLine (const std::string&)
  t.is (longestLine ("one two three four"),    18, "longestLine (one two three four) --> 18");
  t.is (longestLine ("one\ntwo three four"),   14, "longestLine (one\\ntwo three four) --> 14");
  t.is (longestLine ("one\ntwo\nthree\nfour"),  5, "longestLine (one\\ntwo\\nthree\\nfour) --> 5");

  // std::string commify (const std::string& data)
  t.is (commify (""),           "",              "commify '' -> ''");
  t.is (commify ("1"),          "1",             "commify '1' -> '1'");
  t.is (commify ("12"),         "12",            "commify '12' -> '12'");
  t.is (commify ("123"),        "123",           "commify '123' -> '123'");
  t.is (commify ("1234"),       "1,234",         "commify '1234' -> '1,234'");
  t.is (commify ("12345"),      "12,345",        "commify '12345' -> '12,345'");
  t.is (commify ("123456"),     "123,456",       "commify '123456' -> '123,456'");
  t.is (commify ("1234567"),    "1,234,567",     "commify '1234567' -> '1,234,567'");
  t.is (commify ("12345678"),   "12,345,678",    "commify '12345678' -> '12,345,678'");
  t.is (commify ("123456789"),  "123,456,789",   "commify '123456789' -> '123,456,789'");
  t.is (commify ("1234567890"), "1,234,567,890", "commify '1234567890' -> '1,234,567,890'");

  t.is (commify ("pre"),         "pre",          "commify 'pre' -> 'pre'");
  t.is (commify ("pre1234"),     "pre1,234",     "commify 'pre1234' -> 'pre1,234'");
  t.is (commify ("1234post"),    "1,234post",    "commify '1234post' -> '1,234post'");
  t.is (commify ("pre1234post"), "pre1,234post", "commify 'pre1234post' -> 'pre1,234post'");

  // std::string lowerCase (const std::string& input)
  t.is (lowerCase (""),            "",            "lowerCase '' -> ''");
  t.is (lowerCase ("pre01_:POST"), "pre01_:post", "lowerCase 'pre01_:POST' -> 'pre01_:post'");

  // std::string upperCase (const std::string& input)
  t.is (upperCase (""),            "",            "upperCase '' -> ''");
  t.is (upperCase ("pre01_:POST"), "PRE01_:POST", "upperCase 'pre01_:POST' -> 'PRE01_:POST'");

  // bool nontrivial (const std::string&);
  t.notok (nontrivial (""),                       "nontrivial '' -> false");
  t.notok (nontrivial ("   "),                    "nontrivial '   ' -> false");
  t.notok (nontrivial ("\t\t"),                   "nontrivial '\\t\\t' -> false");
  t.notok (nontrivial (" \t \t"),                 "nontrivial ' \\t \\t' -> false");
  t.ok    (nontrivial ("a"),                      "nontrivial 'a' -> true");
  t.ok    (nontrivial ("   a"),                   "nontrivial '   a' -> true");
  t.ok    (nontrivial ("a   "),                   "nontrivial 'a   ' -> true");
  t.ok    (nontrivial ("  \t\ta"),                "nontrivial '  \\t\\ta' -> true");
  t.ok    (nontrivial ("a\t\t  "),                "nontrivial 'a\\t\\t  ' -> true");

  // bool digitsOnly (const std::string&);
  t.ok    (digitsOnly (""),                       "digitsOnly '' -> true");
  t.ok    (digitsOnly ("0"),                      "digitsOnly '0' -> true");
  t.ok    (digitsOnly ("123"),                    "digitsOnly '123' -> true");
  t.notok (digitsOnly ("12fa"),                   "digitsOnly '12fa' -> false");

  // bool noSpaces (const std::string&);
  t.ok    (noSpaces (""),                         "noSpaces '' -> true");
  t.ok    (noSpaces ("a"),                        "noSpaces 'a' -> true");
  t.ok    (noSpaces ("abc"),                      "noSpaces 'abc' -> true");
  t.notok (noSpaces (" "),                        "noSpaces ' ' -> false");
  t.notok (noSpaces ("ab cd"),                    "noSpaces 'ab cd' -> false");

  // bool noVerticalSpace (const std::string&);
  t.ok    (noVerticalSpace (""),                  "noVerticalSpace '' -> true");
  t.ok    (noVerticalSpace ("a"),                 "noVerticalSpace 'a' -> true");
  t.ok    (noVerticalSpace ("abc"),               "noVerticalSpace 'abc' -> true");
  t.notok (noVerticalSpace ("a\nb"),              "noVerticalSpace 'a\\nb' -> false");
  t.notok (noVerticalSpace ("a\rb"),              "noVerticalSpace 'a\\rb' -> false");
  t.notok (noVerticalSpace ("a\fb"),              "noVerticalSpace 'a\\fb' -> false");

  text = "Hello, world.";
  //      0123456789012
  //      s   e  s   e

  // bool isWordStart (const std::string&, std::string::size_type);
  t.notok (isWordStart ("", 0),                   "isWordStart (\"\", 0) -> false");
  t.ok    (isWordStart ("foo", 0),                "isWordStart (\"foo\", 0) -> true");
  t.ok    (isWordStart (text, 0),                 "isWordStart (\"Hello, world.\", 0) -> true");
  t.notok (isWordStart (text, 1),                 "isWordStart (\"Hello, world.\", 1) -> false");
  t.notok (isWordStart (text, 2),                 "isWordStart (\"Hello, world.\", 2) -> false");
  t.notok (isWordStart (text, 3),                 "isWordStart (\"Hello, world.\", 3) -> false");
  t.notok (isWordStart (text, 4),                 "isWordStart (\"Hello, world.\", 4) -> false");
  t.notok (isWordStart (text, 5),                 "isWordStart (\"Hello, world.\", 5) -> false");
  t.notok (isWordStart (text, 6),                 "isWordStart (\"Hello, world.\", 6) -> false");
  t.ok    (isWordStart (text, 7),                 "isWordStart (\"Hello, world.\", 7) -> true");
  t.notok (isWordStart (text, 8),                 "isWordStart (\"Hello, world.\", 8) -> false");
  t.notok (isWordStart (text, 9),                 "isWordStart (\"Hello, world.\", 9) -> false");
  t.notok (isWordStart (text, 10),                "isWordStart (\"Hello, world.\", 10) -> false");
  t.notok (isWordStart (text, 11),                "isWordStart (\"Hello, world.\", 11) -> false");
  t.notok (isWordStart (text, 12),                "isWordStart (\"Hello, world.\", 12) -> false");

  // bool isWordEnd (const std::string&, std::string::size_type);
  t.notok (isWordEnd ("", 0),                     "isWordEnd (\"\", 0) -> false");
  t.ok    (isWordEnd ("foo", 2),                  "isWordEnd (\"foo\", 2) -> true");
  t.notok (isWordEnd (text, 0),                   "isWordEnd (\"Hello, world.\", 0) -> false");
  t.notok (isWordEnd (text, 1),                   "isWordEnd (\"Hello, world.\", 1) -> false");
  t.notok (isWordEnd (text, 2),                   "isWordEnd (\"Hello, world.\", 2) -> false");
  t.notok (isWordEnd (text, 3),                   "isWordEnd (\"Hello, world.\", 3) -> false");
  t.ok    (isWordEnd (text, 4),                   "isWordEnd (\"Hello, world.\", 4) -> true");
  t.notok (isWordEnd (text, 5),                   "isWordEnd (\"Hello, world.\", 5) -> false");
  t.notok (isWordEnd (text, 6),                   "isWordEnd (\"Hello, world.\", 6) -> false");
  t.notok (isWordEnd (text, 7),                   "isWordEnd (\"Hello, world.\", 7) -> false");
  t.notok (isWordEnd (text, 8),                   "isWordEnd (\"Hello, world.\", 8) -> false");
  t.notok (isWordEnd (text, 9),                   "isWordEnd (\"Hello, world.\", 9) -> false");
  t.notok (isWordEnd (text, 10),                  "isWordEnd (\"Hello, world.\", 10) -> false");
  t.ok    (isWordEnd (text, 11),                  "isWordEnd (\"Hello, world.\", 11) -> true");
  t.notok (isWordEnd (text, 12),                  "isWordEnd (\"Hello, world.\", 12) -> false");

  // bool compare (const std::string&, const std::string&, bool caseless = false);
  // Make sure degenerate cases are handled.
  t.ok    (compare ("", ""),    "'' == ''");
  t.notok (compare ("foo", ""), "foo != ''");
  t.notok (compare ("", "foo"), "'' != foo");

  // Make sure the default is case-sensitive.
  t.ok    (compare ("foo", "foo"), "foo == foo");
  t.notok (compare ("foo", "FOO"), "foo != foo");

  // Test case-sensitive.
  t.notok (compare ("foo", "xx", true),  "foo != xx");

  t.ok    (compare ("foo", "foo", true), "foo == foo");
  t.notok (compare ("foo", "FOO", true), "foo != FOO");
  t.notok (compare ("FOO", "foo", true), "FOO != foo");
  t.ok    (compare ("FOO", "FOO", true), "FOO == FOO");

  // Test case-insensitive.
  t.notok (compare ("foo", "xx", false),   "foo != foo (caseless)");

  t.ok    (compare ("foo", "foo", false),  "foo == foo (caseless)");
  t.ok    (compare ("foo", "FOO", false),  "foo == FOO (caseless)");
  t.ok    (compare ("FOO", "foo", false),  "FOO == foo (caseless)");
  t.ok    (compare ("FOO", "FOO", false),  "FOO == FOO (caseless)");

  // std::string::size_type find (const std::string&, const std::string&, bool caseless = false);
  // Make sure degenerate cases are handled.
  t.is ((int) find ("foo", ""), (int) 0,                 "foo !contains ''");
  t.is ((int) find ("", "foo"), (int) std::string::npos, "'' !contains foo");

  // Make sure the default is case-sensitive.
  t.is ((int) find ("foo", "fo"), 0,                       "foo contains fo");
  t.is ((int) find ("foo", "FO"), (int) std::string::npos, "foo !contains fo");

  // Test case-sensitive.
  t.is ((int) find ("foo", "xx", true), (int) std::string::npos, "foo !contains xx");
  t.is ((int) find ("foo", "oo", true), 1,                       "foo contains oo");

  t.is ((int) find ("foo", "fo", true), 0,                       "foo contains fo");
  t.is ((int) find ("foo", "FO", true), (int) std::string::npos, "foo !contains fo");
  t.is ((int) find ("FOO", "fo", true), (int) std::string::npos, "foo !contains fo");
  t.is ((int) find ("FOO", "FO", true), 0,                       "foo contains fo");

  // Test case-insensitive.
  t.is ((int) find ("foo", "xx", false),  (int) std::string::npos, "foo !contains xx (caseless)");
  t.is ((int) find ("foo", "oo", false),  1,                       "foo contains oo (caseless)");

  t.is ((int) find ("foo", "fo", false),  0, "foo contains fo (caseless)");
  t.is ((int) find ("foo", "FO", false),  0, "foo contains FO (caseless)");
  t.is ((int) find ("FOO", "fo", false),  0, "FOO contains fo (caseless)");
  t.is ((int) find ("FOO", "FO", false),  0, "FOO contains FO (caseless)");

  // Test start offset.
  t.is ((int) find ("one two three", "e",  3, true), (int) 11, "offset obeyed");
  t.is ((int) find ("one two three", "e", 11, true), (int) 11, "offset obeyed");

  // int strippedLength (const std::string&);
  t.is (strippedLength (std::string ("")),                                  0, "strippedLength                              -> 0");
  t.is (strippedLength (std::string ("abc")),                               3, "strippedLength abc                          -> 3");
  t.is (strippedLength (std::string ("one\033[5;38;255mtwo\033[0mthree")), 11, "strippedLength one^[[5;38;255mtwo^[[0mthree -> 11");
  t.is (strippedLength (std::string ("\033[0m")),                           0, "strippedLength ^[[0m                        -> 0");
  t.is (strippedLength (std::string ("\033[1m\033[0m")),                    0, "strippedLength ^[[1m^[[0m                   -> 0");

  // std::string format (char);
  t.is (format ('A'), "A", "format ('A') -> A");

  // std::string format (int);
  t.is (format (0),  "0",  "format (0) -> 0");
  t.is (format (-1), "-1", "format (-1) -> -1");

  // std::string formatHex (int);
  t.is (formatHex (0),   "0",  "formatHex (0) -> 0");
  t.is (formatHex (10),  "a",  "formatHex (10) -> a");
  t.is (formatHex (123), "7b", "formatHex (123) -> 7b");

  // std::string format (float, int, int);
  t.is (format (1.23456789, 8, 1),      "       1",     "format (1.23456789,    8,   1) -> _______1");
  t.is (format (1.23456789, 8, 2),      "     1.2",     "format (1.23456789,    8,   2) -> _____1.2");
  t.is (format (1.23456789, 8, 3),      "    1.23",     "format (1.23456789,    8,   3) -> ____1.23");
  t.is (format (1.23456789, 8, 4),      "   1.235",     "format (1.23456789,    8,   4) -> ___1.235");
  t.is (format (1.23456789, 8, 5),      "  1.2346",     "format (1.23456789,    8,   5) -> __1.2346");
  t.is (format (1.23456789, 8, 6),      " 1.23457",     "format (1.23456789,    8,   6) ->  1.23457");
  t.is (format (1.23456789, 8, 7),      "1.234568",     "format (1.23456789,    8,   7) -> 1.234568");
  t.is (format (1.23456789, 8, 8),      "1.2345679",    "format (1.23456789,    8,   8) -> 1.2345679");
  t.is (format (2444238.56789, 12, 11), "2444238.5679", "format (2444238.56789, 12, 11) -> 2444238.5679");

  // std::string format (double, int, int);

  // std::string leftJustify (const std::string&, const int);
  t.is (leftJustify (123, 3), "123",   "leftJustify 123,3 -> '123'");
  t.is (leftJustify (123, 4), "123 ",  "leftJustify 123,4 -> '123 '");
  t.is (leftJustify (123, 5), "123  ", "leftJustify 123,5 -> '123  '");

  // std::string leftJustify (const std::string&, const int);
  t.is (leftJustify ("foo", 3), "foo",   "leftJustify foo,3 -> 'foo'");
  t.is (leftJustify ("foo", 4), "foo ",  "leftJustify foo,4 -> 'foo '");
  t.is (leftJustify ("foo", 5), "foo  ", "leftJustify foo,5 -> 'foo  '");
  t.is (leftJustify ("föo", 5), "föo  ", "leftJustify föo,5 -> 'föo  '");

  // std::string rightJustify (const std::string&, const int);
  t.is (rightJustify (123, 3), "123",   "rightJustify 123,3 -> '123'");
  t.is (rightJustify (123, 4), " 123",  "rightJustify 123,4 -> ' 123'");
  t.is (rightJustify (123, 5), "  123", "rightJustify 123,5 -> '  123'");

  // std::string rightJustify (const std::string&, const int);
  t.is (rightJustify ("foo", 3), "foo",   "rightJustify foo,3 -> 'foo'");
  t.is (rightJustify ("foo", 4), " foo",  "rightJustify foo,4 -> ' foo'");
  t.is (rightJustify ("foo", 5), "  foo", "rightJustify foo,5 -> '  foo'");
  t.is (rightJustify ("föo", 5), "  föo", "rightJustify föo,5 -> '  föo'");

  // int utf8_length (const std::string&);
  t.is ((int) utf8_length ("Çirçös"),            6, "utf8_length (Çirçös) == 6");
  t.is ((int) utf8_length ("ツネナラム"),        5, "utf8_length (ツネナラム) == 5");
  t.is ((int) utf8_length ("Zwölf Boxkämpfer"), 16, "utf8_length (Zwölf Boxkämpfer) == 16");

  return 0;
}
Ejemplo n.º 12
0
static int getAddress()
{
	struct ifreq ifr;
#ifndef SIOCGIFHWADDR	/* BSD、MacOS */
	struct ifaddrs *ifap, *p = NULL;
	struct sockaddr_dl *sdl;
#endif
	int sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0)
	{
		printf("!! 创建套接字失败!\n");
		return -1;
	}
	strcpy(ifr.ifr_name, nic);

#ifdef SIOCGIFHWADDR
	if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
		goto getMACError;
	memcpy(localMAC, ifr.ifr_hwaddr.sa_data, 6);
#else
	if (getifaddrs(&ifap) == 0)
	{
		for (p=ifap; p; p=p->ifa_next)
		{
			if (p->ifa_name && strcmp(p->ifa_name, nic)==0)
			{
				sdl = (struct sockaddr_dl *)p->ifa_addr;
				memcpy(localMAC, sdl->sdl_data + sdl->sdl_nlen, 6);
				break;
			}
		}
		freeifaddrs(ifap);
	}
	if (p == NULL)
		goto getMACError;
#endif

	if (startMode == 0)
		memcpy(destMAC, STANDARD_ADDR, 6);
	else if (startMode == 1)
		memcpy(destMAC, RUIJIE_ADDR, 6);

#ifndef NO_ARP
	gateMAC[0] = 0xFE;
	if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
		printf("!! 在网卡%s上获取IP失败!\n", nic);
	else {
		rip = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;
		if (gateway!=0 && (startMode%3!=2 || ((u_char *)&gateway)[3]!=0x02))
			gateMAC[0] = 0xFF;
	}
	if (dhcpMode!=0 || ip==-1)
		ip = rip;
#else
	if (dhcpMode!=0 || ip==-1) {
		if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
			printf("!! 在网卡%s上获取IP失败!\n", nic);
		else
			ip = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;
	}
#endif

	if (dhcpMode!=0 || mask==-1) {
		if (ioctl(sock, SIOCGIFNETMASK, &ifr) < 0)
			printf("!! 在网卡%s上获取子网掩码失败!\n", nic);
		else
			mask = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;
	}
	close(sock);

	printf("** 本机MAC:\t%s\n", formatHex(localMAC, 6));
	printf("** 使用IP:\t%s\n", formatIP(ip));
	printf("** 子网掩码:\t%s\n", formatIP(mask));
	return 0;

getMACError:
	close(sock);
	printf("!! 在网卡%s上获取MAC失败!\n", nic);
	return -1;
}
Ejemplo n.º 13
0
static void pcap_handle(u_char *user, const struct pcap_pkthdr *h, const u_char *buf)
{
	static unsigned failCount = 0;
	pthread_t thread_lan;

#ifndef NO_ARP
	if (buf[0x0c]==0x88 && buf[0x0d]==0x8e) {
#endif
		if (memcmp(destMAC, buf+6, 6)!=0 && startMode>2)	/* 服务器MAC地址不符 */
			return;
		capBuf = buf;
		if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x01) {	/* 验证用户名 */
			if (startMode < 3) {
				memcpy(destMAC, buf+6, 6);
				print_log(_("** 认证服务器MAC: %s\n"), formatHex(destMAC, 6));
				startMode += 3;	/* 标记认证服务器MAC为已获取,可以锁定 */
			}
			if (proxyMode == 0) {
				if (startMode==3 && memcmp(buf+0x17, "User name", 9)==0)	/* 塞尔 */
					startMode = 5;
				switchState(ID_IDENTITY);
			} else {
				if (proxyClientRequested == 1) {
					print_log(_(">> 服务器已请求用户名\n"));
					proxy_send_to_lan(buf, h->len);
				} else {
					print_log(_("!! 在代理认证完成后收到用户名请求,将重启认证!\n"));
					switchState(ID_WAITCLIENT);
				}
			}
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x04)	{ /* 验证密码 */
			if (proxyMode == 0) {
				switchState(ID_CHALLENGE);
			} else {
				if (proxyClientRequested == 1) {
					print_log(_(">> 服务器已请求密码\n"));
					proxy_send_to_lan(buf, h->len);
				} else {
					print_log(_("!! 在代理认证完成后收到密码请求,将重启认证!\n"));
					switchState(ID_WAITCLIENT);
				}
			}
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x03) {	/* 认证成功 */
			print_log(_(">> 认证成功!\n"));
			failCount = 0;
			proxySuccessCount++;
			if (proxyMode != 0) {
				proxy_send_to_lan(buf, h->len);
				if (proxySuccessCount >= proxyRequireSuccessCount) {
					pcap_breakloop(hPcapLan);
					proxyClientRequested = 0;
					proxySuccessCount = 0;
					memcpy(lastSuccessClientMAC, clientMAC, 6); // 备份本次认证成功的客户端MAC,用于通知掉线
					proxy_clear_client_mac(); // 重设MAC地址,以备下次使用不同客户端认证用
					print_log(_(">> 已关闭LAN监听线程\n"));
				}
			}
			if (!(startMode%3 == 2)) {
				getEchoKey(buf);
			}
			showRuijieMsg(buf, h->caplen);
			if (dhcpMode==1 || dhcpMode==2)	/* 二次认证第一次或者认证后 */
				switchState(ID_DHCP);
			else if (startMode%3 == 2)
				switchState(ID_WAITECHO);
			else
				switchState(ID_ECHO);
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x02)	/* 显示赛尔提示信息 */
			showCernetMsg(buf);
		else if (buf[0x0F] == 0x05)	/* (赛尔)响应在线 */
			switchState(ID_ECHO);
		else if (buf[0x0F]==0x00 && buf[0x12]==0x04) {  /* 认证失败或被踢下线 */
			if (state==ID_WAITECHO || state==ID_ECHO) {
				if (proxyMode == 0) {
					print_log(_(">> 认证掉线!\n"));
					showRuijieMsg(buf, h->caplen);
					if (restartOnLogOff) {
						print_log(_(">> 正在重新认证...\n"));
						switchState(ID_START);					
					} else {
						exit(1);
					}
				} else {
					pthread_create(&thread_lan, NULL, lan_thread, 0);
					print_log(_(">> 认证掉线,已发回客户端并重新启用对LAN的监听\n"));
					showRuijieMsg(buf, h->caplen);
					// clientMAC已经在成功时被清除了,所以使用lastSuccessClientMAC发送,发完清除
					memmove(clientMAC, lastSuccessClientMAC, 6);
					proxy_send_to_lan(buf, h->len);
					proxy_clear_client_mac();
					switchState(ID_WAITCLIENT);
				}
			}
			else if (buf[0x1b]!=0 || startMode%3==2) {
				print_log(_(">> 认证失败!\n"));
				showRuijieMsg(buf, h->caplen);
				if (maxFail && ++failCount>=maxFail) {
					print_log(_(">> 连续认证失败%u次,退出认证。\n"), maxFail);
					exit(EXIT_SUCCESS);
				}
				restart();
			} else {
				if (proxyMode == 0)
					switchState(ID_START);
				else
					switchState(ID_WAITCLIENT);
			}
		}
#ifndef NO_ARP
	} else if (gateMAC[0]!=0xFE && buf[0x0c]==0x08 && buf[0x0d]==0x06) {
		if (*(u_int32_t *)(buf+0x1c) == gateway) {
			char str[50];
			if (gateMAC[0] == 0xFF) {
				memcpy(gateMAC, buf+0x16, 6);
				print_log(_("** 网关MAC:\t%s\n"), formatHex(gateMAC, 6));
				sprintf(str, "arp -s %s %s", formatIP(gateway), formatHex(gateMAC, 6));
				system(str);
			} else if (buf[0x15]==0x02 && memcmp(&rip, buf+0x26, 4)==0
				&& memcmp(gateMAC, buf+0x16, 6)!=0) {
				print_log(_("** ARP欺骗:\t%s\n"), formatHex(buf+0x16, 6));
#ifndef NO_NOTIFY
				if (showNotify) {
					sprintf(str, _("欺骗源: %s"), formatHex(buf+0x16, 6));
					if (show_notify(_("MentoHUST - ARP提示"), str, 1000*showNotify) < 0)
						showNotify = 0;
				}
#endif
			}
		}
	}
#endif
}
Ejemplo n.º 14
0
static void pcap_handle_lan(u_char *user, const struct pcap_pkthdr *h, const u_char *buf)
{
	PACKET_HEADER* hdr = (PACKET_HEADER*)buf;
	int eap_type_int; // EAP中的type
	int eapol_type_int = hdr->eapol_hdr.type;
	MAC_CHECK_STATUS mac_status = proxy_check_mac_integrity(buf);

	switch (eapol_type_int) {
	case EAPOL_START:
		switch (mac_status) {
		case MAC_NOT_DEFINED:
			proxy_store_client_mac(buf); // 锁定客户端的MAC地址,以防不同设备的认证流程干扰
			print_log(_(">> 客户端%s正在发起认证\n"), formatHex(clientMAC, 6));
			proxyClientRequested = 1;
			switchState(ID_START);
			break;
		case MAC_CHECK_PASSED:
			if (proxySuccessCount < proxySuccessCount && (state == ID_ECHO || state == ID_WAITECHO)) {
				print_log(_("!! 客户端在认证完成后发送Start包,忽略\n"));
				goto DONE;
			} else {
				/* 这里一般是多次认证(-j参数大于1时) */
				print_log(_(">> 客户端%s再次发起认证\n"), formatHex(clientMAC, 6));
				switchState(ID_START);
			}
			break;
		case MAC_CHECK_FAILED:
			goto PROXY_INTERRUPTED;
		}
		break;
	case EAPOL_LOGOFF:
		switch (mac_status) {
		case MAC_CHECK_FAILED:
			goto PROXY_INTERRUPTED;
		case MAC_NOT_DEFINED:
			goto DONE;
		case MAC_CHECK_PASSED:
			print_log(_("!! 客户端要求断开认证,将忽略此请求\n"));
			goto DONE;
		}
	case EAP_PACKET:
		switch (mac_status) {
		case MAC_CHECK_FAILED:
			goto PROXY_INTERRUPTED;
		case MAC_NOT_DEFINED:
			goto DONE;
		case MAC_CHECK_PASSED:
			eap_type_int = hdr->eap_hdr.type;
			switch (eap_type_int) {
			case IDENTITY:
				print_log(_(">> 客户端已发送用户名\n"));
				break;
			case MD5_CHALLENGE:
				print_log(_(">> 客户端已发送密码\n"));
				break;
			}
			break;
		}
	}

	/*
	所有不需代理的情况均已处理完毕,
	现在将客户端发来的数据包中源MAC改为本设备的并发送出去
	*/
	proxy_send_to_wan(buf, h->len);
	goto DONE;

PROXY_INTERRUPTED:
	print_log(_("!! 认证流程受到来自%s的干扰!\n"), formatHex(hdr->eth_hdr.src_mac, 6));
DONE:
	return;
}