init on github

This commit is contained in:
eddyem 2015-07-23 13:53:23 +03:00
parent 78114fe2cd
commit f4ec4c3ae3
13 changed files with 1239 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
*~
*.bak
*.bck
*.o
.hg*
.dropbox.attr

125
DrawOnScreen.c Normal file
View File

@ -0,0 +1,125 @@
// use -std=gnu99 -lX11 2 compile
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/cursorfont.h>
int main(){
Display* display;
int screen_num;
Screen *screen;
Window root_win;
XGCValues gc_val;
XEvent report;
XButtonEvent *xb = (XButtonEvent *)&report;
XKeyEvent *xk = (XKeyEvent *)&report;
int status, x,y,oldx = -1, oldy = -1;
Cursor cursor;
display = XOpenDisplay(0);
if (display == NULL){
perror("Cannot connect to X server");
exit (-1);
}
//XGrabServer(display);
screen_num = DefaultScreen(display);
screen = XScreenOfDisplay(display, screen_num);
root_win = RootWindow(display, XScreenNumberOfScreen(screen));
cursor = XCreateFontCursor(display, XC_crosshair);
status = XGrabPointer(display, root_win, False,
ButtonReleaseMask | ButtonPressMask|Button1MotionMask, GrabModeSync,
GrabModeAsync, root_win, cursor, CurrentTime);
if(status != GrabSuccess){
perror("Can't grab the mouse");
exit(-1);
}
status = XGrabKeyboard(display, root_win, False,
GrabModeSync, GrabModeAsync, CurrentTime);
if(status != GrabSuccess){
perror("Can't grab the keyboard");
exit(-1);
}
gc_val.function = GXxor;
gc_val.plane_mask = AllPlanes;
gc_val.foreground = 0x00ff0000L;
gc_val.background = BlackPixel(display, screen_num);
gc_val.line_width = 3;
gc_val.line_style = LineSolid;
gc_val.cap_style = CapButt;
gc_val.join_style = JoinMiter;
gc_val.fill_style = FillOpaqueStippled;
gc_val.fill_rule = WindingRule;
gc_val.graphics_exposures = False;
gc_val.clip_x_origin = 0;
gc_val.clip_y_origin = 0;
gc_val.clip_mask = None;
gc_val.subwindow_mode = IncludeInferiors;
#define MKGC() XCreateGC(display, root_win, GCFunction | GCPlaneMask | GCForeground | GCBackground | GCLineWidth | GCLineStyle | \
GCCapStyle | GCJoinStyle | GCFillStyle | GCFillRule | GCGraphicsExposures | \
GCClipXOrigin | GCClipYOrigin | GCClipMask | GCSubwindowMode, &gc_val)
GC gc_red = MKGC();
gc_val.foreground = 0x0000ff00L;
GC gc_green = MKGC();
gc_val.foreground = 0x000000ffL;
GC gc_blue = MKGC();
GC *gc_cur = &gc_red;
do{
XAllowEvents(display, SyncPointer, CurrentTime);
XWindowEvent(display, root_win, ButtonMotionMask | KeyPressMask| ButtonPressMask | ButtonReleaseMask, &report);
switch(report.type){
case KeyPress: // color
switch(xk->keycode){
case 9: goto End; break; // ESC
case 27: gc_cur = &gc_red; break; // R
case 42: gc_cur = &gc_green; break; // G
case 56: gc_cur = &gc_blue; break; // B
}
break;
case MotionNotify:
xb->button = 1;
case ButtonPress:
x = xb->x_root, y = xb->y_root;
switch(xb->button){
case 1:
if(oldx>-1 && oldy>-1)
XDrawLine(display, root_win, *gc_cur,
oldx, oldy, x, y);
oldx = x; oldy = y;
break;
case 2:
if(oldx>-1 && oldy>-1){
int lx,ly,rx,ry;
lx = (oldx < x) ? oldx : x;
ly = (oldy < y) ? oldy : y;
rx = (oldx > x) ? oldx : x;
ry = (oldy > y) ? oldy : y;
XDrawRectangle(display, root_win, *gc_cur,
lx, ly, rx-lx, ry-ly);
oldx = -1; oldy = -1;
}else{
oldx = x; oldy = y;}
break;
case 3:
if(oldx>-1 && oldy>-1)
XDrawLine(display, root_win, *gc_cur,
oldx, oldy, x, y);
oldx = x; oldy = y;
break;
}
break;
case ButtonRelease:
if(xb->button == 1){oldx = -1; oldy = -1;}
break;
}
}while(1);
End:
XFlush(display);
XUngrabServer(display);
XCloseDisplay( display );
return 0;
}

14
README Normal file
View File

@ -0,0 +1,14 @@
run ./compile to compile all
run ./compile {filename} to compile only one file
book_table.c Generates a list of pages to print a book
chartable.c List of charset table
lowercase.c Renames files into lowercase
mydiff.c Simple diff without sort need
parsesquid.c Parce suid log
charset.c Try to guess charset
recdecode.c Decode .rec-files of tricolor satellite receiver
swapfiles.c Swap contents of 2 files
file_histogram.c Simple histogram of file sizes in current directory
DrawOnScreen.c Allows 2 draw on screen by mouse + change color ('r', 'g', 'b'); 'Esc' - stop

69
book_table.c Normal file
View File

@ -0,0 +1,69 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//use: tofile [-f] <total pages> [pages-in-pamphlet]
FILE* f;
int i,total,b,ii,ost,tp;
int tostd=1;//if prints to std -- adds comments to it
void first(int N, int i)
{
int tp4 = (int)N/4;
if (tostd)
printf("\tside # 1\n");
fprintf(f,"\n");
for (ii=1; ii<tp4; ii++){
fprintf(f, "%d,%d,", tp*i+N-2*ii+2, tp*i+2*ii-1);
}
fprintf(f, "%d,%d", tp*i+N-2*tp4+2, tp*i+2*tp4-1);
fprintf(f,"\n");
}
void second(int N, int i)
{
int tp4 = (int)N/4;
if (tostd)
printf("\tside # 2\n");
for (ii=1; ii<tp4; ii++){
fprintf(f, "%d,%d,", tp*i+2*tp4-2*ii+2, tp*i+2*tp4-1+2*ii);
}
fprintf(f, "%d,%d", tp*i+2, tp*i+4*tp4-1);
fprintf(f,"\n");
}
int main(int argc, char** argv)
{
// printf("1:%s", argv[1]);
if ( strcmp(argv[1], "-f") == 0 ){
f = fopen("table", "w");
--argc;
++argv;
tostd=0;
}
else f = stdout;
// printf("\n2:%s", argv[1]);
total=atoi(argv[1]);
tp=32;
if ( argc > 2)
tp=atoi(argv[2]);
b = (int)total/tp;
ost=total%tp;
if (ost%4 > 0 || tp%4 >0){
fprintf(stderr, "þÉÓÌÏ ÓÔÒÁÎÉÃ ÎÅ ÄÅÌÉÔÓÑ ÎÁ 4");
return(1);
}
for (i=0; i < b; i++){
if (tostd)
printf("\nTetrad' # %d\n", i+1);
first(tp,i);
second(tp,i);
}
if ( ost>0 ){
if (tostd)
printf("\nLast tetrad'\n");
first(ost,b);
second(ost,b);
}
fclose(f);
return 0;
}

92
charset.c Normal file
View File

@ -0,0 +1,92 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
unsigned char c[3][128]={
"<EFBFBD>ƒ„…†‡ˆ‰ŠŒ<EFBFBD>Ž<EFBFBD><EFBFBD>“”•˜™šœ<EFBFBD>žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
"???????????????????????????????? ???????³¿??????œ??????ž£???????áâ÷çäåöúéêëìíîïðòóôõæèãþûýÿùøüàñÁÂ×ÇÄÅÖÚÉÊËÌÍÎÏÐÒÓÔÕÆÈÃÞÛÝßÙØÜÀÑ",
"áâ÷çäåöúéêëìíîïðòóôõæèãþûýÿùøüàñÁÂ×ÇÄÅÖÚÉÊËÌÍÎÏÐ<EFBFBD><EFBFBD>‡²´§¦µ¡¨®­¬ƒ„‰ˆ†€Š¯°«¥»¸± ¾¹º¶·ª©¢¤½¼…<EFBFBD>ŒŽ<EFBFBD>ÒÓÔÕÆÈÃÞÛÝßÙØÜÀѳ£??????œ•ž–??” "};
char encode(const int ch, const int i){ //returns encoding letter
char ret;
if (ch == 13) ret = 10;
else
if (ch < 128) ret = ch;
else
ret = c[i][ch%256 - 128];
return ret;
}
int recognize(FILE* f){ //asks to recognize encoding
char* ans=(char*) malloc(128);
int i,ch,ii;
if (f==NULL){
printf("Cannot open file\n");
exit(4);
}
printf("\n");
for (i=0; i<3; i++){
ch=fgetc(f);
ii=0;
while(ch != EOF){
if (ch>127){
++ii;
if (ii<256) putchar(encode(ch,i));
else
break;
}
ch=fgetc(f);
}
rewind(f);
printf("\n\nIs it right?[n]\n");
scanf("%s",ans);
if(strcmp(ans,"y")==0 || strcmp(ans,"yes")==0) return i;
}
printf("\n\t\t\tUndefined codepage!!!\n\n");
return 0;
}
int main(int argc, char** argv){
int x,i,l;
char name[128];
FILE *f, *f1;
if(argc<2){
printf("\nError! Need at least 1 argument!!!\n");
exit(1);
}
int global=0; //asks to recognize only once
if(strcmp(argv[1],"cp1251")==0 || strcmp(argv[1],"CP1251")==0){
--argc; ++argv;
global=1;
x=1;
}
if(strcmp(argv[1],"-r")==0 && global != 1){
printf("Recognize first file\n");
--argc; ++argv; //analog of shell's "shift"
global=1;
f=fopen(argv[1],"r");
x=recognize(f);
fclose(f);
}
for (i=1; i<argc; i++){
f=fopen(argv[i],"r");
if (global==0) x=recognize(f);
sprintf(name, "enc.%d", i);
f1=fopen("tmp_encode","w");
l=fgetc(f);
while(l!=EOF){
fputc(encode(l,x),f1); //this is encoding itself
l=fgetc(f);
}
fclose(f1);
fclose(f);
unlink(argv[i]);//rename tmp->argv[i]
if(link("tmp_encode",argv[i])<0)
printf("error moving file %s\n",argv[i]);
unlink("tmp_encode");
printf("File %s is done\n",argv[i]);
}
printf("\nAll files are processed!!!\n");
return 0;
}

25
chartable.c Normal file
View File

@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define UC unsigned char
int main(int argc, char* argv []){
UC code;
int ii,i;
printf("\n");
if(argc > 1){
if(isdigit(*argv[1])){
code=(UC)atoi(argv[1]);
printf("Code %3d is letter %c\n", code, code);
exit (0);}
else{
code=(UC)*argv[1];
printf("Char %c is %3d\n", code, code);}}
else{
for(i=0; i<32; i++){
for(ii=1; ii<8; ii++){
code=(UC)(i+ii*32);
printf("%3d [0x%x] - %c\t", code, code, code);}
printf("\n");}}
return 0;
}

14
compile Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
function compile_file(){
Name="$(echo "$1" | sed "s/\(.*\)\.c/\1/")"
gcc -Wall -Werror -lX11 -lm -lpthread "${Name}.c" -o "$Name"
}
if [ "$1" != "" ]; then
compile_file "$1"
else
for file in *.c; do
compile_file "$file"
done
fi
rm -f *.o

305
file_histogram.c Normal file
View File

@ -0,0 +1,305 @@
#define _GNU_SOURCE
#include <sys/types.h> // opendir, closedir
#include <dirent.h> // opendir, closedir
#include <string.h> // strdup
#include <unistd.h> // getcwd, chdir
#include <stdio.h> // perror
#include <stdlib.h> // exit, calloc
#include <sys/stat.h> // stat
#include <sys/time.h> // gettimeofday
#include <getopt.h> // getopt_long
#include <math.h> // log
extern const char *__progname;
long long *histogram; // histogram of file sizes
long long StarAmount = 30LL; // max number of stars in histogram
int histosize = 15; // size of histogram
double d_histosize; // -//-
double MAXsize; // max file size
// simple indicator
char *indicator[] = {"|","/","-","\\"};
int indi = 0; // char in indicator
// keys
int
follow_links = 0 // follow symbolic links
,show_histogram = 0 // show histogram
,FS = 'H' // file size format (default - human)
,HS = 'l' // histogram format (default - linear)
;
// pointer to lstat or stat (depends on follow_links key)
int (*Stat)(const char *path, struct stat *buf);
// pointer to function, which will make histogram
int (*Hist)(off_t sz);
// file & directories counters
long long fcounter = 0LL, dcounter = 0LL, lcounter = 0LL;
char maxname[PATH_MAX]; // name of biggest file
off_t maxsize = 0; // size of biggest file
// returns current time (double value)
double dtime(){
double t;
struct timeval tv;
gettimeofday(&tv, NULL);
t = tv.tv_sec + ((double)tv.tv_usec)/1e6;
return t;
}
// linear histogram
int linhist(off_t sz){
double s = (double)sz / MAXsize;
int r = (int)(s * d_histosize-0.5);
if(r < 0) r = 0;
return (r > histosize) ? histosize : r;
}
// log histogram
int loghist(off_t sz){
double s = log((double)sz / MAXsize * (M_E + 1.) + 1.);
int r = (int)(s * d_histosize - 0.5);
if(r < 0) r = 0;
return (r < histosize) ? r : histosize - 1;
}
// help
void usage(){
printf("\nUsage:\t%s [options] <path to directory>\n", __progname);
printf("Options:\n");
printf("\t-h,\t--help\t\t\tshow this help\n");
printf("\t-l,\t--follow-link\t\tfollow symbolic links\n");
printf("\t-s,\t--show-histogram\tshow simple histogram of file's size\n");
printf("\t-L,\t--log\t\t\thistogram in log format\n");
printf("\tFile size:\n");
printf("\t-K,\t--kilobytes\t\tSize in Kilobytes\n");
printf("\t-M,\t--megabytes\t\tSize in Megabytes\n");
printf("\t-G,\t--gigabytes\t\tSize in Gigabytes\n");
printf("\t-H,\t--human-readable\t(default) depends on file size\n");
printf("\n");
exit(0);
}
// process directory path, oldWD - old working directory
void proc_dir(char *path, char *oldWD){
DIR *dir;
struct dirent *de;
struct stat statbuf;
char msg[1025];
char curname[PATH_MAX];
off_t size;
printf("work... %s\r", indicator[indi++]); // simple indicator
if(indi>3) indi = 0;
fflush(stdout);
if(chdir(path)){
perror("Can't change directory");
return;
}
if(!(dir = opendir(path))){
snprintf(msg, 1024, "Couldn't open dir %s", path);
perror(msg);
return;
}
while((de = readdir(dir)) != NULL){
if(!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
if(path[strlen(path)-1] == '/')
snprintf(curname, PATH_MAX-1, "%s%s", path, de->d_name);
else
snprintf(curname, PATH_MAX-1, "%s/%s", path, de->d_name);
if(Stat(de->d_name, &statbuf)){
snprintf(msg, 1024, "Can't STAT %s", curname);
perror(msg);
continue;
}
if(S_ISLNK(statbuf.st_mode)){
lcounter++;
if(!follow_links) continue;
}
size = statbuf.st_size;
if(S_ISDIR(statbuf.st_mode)){
dcounter++;
proc_dir(curname, path);
}else if(S_ISREG(statbuf.st_mode)){
fcounter++;
if(size > maxsize){
maxsize = size;
strncpy(maxname, curname, PATH_MAX-1);
}
}
}
if(oldWD) chdir(oldWD);
closedir(dir);
}
// process directory path to make histogram (without err messages)
void proc_dir_hist(char *path, char *oldWD){
DIR *dir;
struct dirent *de;
struct stat statbuf;
char curname[PATH_MAX];
printf("work... %s\r", indicator[indi++]); // simple indicator
if(indi>3) indi = 0;
fflush(stdout);
if(chdir(path)) return;
if(!(dir = opendir(path))) return;
while((de = readdir(dir)) != NULL){
if(!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
if(Stat(de->d_name, &statbuf)) continue;
if(!follow_links && S_ISLNK(statbuf.st_mode)) continue;
if(S_ISDIR(statbuf.st_mode)){
if(path[strlen(path)-1] == '/')
snprintf(curname, PATH_MAX-1, "%s%s", path, de->d_name);
else
snprintf(curname, PATH_MAX-1, "%s/%s", path, de->d_name);
proc_dir_hist(curname, path);
}else if(S_ISREG(statbuf.st_mode)){
histogram[Hist(statbuf.st_size)]++;
}
}
if(oldWD) chdir(oldWD);
closedir(dir);
}
double size_in_units(off_t sz, int *unit){
double s = (double) sz;
int i = 0;
switch(FS){
case 'G':
s /= 1024.; // giga
i++;
case 'M':
s /= 1024.; // mega
i++;
case 'K':
s /= 1024.; // kilo
i++;
break;
default:
while(s > 1024. && ++i < 4) s /= 1024.;
}
if(i > 3) i = 3;
if(unit) *unit = i;
return s;
}
// Prints file size in human readable format (depends on FS key)
char* pretty_size(off_t sz){
static char buf[256];
char *units[4] = {"B", "KB", "MB", "GB"};
int i;
double s = size_in_units(sz, &i);
snprintf(buf, 255, "%.3f%s", s, units[i]);
return buf;
}
void print_stars(long long n, long long MaxNum){
int i, N = (int)(n * StarAmount / MaxNum);
for(i = 0; i < N; i++) printf("*");
printf("\n");
}
void print_histo(){
int i;
double histunit = MAXsize / d_histosize;
long long MaxNum = 0LL; // max number of files
for(i = 0; i < histosize; i++)
if(histogram[i] > MaxNum) MaxNum = histogram[i];
if(Hist == linhist)
for(i = 0; i < histosize; i++){
printf("%12s%8lld ", pretty_size((off_t)(histunit * i)), histogram[i]);
print_stars(histogram[i], MaxNum);
}
else // log format
for(i = 0; i < histosize; i++){
double s = (exp((double)i / d_histosize) - 1.) * MAXsize / (M_E + 1.);
printf("%12s%8lld ", pretty_size((off_t)s), histogram[i]);
print_stars(histogram[i], MaxNum);
}
}
int main(int argc, char **argv){
char short_options[] = "lhsGHKML";
struct option long_options[] = {
{"help", 0, 0, 'h'},
{"follow-link", 0, 0, 'l'},
{"show-histogram", 0, 0, 's'},
{"human-readable", 0, 0, 'H'},
{"kilobytes", 0, 0, 'K'},
{"megabytes", 0, 0, 'M'},
{"gigabytes", 0, 0, 'G'},
{"log", 0, 0, 'L'},
{ 0, 0, 0, 0 }
};
DIR *dir;
char *path = NULL, *wd = NULL;
double Time0 = dtime();
Stat = lstat;
Hist = linhist;
while (1){
int opt;
if((opt = getopt_long(argc, argv, short_options,
long_options, NULL)) == -1) break;
switch(opt){
case 'h':
usage();
break;
case 'l':
follow_links = 1;
Stat = stat;
break;
case 's':
show_histogram = 1;
break;
case 'H': break; // default
case 'K': case 'M': case 'G':
FS = opt;
break;
case 'L':
Hist = loghist;
break;
default:
usage();
}
}
d_histosize = (double) histosize;
argc -= optind;
argv += optind;
wd = get_current_dir_name();
if(argc == 0) path = strdup(wd);
else path = strdup(argv[0]);
if(!(dir = opendir(path))){
perror("Couldn't open dir, try to open CWD");
if(!(dir = opendir(wd))){
perror("Couldn't open CWD, die");
exit(1);
}else{
free(path);
path = strdup(wd);
}
}
closedir(dir);
proc_dir(path, wd);
printf("Done!!! \n");
if(maxsize){
printf("\nBiggest file: %s with size=%s\n", maxname, pretty_size(maxsize));
printf("Processed: %lld files in %lld directories", fcounter, dcounter);
if(!follow_links) printf("; %lld symlinks dropped\n\n", lcounter);
else printf("\n\n");
}else
printf("\nDirectory %s doesn't contain non-empty files\n", path);
if(show_histogram){
histogram = calloc(histosize, sizeof(long long));
if(!histogram){
perror("Can't allocate memory for histogram");
exit(1);
}
MAXsize = (double)maxsize;
printf("Make histogram.\n");
proc_dir_hist(path, wd);
printf("Done!!! \n");
print_histo();
}
printf("Time of work: %.3fs\n", dtime() - Time0);
free(wd); free(path);
return 0;
}

57
lowercase.c Normal file
View File

@ -0,0 +1,57 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>
#define BUFFSIZE 1024
char *file;
char file1[BUFFSIZE];
char *basename;
char *newfile;
char to_lower(char ch){
int ret = (int)ch;
if (isupper(ret))
ret = tolower(ret);
if (ret > 223)
ret = ret - 32;
if (ret == 179)
ret = 163;
return (char)ret;
}
void usage(int err)
{
switch (err){
case 0: printf("\tYou have missed filename\n");
break;
case 1: printf("\tFile %s dosen't exists or permissions denied\n", file);
break;
default: printf("\tToo many parameters\n");
break;
}
printf("\t\tUsage:\n\t%s <filename>\n", basename);
exit (1);
}
int main(int argc, char* argv[])
{
basename = argv[0];
if (argc < 2) usage(0);
file = strdup(argv[1]);
newfile = file;
strncpy(file1, file, BUFFSIZE-1);
if (argc > 2) usage(2);
while (*file++)
*file = to_lower(*file);
link(file1, newfile);
unlink(file1);
return 0;
}

52
mydiff.c Normal file
View File

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>
void help(char* name){
printf("\nUsage:\n\t%s <file1> <file2>\n\t\tprint lines of <file1>, that not present in <file2>\n", name);
printf("\t%s -v <file1> < file2>\n\t\tshows lines of <file1>, that present in <file2>\n", name);
exit(0);
}
int main(int argc, char** argv){
char *buf, *F1, *F2, *ptr, *ptr1;
int file1, file2, n = 0, Vflag = 0;
long size1, size2;
struct stat St;
if(argc < 3 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) help(argv[0]);
if(strcmp(argv[1], "-v") == 0){ Vflag = 1; n = 1;}
if( stat(argv[n+1], &St) < 0) err(1, "\n\tCan't stat %s", argv[n+1]);
size1 = St.st_size;
if( stat(argv[n+2], &St) < 0) err(2, "\n\tCan't stat %s", argv[n+2]);
size2 = St.st_size;
file1 = open(argv[n+1], O_RDONLY);
if(file1 < 0) err(3, "\n\tCan't open %s", argv[n+1]);
file2 = open(argv[n+2], O_RDONLY);
if(file2 < 0) err(4, "\n\tCan't open %s", argv[n+2]);
buf = malloc(16385); // ÂÕÆÅÒ ÄÌÑ ÓÔÒÏËÉ
F1 = malloc(size1 + 1); // ÓÏÄÅÒÖÉÍÏÅ ÆÁÊÌÁ 1
ptr1 = F1;
F2 = malloc(size2 + 1); // ÓÏÄÅÒÖÉÍÏÅ ÆÁÊÌÁ 2
if(read(file1, F1, size1) != size1) err(5, "\n\tCan't read %s", argv[n+1]);
F1[size1] = 0;
close(file1);
if(read(file2, F2, size2) != size2) err(6, "\n\tCan't read %s", argv[n+2]);
F2[size2] = 0;
close(file2);
while(ptr1){
ptr = strchr(ptr1, '\n');
if(ptr) *ptr = 0;
strncpy(buf, ptr1, 16384);
if(strstr(F2, buf) == NULL){ if (Vflag == 0) printf("%s\n", buf);}
else if(Vflag == 1) printf("%s\n", buf);
if(ptr) ptr1 = ptr + 1;
else ptr1 = NULL; // ËÏÎÅÃ ÓÔÒÏËÉ
}
free(buf); free(F1); free(F2);
exit(0);
}

276
parsesquid.c Normal file
View File

@ -0,0 +1,276 @@
#define _FILE_OFFSET_BITS 64
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <time.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define CACHE_FILE "/tmp/.parsesquid_cache"
#define LOG_FILE "/var/log/squid/access.log"
#define TIME_INTERVAL 25000
#define NEW 0
#define UPDATE 1
struct idx{
int time;
off_t offset;
} s_cache;
void help(const char* name){
printf("\néÓÐÏÌØÚÏ×ÁÎÉÅ:\n%s [ëÌÀÞÉ]\n÷ÙÄÁÅÔ ÉÎÆÏÒÍÁÃÉÀ Ï ÔÒÁÆÉËÅ, ÐÏÌÕÞÅÎÎÏÍ ÉÚ×ÎÅ É ÉÚ ËÅÛÁ ÐÒÏËÓÉ\n", name);
printf("\t-h\t--help\t\t\tüÔÏ ÓÏÏÂÝÅÎÉÅ\n");
printf("\t-f\t--from äáôá\t\tõËÁÚÁÔØ ÄÁÔÕ, Ó ËÏÔÏÒÏÊ ÎÅÏÂÈÏÄÉÍÏ ÎÁÞÁÔØ ÐÏÄÓÞÅÔ\n");
printf("\t-t\t--to äáôá\t\tõËÁÚÁÔØ ÄÁÔÕ, ÎÁ ËÏÔÏÒÏÊ ÎÅÏÂÈÏÄÉÍÏ ÚÁËÏÎÞÉÔØ ÐÏÄÓÞÅÔ\n");
printf("\t-a\t--address addr\t\tõËÁÚÁÔØ ÞÁÓÔØ ÉÍÅÎÉ ÓÁÊÔÁ, ÄÌÑ ËÏÔÏÒÏÇÏ ÐÒÏÉÚ×ÏÄÉÔØ ÐÏÄÓÞÅÔ\n");
printf("\t-u\t--update\t\tïÂÎÏ×ÉÔØ ÉÎÄÅËÓÎÙÊ ÆÁÊÌ\n");
printf("\t-n\t--new\t\túÁÎÏ×Ï ÓÏÚÄÁÔØ ÉÎÄÅËÓÎÙÊ ÆÁÊÌ\n");
printf("\næÏÒÍÁÔ ÄÁÔÙ: ä/í/ç-Þ:Í, ä/í/ç, Þ:Í, ä/í, í\n\n");
exit(0);
}
int get_date(char *line){
time_t date;
struct tm time_, time_now;
time(&date);
time_now = *localtime(&date);
time_.tm_sec = 0;
if(sscanf(line, "%d/%d/%d-%d:%d", &time_.tm_mday, &time_.tm_mon, &time_.tm_year,
&time_.tm_hour, &time_.tm_min) == 5){time_.tm_mon -= 1;}
else if(!strchr(line, ':') && sscanf(line, "%d/%d/%d", &time_.tm_mday, &time_.tm_mon, &time_.tm_year) == 3){
date = -1; time_.tm_mon -= 1;}
else if(!strchr(line, ':') && sscanf(line, "%d/%d", &time_.tm_mday, &time_.tm_mon) == 2){
date = -1; time_.tm_mon -= 1; time_.tm_year = time_now.tm_year;}
else if(sscanf(line, "%d:%d", &time_.tm_hour, &time_.tm_min) == 2){
time_.tm_year = time_now.tm_year; time_.tm_mon = time_now.tm_mon;
time_.tm_mday = time_now.tm_mday;}
else if(!strchr(line, ':') && !strchr(line, '/') && !strchr(line, '.') && !strchr(line, '-')
&& sscanf(line, "%d", &time_.tm_mon) == 1){
date = -1; time_.tm_mon -= 1; time_.tm_year = time_now.tm_year;
time_.tm_mday = 1;}
else{
printf("\nîÅ×ÅÒÎÙÊ ÆÏÒÍÁÔ ×ÒÅÍÅÎÉ!\n");
printf("æÏÒÍÁÔÙ: D/M/Y-hh:mm, D/M/Y, hh:mm, D/M, M\n");
exit(1);
}
if(date == -1){
time_.tm_hour = 0;
time_.tm_min = 0;
}
if(time_.tm_mon > 11 || time_.tm_mon < 0){
printf("\níÅÓÑà ×ÎÅ ÄÉÁÐÁÚÏÎÁ 1..12\n");
exit(2);
}
if(time_.tm_mday > 31 || time_.tm_mday < 1){
printf("\nþÉÓÌÏ ÍÅÓÑÃÁ ×ÎÅ ÄÉÁÐÁÚÏÎÁ 1..31, %d\n", time_.tm_mday);
exit(3);
}
if(time_.tm_year > 1900) time_.tm_year -= 1900;
else if(time_.tm_year > -1 && time_.tm_year < 100) time_.tm_year += 100;
else if(time_.tm_year < 0 || time_.tm_year > 200){
printf("\nîÅ×ÅÒÎÙÊ ÆÏÒÍÁÔ ÇÏÄÁ %d\n", time_.tm_year);
exit(4);
}
if(time_.tm_hour > 23 || time_.tm_hour < 0){
printf("\n÷ÒÅÍÑ ×ÎÅ ÄÉÁÐÁÚÏÎÁ 0..23 ÞÁÓÁ\n");
exit(5);
}
if(time_.tm_min > 59 || time_.tm_min < 0){
printf("\n÷ÒÅÍÑ ×ÎÅ ÄÉÁÐÁÚÏÎÁ 0..59 ÍÉÎÕÔ\n");
exit(6);
}
date = mktime(&time_);
#ifdef DEBUG
printf("date: %d\n", date);
#endif
return (int)date;
}
void makecache(unsigned char flag){
int f_log, cache = open(CACHE_FILE, O_CREAT|O_RDWR, 00644);
off_t offset = 0, tmp = 0;
if(cache < 0){
printf("\nîÅ ÍÏÇÕ ÓÏÚÄÁÔØ ÉÎÄÅËÓ-ÆÁÊÌ\n");
exit(7);
}
if(flag == UPDATE){
if((tmp = lseek(cache, -((off_t)(sizeof(struct idx))), SEEK_END)) > 0){
if(read(cache, &s_cache, sizeof(struct idx)) > 0){
offset = s_cache.offset;
}
}
#ifdef EBUG
printf("off=%lld\n", offset);
#endif
}
off_t len = 0;
char *string = NULL;
struct stat filestat;
FILE *log = fopen(LOG_FILE, "r");
if(!log){
printf("\nîÅ ÍÏÇÕ ÏÔËÒÙÔØ " LOG_FILE " \n");
exit(8);
}
f_log = fileno(log);
if(flag == NEW) printf("\nóÏÚÄÁÀ ÉÎÄÅËÓÎÙÊ ÆÁÊÌ\n");
else printf("\nïÂÎÏ×ÌÑÀ ÉÎÄÅËÓÎÙÊ ÆÁÊÌ\n");
if(stat(LOG_FILE, &filestat) != 0){
printf("\nïÛÉÂËÁ, " LOG_FILE ": ÎÅ ÍÏÇÕ ÓÄÅÌÁÔØ stat\n");
exit(10);
}
if(lseek(f_log, offset, SEEK_SET) != 0){
printf("\n÷ÎÉÍÁÎÉÅ: " LOG_FILE " ÕÓÔÁÒÅÌ, ÏÂÎÏ×ÌÑÀ ÉÎÄÅËÓÎÙÊ ÆÁÊÌ ÐÏÌÎÏÓÔØÀ\n");
offset = 0;
}
s_cache.offset = offset;
if(getline(&string, (size_t*)&len, log) < 1){
printf("\nïÛÉÂËÁ: " LOG_FILE "ÐÕÓÔ\n");
exit(9);
}
off_t dataportion = filestat.st_size / 100;
int indpos = 1;
int frac = 0;
if(offset > 0) frac = atoi(string) / TIME_INTERVAL;
do{
if( ( tmp = ((s_cache.time = atoi(string)) / TIME_INTERVAL)) != frac ){
write(cache, &s_cache, sizeof(struct idx));
#ifdef DEBUG
printf("ÏÞÅÒÅÄÎÁÑ ÓÔÒÏËÁ, ×ÒÅÍÑ: %d, ÓÍÅÝÅÎÉÅ: %lld, sizeof(s_cache)=%d\n", s_cache.time, s_cache.offset, sizeof(struct idx));
#endif
frac = tmp;
}
s_cache.offset = lseek(f_log, 0, SEEK_CUR);
if( (tmp = s_cache.offset / dataportion) > indpos ){
if( (tmp % 10) == 0) printf(" %lld%% ", (long long)tmp);
else printf(".");
indpos = tmp;
fflush(stdout);
}
} while(getline(&string, (size_t*)&len, log) > 0);
printf("\nçÏÔÏ×Ï!\n");
free(string);
close(cache);
fclose(log);
}
int count_bytes(off_t from_offset, off_t to_offset, int from_date, int to_date, char* addr){
off_t dataportion = (to_offset - from_offset) / 100, tmp, indpos = 0;
long long bytes_from_outside = 0, bytes_from_cache = 0;
char* string = NULL;
off_t len = 0, curpos;
int time, bytes;
FILE *log = fopen(LOG_FILE, "r");
int f_log = fileno(log);
lseek(f_log, from_offset, SEEK_SET);
while(getline(&string, (size_t*)&len, log) > 0){
time = atoi(string);
curpos = lseek(f_log, 0, SEEK_CUR) - from_offset;
if( (tmp = curpos / dataportion) > indpos){
if( (tmp % 10) == 0) printf(" %lld%% ", (long long)tmp);
else printf(".");
indpos = tmp;
fflush(stdout);
}
if(time < from_date) continue;
else if(time > to_date) break;
sscanf(string, "%*s %*s %*s %*s %d", &bytes);
if(addr)
if(!strcasestr(string, addr)) continue;
if(strstr(string, "NONE")) bytes_from_cache += bytes;
else bytes_from_outside += bytes;
}
if(addr) printf("\nðÏÉÓË ÐÏ ÐÏÄÓÔÒÏËÅ URI: \"%s\"", addr);
printf("\nðÏÌÕÞÅÎÏ ÉÎÆÏÒÍÁÃÉÉ\n\t\tÉÚ ÍÉÒÁ: %lld ÂÁÊÔ (%.2f íâ);\n\t\tÉÚ ËÜÛÁ: %lld ÂÁÊÔ (%.2f íâ)\n",
bytes_from_outside, (double)bytes_from_outside/1024./1024., bytes_from_cache,
(double)bytes_from_cache/1024./1024.);
free(string);
fclose(log);
return(time);
}
int main(int argc, char** argv){
int from_date = 0, to_date = INT_MAX, last_cache_time, last_log_time;
struct stat filestat;
char* const short_options = "hf:t:una:";
char *addr = NULL;
struct option long_options[] = {
{ "help", 0, NULL, 'h'},
{ "from", 1, NULL, 'f'},
{ "to", 1, NULL, 't'},
{ "update", 0, NULL, 'u'},
{ "new", 0, NULL, 'n'},
{ "address", 1, NULL, 'a'},
{ NULL, 0, NULL, 0 }
};
int next_option;
do{
next_option = getopt_long(argc, argv, short_options, long_options, NULL);
switch(next_option){
case 'h': help(argv[0]);
break;
case 'f': from_date = get_date((char*)optarg);
break;
case 't': to_date = get_date((char*)optarg);
break;
case 'u': makecache(UPDATE); exit(0);
break;
case 'n': makecache(NEW); exit(0);
break;
case 'a': addr = strdup(optarg);
break;
}
}while(next_option != -1);
if(stat(CACHE_FILE, &filestat) != 0) makecache(NEW);
else if(filestat.st_size == 0) makecache(NEW);
int cache = open(CACHE_FILE, O_RDONLY);
off_t bytes_read;
unsigned char find_from = 1;
off_t from_offset = 0, to_offset = 0;
bytes_read = read(cache, &s_cache, sizeof(s_cache));
#ifdef DEBUG
printf("\nfirst, time=%d, from=%lld\n", s_cache.time, s_cache.offset);
#endif
while(bytes_read == sizeof(struct idx)){
#ifdef DEBUG
printf("\ntime=%d, from=%lld, idxpos=%lld\n", s_cache.time, s_cache.offset, lseek(cache, 0, SEEK_CUR));
#endif
if( (last_cache_time = s_cache.time) >= from_date && find_from){
find_from = 0;
from_offset = s_cache.offset;
}
else if(s_cache.time >= to_date)
to_offset = s_cache.offset;
bytes_read = read(cache, &s_cache, sizeof(struct idx));
}
close(cache);
if(find_from){
printf("\nîÁÞÁÌØÎÁÑ ÄÁÔÁ ÐÏÉÓËÁ ÓÔÁÒÛÅ ÐÏÓÌÅÄÎÅÊ ÚÁÐÉÓÉ ÌÏÇÏ×\n");
exit(11);
}
if(to_offset == 0){
stat(LOG_FILE, &filestat);
to_offset = filestat.st_size;
}
if(to_offset <= from_offset){
printf("\nîÅ×ÅÒÎÏ ×ÙÂÒÁÎÙ ÎÁÞÁÌÏ É ËÏÎÅà ÄÉÁÐÁÚÏÎÁ ÄÁÔ,\n"
"\tÌÉÂÏ Ó×ÅÄÅÎÉÑ ÚÁ ÕËÁÚÁÎÎÙÊ ÐÅÒÉÏÄ ÏÔÓÕÔÓÔ×ÕÀÔ\n");
exit(12);
}
printf("\nðÒÏ×ÏÖÕ ÐÏÄÓÞÅÔ (ÏÔ %lld ÄÏ %lld)\n", (long long)from_offset, (long long)to_offset);
printf("\n====================================================================\n");
last_log_time = count_bytes(from_offset, to_offset, from_date, to_date, addr);
printf("\n====================================================================\n");
if(last_log_time - last_cache_time > TIME_INTERVAL){
printf("\núÁÐÉÓÉ ÆÁÊÌÁ ËÅÛÁ ÕÓÔÁÒÅÌÉ. ïÂÎÏ×ÌÑÀ...\n");
makecache(UPDATE);
// count_bytes(from_offset, to_offset, from_date, to_date);
}
exit(0);
}

131
recdecode.c Normal file
View File

@ -0,0 +1,131 @@
#define _FILE_OFFSET_BITS 64
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#ifdef EBUG
#define DBG(N, msg) fprintf(stderr, "%s: %s %d\n", __func__, msg, N)
#else
#define DBG(N, msg) {}
#endif
#define LOCK(name, no) do{ \
DBG(no, #name); \
pthread_mutex_lock(& name[no]); \
DBG(no, "locked"); \
}while(0)
#define UNLOCK(name, no) do{ \
DBG(no, #name); \
pthread_mutex_unlock(& name[no]); \
DBG(no, "unlocked"); \
}while(0)
#ifndef BUF_SIZ
#define BUF_SIZ 1048576L
#endif
#ifndef NBUF
#define NBUF 8
#endif
pthread_mutex_t r_mutex[NBUF], w_mutex[NBUF];
int out;
struct sbuf{
unsigned char *data;
ssize_t len;
int bufno;
}s_buf[NBUF];
char end = 0;
void *write_data(){
int i = 0;
while(s_buf[0].len == 0){
DBG(s_buf[0].len, "buflen");
#ifdef EBUG
sleep(1);
#endif
};
DBG(i, "begin");
while(1){
LOCK(w_mutex, i);
if(end && s_buf[i].len == 0){
UNLOCK(r_mutex, i);
UNLOCK(w_mutex, i);
return NULL;
}
write(out, s_buf[i].data, s_buf[i].len);
s_buf[i].len = 0;
UNLOCK(r_mutex, i);
UNLOCK(w_mutex, i);
i++;
if(i == NBUF) i = 0;
}
return NULL;
}
void *xor_data(void *buffer){
struct sbuf *buf = (struct sbuf*) buffer;
int n = buf->bufno;
unsigned char *ptr = buf->data;
ssize_t i, len = buf->len;
LOCK(r_mutex, n);
for(i = 0; i < len; i++) *ptr++ ^= 0xaa;
UNLOCK(w_mutex, n);
return NULL;
}
int main(int argc, char **argv){
int i, j, l, in;
char not_first = 0;
ssize_t rb;
pthread_t w_thread, d_thread[NBUF];
if(argc < 3){
printf("\nUsage:\t%s <file.rec> <file.001> ... <file.avi>\n\t\t\"ÄÅËÏÄÉÒÕÅÔ\" rec-ÆÁÊÌ × ×ÙÈÏÄÎÏÊ avi-ÆÁÊÌ\n", argv[0]);
exit(-1);
}
for(i = 0; i < NBUF; i++){
s_buf[i].data = malloc(BUF_SIZ * sizeof(char));
s_buf[i].len = 0;
s_buf[i].bufno = i;
}
out = open(argv[argc - 1], O_RDWR|O_CREAT|O_TRUNC, 0666);
l = argc - 1;
i = 0;
pthread_create(&w_thread, NULL, write_data, NULL);
for(j = 1; j < l; j++){
in = open(argv[j], O_RDONLY);
do{
if(not_first)
if(pthread_join(d_thread[i], NULL)){
perror("\n\nCan't join thread");
}
LOCK(r_mutex, i);
LOCK(w_mutex, i);
rb = read(in, s_buf[i].data, BUF_SIZ);
s_buf[i].len = rb;
UNLOCK(r_mutex, i);
if(pthread_create(&d_thread[i], NULL, xor_data, &s_buf[i])){
perror("\n\nCan't create thread");
exit(-1);
}
DBG(i, "thread created");
i++; if(i == NBUF){ i = 0; not_first = 1;}
}while(rb);
DBG(j, "EOF");
close(in);
}
end = 1;
DBG(1, "wait 4 xor");
for(i = 0; i < NBUF; i++) pthread_join(d_thread[i], NULL);
DBG(1, "xor ends");
pthread_join(w_thread, NULL);
close(out);
for(i = 0; i < NBUF; i++) free(s_buf[i].data);
return 0;
}

73
swapfiles.c Normal file
View File

@ -0,0 +1,73 @@
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
//#define __USE_MISC
#include <sys/shm.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char** argv){
int w1, w2, r1, r2, bytes1, bytes2, bytes;
int memsize, id1, id2, Mb = 1024*1024;
key_t key1, key2;
unsigned char *data1, *data2;
if(argc < 3){
printf("\nUsage: %s <file1> <file2> [mem]\n", argv[0]);
printf("\tswaps data in files <file1> & <file2>\n");
printf("mem - shared memory segments size in Mb (by default: 100)\n\n");
exit(1);
}
w1=open(argv[1], O_WRONLY);
r1=open(argv[1], O_RDONLY);
if(w1 < 1 || r1 < 1){
perror("Cant open file1");
exit(1);
}
w2=open(argv[2], O_WRONLY);
r2=open(argv[2], O_RDONLY);
if(w2 < 1 || r2 < 1){
perror("Cant open file2");
exit(1);
}
if(argc == 4) memsize = atoi(argv[3]);
else memsize = 100;
memsize *= Mb;
key1 = ftok(argv[1], 22);
key2 = ftok(argv[2], 22);
id1 = shmget(key1, memsize, IPC_CREAT|0644|SHM_DEST);
id2 = shmget(key2, memsize, IPC_CREAT|0644|SHM_DEST);
if(id1 < 0 || id2 < 0){
perror("Can't get shared memory");
goto ex;
}
data1 = (unsigned char*)shmat(id1, NULL, 0);
data2 = (unsigned char*)shmat(id2, NULL, 0);
if(data1 == ((void*)-1) || data2 == ((void*)-1)){
perror("Can't attach shared memory");
exit(1);
}
do{
bytes1 = read(r1, data1, memsize);
bytes2 = read(r2, data2, memsize);
if(bytes1 < 0 || bytes2 < 0){
perror("Can't read data from files");
goto ex;
}
bytes = (bytes1 > bytes2) ? bytes2:bytes1;
bytes1 = write(w1, data2, bytes);
bytes2 = write(w2, data1, bytes);
if(bytes1 != bytes || bytes2 != bytes){
perror("Can't write data to files");
goto ex;
}
}while(bytes == memsize);
ex:
shmdt(data2);
shmctl(id2, IPC_RMID, NULL);
shmdt(data1);
shmctl(id1, IPC_RMID, NULL);
return 0;
}