Skip to content

Instantly share code, notes, and snippets.

@masthoon
Created April 30, 2022 20:39
Show Gist options
  • Save masthoon/e888c10ee41e130977d257ab33f1ec7e to your computer and use it in GitHub Desktop.
Save masthoon/e888c10ee41e130977d257ab33f1ec7e to your computer and use it in GitHub Desktop.
bgrep.c
// dirty stolen code
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
char* PATTERN = "";
int PATTERN_LEN = 0;
void find_in_file(const char* filename) {
// Stupid 1 byte at a time
int fd = open(filename, O_RDONLY);
if (fd == -1)
return;
off_t off = lseek(fd, 0, SEEK_END);
if (off == -1)
return;
char* addr = mmap(NULL, off, PROT_READ, MAP_SHARED, fd, 0);
for (off_t i = 0 ; i < off ; i++) {
if (addr[i] == PATTERN[0] && (off - i) >= PATTERN_LEN) {
if (memcmp(&addr[i], PATTERN, PATTERN_LEN) == 0) {
printf("PATTERN FOUND %s at 0x%lx\n", filename, i);
munmap(addr, off);
close(fd);
return;
}
}
}
munmap(addr, off);
close(fd);
}
void listdir(const char *name, int indent)
{
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(name)))
return;
while ((entry = readdir(dir)) != NULL) {
char path[1024];
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// printf("%*s[%s]\n", indent, "", entry->d_name);
listdir(path, indent + 2);
} else {
// printf("%*s- %s\n", indent, "", entry->d_name);
find_in_file(path);
}
}
closedir(dir);
}
int hexchr2bin(const char hex, char *out)
{
if (out == NULL)
return 0;
if (hex >= '0' && hex <= '9') {
*out = hex - '0';
} else if (hex >= 'A' && hex <= 'F') {
*out = hex - 'A' + 10;
} else if (hex >= 'a' && hex <= 'f') {
*out = hex - 'a' + 10;
} else {
return 0;
}
return 1;
}
size_t hexs2bin(const char *hex, unsigned char **out)
{
size_t len;
char b1;
char b2;
size_t i;
if (hex == NULL || *hex == '\0' || out == NULL)
return 0;
len = strlen(hex);
if (len % 2 != 0)
return 0;
len /= 2;
*out = (unsigned char*)malloc(len);
memset(*out, 'A', len);
for (i=0; i<len; i++) {
if (!hexchr2bin(hex[i*2], &b1) || !hexchr2bin(hex[i*2+1], &b2)) {
return 0;
}
(*out)[i] = (b1 << 4) | b2;
}
return len;
}
int main(int argc, char** argv) {
if (argc == 2) {
PATTERN_LEN = hexs2bin(argv[1], (unsigned char **)&PATTERN);
if (PATTERN_LEN)
listdir(".", 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment