Last active
September 25, 2015 05:57
-
-
Save ph1ee/e968c99a5a3330bada7a to your computer and use it in GitHub Desktop.
Extract multipart messages from raw HTTP captures into individual files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * extract-multipart.cc | |
| * | |
| * This program extracts multipart messages from raw HTTP captures into | |
| * individual files. | |
| * | |
| * Usage: a.out <file ...> | |
| */ | |
| #include <iostream> | |
| #include <fstream> | |
| #include <string> | |
| #include <sstream> | |
| #include <iomanip> | |
| #include <cassert> | |
| using namespace std; | |
| enum { kMaxLength = 70 }; | |
| const string hyphens = "--"; | |
| const string match("boundary="); | |
| int main(int argc, char *argv[]) { | |
| int count = 0; | |
| for (int i = 1; i < argc; i++) { | |
| for (ifstream ifs(argv[i], ifstream::in); ifs; ifs.close()) { | |
| string boundary; | |
| for (string line; std::getline(ifs, line);) { | |
| if (line.find("Content-Type") != string::npos) { | |
| size_t pos = line.find(match); | |
| if (pos != string::npos) { | |
| pos += match.size(); // skip match pattern | |
| size_t end = line.find_first_of(" \r\n", pos); | |
| if ((end - pos) > 0) { | |
| boundary = line.substr(pos, end - pos); | |
| assert(boundary.size() <= kMaxLength); | |
| } | |
| } | |
| } | |
| if (line.size() > hyphens.size() && | |
| line.substr(0, hyphens.size()) == hyphens && | |
| line.substr(hyphens.size(), boundary.size()) == boundary) { | |
| string type; | |
| string lenInStr; | |
| ifs >> type >> type; | |
| ifs >> lenInStr >> lenInStr; | |
| int len = std::stoi(lenInStr); | |
| #ifdef DEBUG | |
| cout << "Content-Type: " << type << ", " | |
| << "Content-Length: " << len << endl; | |
| #endif | |
| // eat two newline characters | |
| std::getline(ifs, line); | |
| std::getline(ifs, line); | |
| string content(len, '\0'); | |
| ifs.read(&content[0], len); | |
| // add leading 0's | |
| std::ostringstream ss; | |
| ss << std::setw(4) << std::setfill('0') << count++; | |
| std::ofstream out(boundary + "_" + string(ss.str()) + ".dat"); | |
| out << content; | |
| out.close(); | |
| } | |
| } | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment