Skip to content

Instantly share code, notes, and snippets.

@daschr
Last active August 3, 2021 09:34
Show Gist options
  • Save daschr/f24c76947c9321a7fceb1a7b29a1b7ec to your computer and use it in GitHub Desktop.
Save daschr/f24c76947c9321a7fceb1a7b29a1b7ec to your computer and use it in GitHub Desktop.
update crc-32 of ldif files
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <zlib.h>
#define BUFSIZE 256
int update_checksum(const char *filename);
int main(int ac, char *as[]) {
if(ac<2) {
fprintf(stderr, "Usage: %s [file.ldif]\n", as[0]);
return EXIT_FAILURE;
}
return update_checksum(as[1]);
}
int update_checksum(const char *filename) {
FILE *f=NULL;
int tf=-1;
if((f=fopen(filename, "r"))==NULL)
return 1;
long int start_pos=0;
for(int c=fgetc(f), i=0; i<2; c=fgetc(f)) {
switch(c) {
case '\n':
++i;
break;
case -1:
return 1;
break;
default:
break;
}
++start_pos;
}
char buf[BUFSIZE];
unsigned long crc = crc32_z(0L, Z_NULL, 0);
size_t read_b=0;
fseek(f, start_pos, SEEK_SET);
do {
read_b=fread(buf, 1, BUFSIZE, f);
crc=crc32_z(crc, (const Bytef *) buf, read_b);
} while(read_b==BUFSIZE);
fseek(f, start_pos, SEEK_SET);
char tempf[]="/tmp/fileXXXXXX";
if((tf=mkstemp(tempf))==-1)
goto error;
dprintf(tf, "# AUTO-GENERATED FILE - DO NOT EDIT!! Use ldapmodify.\n"
"# CRC32 %lx\n", crc);
do {
read_b=fread(buf, 1, BUFSIZE, f);
dprintf(tf, "%.*s", (int) read_b, buf);
} while(read_b==BUFSIZE);
fclose(f);
close(tf);
struct stat f_stats;
memset(&f_stats, 0, sizeof(struct stat));
stat(filename, &f_stats);
rename(tempf, filename);
chown(filename, f_stats.st_uid, f_stats.st_gid);
chmod(filename, f_stats.st_mode);
return 0;
error:
if(f!=NULL) fclose(f);
if(tf!=-1) close(tf);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment