Advertisement
utroz

Beer

Jan 15th, 2012
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 15.26 KB | None | 0 0
  1. /* https://github.com/CoolerVoid/C/blob/master/beer.h
  2. last check up
  3. 11/01/2012
  4. ------------
  5.  
  6.        _____________
  7.       (             )
  8.       (____________ )
  9.        |           |
  10.        |           |  
  11.        |           |
  12.       /             \
  13.      /               \  
  14.    /                  \
  15.   (___________________)
  16.   |                   |
  17.   |   ...:::Beer:::   |
  18.   |..::Version:0.04::.|
  19.   |                   |
  20.   |___________________|
  21.   |                   |
  22.   |                   |
  23.   |                   |
  24.   |                   |
  25.   |                   |
  26.   (___________________)
  27. 0101010101010110101010101010101101010101010  
  28.  
  29. is held by Apache license 2.0
  30. -----------------------
  31. Beer simple C header
  32.  
  33. Authors: Cooler_,m0nad,ryonagana,utroz
  34. E-mail: c00f3r[at]gmail[dot]com
  35. date: 03/08/2011
  36.  
  37. thanks:
  38.   _mlk_,m0nad, utroz
  39.   I4K,sigsegv,b-man
  40.   delfo,c0lt7r,B4r0n,joey,fokerbug,
  41.   zepplin,voidpointer,muzgo,memset,b4r0n,novato_br...
  42.  
  43. */
  44.  
  45. #include <stdio.h>
  46. // use alloca z noobs dont use free() xD
  47. #include <alloca.h>
  48. #include <stdlib.h>
  49. #include <string.h>
  50. #include <dirent.h>
  51. #include <time.h>
  52.  
  53. //macro to read stdin string
  54. #define ReadString(a) fgets(a,sizeof(a),stdin),a[strlen(a)-1] = '\0';
  55.  
  56. //return elements of array
  57. #define array_elements(array) (sizeof(array) / sizeof *(array))
  58.  
  59. //hide and unhide strings
  60. #define UNHIDE_STR(str) do { char *p = str;  while (*p) *p++ += 0x19; } while (0)
  61. #define HIDE_STR(str)   do { char *p = str;  while (*p) *p++ -= 0x19; } while (0)
  62.  
  63. // bitwise macros
  64. #define XorSwap(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
  65. #define BIT_POS(N)            ( 1U << (N) )
  66. #define SET_FLAG(N, F)        ( (N) |= (F) )
  67. #define CLR_FLAG(N, F)        ( (N) &= -(F) )
  68. #define TST_FLAG(N, F)        ( (N) & (F) )
  69. #define BIT_RANGE(N, M)       ( BIT_POS((M)+1 - (N))-1 << (N) )
  70. #define BIT_SHIFTL(B, N)      ( (unsigned)(B) << (N) )
  71. #define BIT_SHIFTR(B, N)      ( (unsigned)(B) >> (N) )
  72. #define SET_MFLAG(N, F, V)    ( CLR_FLAG(N, F), SET_FLAG(N, V) )
  73. #define CLR_MFLAG(N, F)       ( (N) &= ~(F) )
  74. #define GET_MFLAG(N, F)       ( (N) & (F) )
  75.  
  76. #define BUGVIEW 1
  77.  
  78. // DEBUG MACRO
  79. #define DEBUG(x, s...) do { \
  80.  if (!BUGVIEW) { break; } \
  81.  time_t t = time(NULL); \
  82.  char *d = ctime(&t); \
  83.  fprintf(stderr, "%.*s %s[%d] %s(): ", \
  84.  (int)strlen(d) - 1, d, __FILE__, \
  85.  __LINE__, __FUNCTION__); \
  86.  fprintf(stderr, x, ## s); \
  87. } while (0);
  88.  
  89. // convert decimal to binary  by Cooler_
  90. char * dec2bin(int n, char * string)
  91. {
  92.  int i;
  93.  static int size = 8 * sizeof(int);
  94.  
  95.   for(i = size - 1; i >= 0; i--, n >>= 1)
  96.    string[i] = (01 & n) + '0';
  97.  
  98.  string[size] = '\0';
  99.  return string;
  100. }
  101.  
  102. // Hexadecimal to Character
  103.  
  104. // with bitwise , by Cooler_
  105. char Hex2Char(char *Hex)
  106. {
  107.  char rch=0;
  108.  int i=0;
  109.  
  110.  while(i<2)
  111.  {
  112.   if ( *(Hex + i) >= '0' && *(Hex + i) <= '9' )
  113.    rch = (rch << 4) + (*(Hex + i) - '0');
  114.   else if ( *(Hex + i) >= 'A' && *(Hex + i) <= 'F' )
  115.    rch = (rch << 4) + (*(Hex + i) - 'A' + 10);
  116.   else
  117.    break;
  118.   i++;
  119.  }
  120.  return rch;
  121. }
  122.  
  123. //simple version by Cooler_
  124. static char char2Hex(unsigned char c)
  125. {
  126.  static const char *HexCharacters = "0123456789ABCDEF";
  127.    if(c > 15)
  128.    {
  129.      DEBUG("error in char2Hex() %c",HexCharacters[c]);
  130.      return -1;
  131.    }
  132.  return HexCharacters[c];
  133. }
  134.  
  135. //by Cooler_  unsigned char x[]={"google.com"}; string2hex(y,x,16)...
  136. static void string2hex(char *Output, unsigned char *Input, int Length)
  137. {
  138.  char *Out;
  139.  char First;
  140.  char Second;
  141.  
  142.  Out = Output;
  143.  while (Length > 0)
  144.  {
  145.   First = *Input / 0x10;
  146.   Second = *Input % 0x10;
  147.   *Out = char2Hex(First);
  148.    Out++;
  149.   *Out = char2Hex(Second);
  150.    Out++;
  151.    Length--;
  152.    Input++;
  153.  }
  154.  *Out = '\0';
  155.  return;
  156. }
  157.  
  158. // by cooler_
  159. unsigned long hex2int(char *a, unsigned int len)
  160. {
  161.  int i=0;
  162.  unsigned long val = 0;
  163.  
  164.  while(i<len)
  165.  {
  166.   if(a[i] <= 57)
  167.    val += (a[i]-48)*(1<<(4*(len-1-i)));
  168.   else
  169.    val += (a[i]-55)*(1<<(4*(len-1-i)));
  170.   i++;
  171.  }
  172.  return val;
  173. }
  174.  
  175.  
  176. /*
  177.  
  178. this function made by utroz
  179.  
  180.  binary_str and  binary_view
  181. How to use (Example): binary_str("String Test");
  182.  CHAR           BINARY          ASCII
  183. (char)-> S |(bin)-> 01010011 |(dec)-> 83
  184. (char)-> t |(bin)-> 01110100 |(dec)-> 116
  185. (char)-> r |(bin)-> 01110010 |(dec)-> 114
  186. (char)-> i |(bin)-> 01101001 |(dec)-> 105
  187. (char)-> n |(bin)-> 01101110 |(dec)-> 110
  188. (char)-> g |(bin)-> 01100111 |(dec)-> 103
  189. (char)->   |(bin)-> 00100000 |(dec)-> 32
  190. (char)-> T |(bin)-> 01010100 |(dec)-> 84
  191. (char)-> e |(bin)-> 01100101 |(dec)-> 101
  192. (char)-> s |(bin)-> 01110011 |(dec)-> 115
  193. (char)-> t |(bin)-> 01110100 |(dec)-> 116
  194. */
  195.  
  196. char * binary_view (char *buffer, unsigned char bits)
  197. {
  198.     register i, j;
  199.    
  200.     for (i = 0, j = 8; i < 8; bits >>= 1, i++)
  201.     buffer[--j] = (bits & 0x1) + '0';    
  202.    
  203.     return buffer;
  204. }
  205.  
  206. void binary_str (char *args)
  207. {
  208.     char buffer[9] = { 0 };
  209.    
  210.     puts(" CHAR\t\tBINARY\t\tASCII");
  211.     while (*args) {
  212.     printf("(char)-> %c |(bin)-> %s |(dec)-> %d\n",
  213.            *args, binary_view(buffer, *args), *args);
  214.     args++;
  215.     }
  216. }
  217.  
  218.  
  219. //  Math functions
  220. /*
  221. MDC Máximo Divisor Comum,dois números inteiros é o maior número inteiro que divide
  222. ambos sem deixar resto. func by Cooler_
  223. */
  224. int mdc(int a,int b)
  225. {
  226.   if(!b)
  227.    return a;
  228.   else
  229.    return mdc(b,a%b);
  230. }
  231.  
  232. /*
  233. MMC = mínimo múltiplo comum entre dois números é representado
  234. pelo menor valor comum pertencente aos múltiplos dos números.
  235. by Cooler_
  236. */
  237. int mmc(int a,int b)
  238. {
  239.  int formula;
  240.    if(!b)
  241.     return a;
  242.    else
  243.     formula = (a*b)/(mdc(a,b));
  244.  return (formula);
  245. }
  246.  
  247. // quadratic equation by Cooler_
  248. char * baskara(float a, float b, float c, float *raizes)
  249. {
  250.  float delta=((b*b)-4*(a*c));
  251.  float x1=0,x2=0;
  252.  char *reply;
  253.  
  254.  if((!a)||(delta<0))
  255.  {
  256.   DEBUG("error in equation baskara(), delta: %f ",delta);
  257.   return 0;
  258.  }
  259.  if(delta>0)
  260.   x1=((-b + ((float)bit_sqrt(delta)) )/(2*a));
  261.  x2=((-b - ((float)bit_sqrt(delta)) )/(2*a));
  262.  snprintf(reply,sizeof(reply)," X1 : %5.2f \n X2 : %5.2f\n",x1,x2);
  263.  return reply;
  264. }
  265.  
  266. // simple factorial by Cooler_
  267. int factorial( int n )
  268. {
  269.  if(n<=1)
  270.   return 1;
  271.  else
  272.   return n*factorial(n-1);
  273. }
  274.  
  275. // test if var is prime by Cooler_
  276. int isprime(int n)
  277. {
  278.  int d=2;
  279.  
  280.  if(n<=0)
  281.  {
  282.   DEBUG("error isprime(), n = %d ",n);
  283.   return -1;
  284.  }
  285.  
  286.  while(d<n)
  287.  {
  288.   if(!(n%d))
  289.    return 0;
  290.   d+=2;
  291.  }
  292.  return 1;
  293. }  
  294.  
  295. //square root by Cooler_
  296. int bit_sqrt(int num)
  297. {
  298. //so 32 is sizeof(int)<<3
  299.  int num0=num,result=0,tbit=1<<((sizeof(int)<<3)-2);
  300.  
  301.  if(num<=0)
  302.  {
  303.   DEBUG("error bit_sqrt(), num = %d ",num);
  304.   return -1;
  305.  }
  306.        
  307.  while(tbit>num0)
  308.   tbit>>=2;    
  309.  while(tbit^0)
  310.  {
  311.   if(num0>=result+tbit)
  312.   {
  313.    num0-=result+tbit;
  314.    result=(result>>1)+tbit;
  315.   }else
  316.    result>>=1;
  317.   tbit>>=2;
  318.  }
  319.  return result;
  320. }
  321.  
  322. // test if is palindrome by Cooler_
  323. int palindrome(const char *s)
  324. {
  325.   int x,y;
  326.  
  327.   y = strlen(s);
  328.   for(x=0; x<y/2; x++)
  329.   {
  330.    if( s[x] != s[y-x-1] )
  331.     return 0;
  332.   }
  333.   return 1;
  334. }
  335.  
  336. // return time by Cooler_
  337. // example OutPut Wed Aug  3 18:26:24 2011
  338. char *TimeNow()
  339. {
  340.  struct tm *local;
  341.  time_t t;
  342.  t = time(NULL);
  343.  local = localtime(&t);
  344.  local = gmtime(&t);
  345.  return asctime(local);
  346. }
  347.  
  348. // Files jobs  ##############################################################
  349. //by Cooler_
  350. int CopyFile(char *fromfile, char *tofile)
  351. {
  352.  FILE *ifp, *ofp;
  353.  int c;
  354.  
  355.  if((ifp = fopen(fromfile, "r")) == NULL)
  356.   return -1;
  357.  if((ofp = fopen(tofile, "w")) == NULL)
  358.  {
  359.   fclose(ifp);
  360.   DEBUG("Error CopyFile()");
  361.   return -1;
  362.  }
  363.  
  364.  while((c = getc(ifp)) != EOF)
  365.   putc(c, ofp);
  366.  
  367.  fclose(ifp);
  368.  fclose(ofp);
  369.  return 0;
  370. }
  371.  
  372. //by Cooler_
  373. int WriteFile(char *file,char *str)
  374. {
  375.  FILE *arq;
  376.  
  377.  arq=fopen(file,"a");
  378.   if(!arq)
  379.   {
  380.    DEBUG("error in WriteFile() %s",file);
  381.    return 0;
  382.   }
  383.  fprintf(arq,"%s\n",str);
  384.  fclose(arq);
  385.  return 1;
  386. }
  387.  
  388. // by Cooler_,return lines from file, example:  const char *buff=readLine("log.txt"),printf("%s",buff);
  389. const char *readLine(char * NameFile)
  390. {
  391.  FILE * file;
  392.  file = fopen(NameFile, "r");
  393.  if(!file)
  394.  {
  395.   DEBUG("error in file");    
  396.   return;
  397.  }
  398.  char *lineBuffer=calloc(1,1), line[128];
  399.  
  400.  if(!lineBuffer)
  401.  {
  402.   DEBUG("error in readLine() at %s",NameFile);
  403.   return;
  404.  }
  405.  
  406.  while(fgets(line,sizeof line,file))  
  407.  {
  408.   lineBuffer=realloc(lineBuffer,strlen(lineBuffer)+strlen(line)+1);
  409.   if(!lineBuffer)
  410.   {
  411.    DEBUG("error in readLine() at %s",NameFile);
  412.    return;
  413.   }
  414.   strcat(lineBuffer,line);
  415.  }
  416.  
  417.  return lineBuffer;
  418. }
  419.  
  420. // ListDir(directory_name_2_list,Max_chars) by Cooler_
  421. char *ListDir(char *file2list,int MAX)
  422. {
  423.  DIR *d;
  424.  struct dirent *dir;
  425.  char *ret=alloca(sizeof(char)*MAX);
  426.  
  427.  d = opendir(file2list);
  428.  
  429.  if(!d)
  430.  {
  431.   DEBUG("error in directory");
  432.   return NULL;
  433.  }  
  434.  
  435.  while((dir = readdir(d)) != NULL)
  436.  {    
  437.   strncat(ret,dir->d_name,strlen(dir->d_name));
  438.   strncat(ret,"\n",1);
  439.  }  
  440.  
  441.  closedir(d);
  442.  return ret;
  443. }  
  444.  
  445. // return size of bytes on file , same to unix cmd "du -b file" by Cooler_
  446. long FileSize(const char *file)
  447. {
  448.   long ret;
  449.   FILE *fh = fopen(file, "r");
  450.   if(!fh)
  451.   {
  452.    DEBUG("error in file");
  453.    return 0;
  454.   }
  455.   fseek(fh, 0, SEEK_END);
  456.   ret = ftell(fh);
  457.   fclose(fh);
  458.   return ret;
  459. }
  460.  
  461.  
  462. /* #################################################################################
  463.  to use with Sort functions
  464.  example:
  465.   char *list[] = { "madruga", "chaves", "kiko", "chiquinha", "inhonho" };
  466.   qsort((void *)list, array_elements(list), sizeof(list[0]), sort_char);
  467. */
  468.  
  469. int sort_char( const void *a, const void *b)
  470. {
  471.  return( strcmp(a,b) );
  472. }
  473.  
  474. int sort_int(const void *a, const void *b)
  475. {
  476.  long *a1, *b1;
  477.  a1 = (long *)a; b1 = (long *)b;
  478.  return (*a1 > *b1);
  479. }
  480.  
  481. //example mergesort(a, 0, sizeof(a)/sizeof(i) - 1); by Cooler_
  482. void mergesort(int *array, size_t first, size_t last)
  483. {
  484.  int middle;
  485.        
  486.  if(first>=last)
  487.   return;
  488.        
  489.  middle = (first + last) / 2;
  490.  mergesort(array, first, middle);
  491.  mergesort(array, middle + 1, last);
  492.  
  493.  int *temp;
  494.  size_t i = first,j = middle + 1,tp = 0;
  495.  temp = (int *) alloca(sizeof(int) * (last - first + 1));
  496.            
  497.  while(i <= middle && j <= last)
  498.  {
  499.   if(array[i] <= array[j])
  500.   {
  501.    temp[tp] = array[i];
  502.    ++i;
  503.   }
  504.   else
  505.   {
  506.    temp[tp] = array[j];
  507.    ++j;
  508.   }
  509.   ++tp;
  510.  }
  511.    
  512.  while(j<=last)
  513.  {
  514.   temp[tp] = array[j];
  515.   ++tp;
  516.   j++;
  517.  }     
  518.  while(i<=middle)
  519.  {
  520.   temp[tp] = array[i];
  521.   ++tp;
  522.   i++;
  523.  }
  524.    
  525.  i=first;
  526.  while(i<=last)
  527.  {
  528.   array[i] = temp[i - first];
  529.   i++;
  530.  } 
  531.  
  532.  free(temp);
  533. }
  534.  
  535. //by Cooler_
  536. void bubbleSort(void *p, int width, int N, int(*fptr)(const void *, const void *))
  537. {
  538.  int i, j, k;
  539.  
  540.  unsigned char buf[256];
  541.  unsigned char *bp = p;
  542.  
  543.   for (i = N-1; i >= 0; i--)
  544.   {
  545.    for (j = 1; j <= i; j++)
  546.    {
  547.     k = fptr((void *)(bp + width*(j-1)), (void *)(bp + j*width));
  548.     if(k > 0)
  549.     {
  550.      memcpy(buf, bp + width*(j-1), width);
  551.      memcpy(bp + width*(j-1), bp + j*width , width);
  552.      memcpy(bp + j*width, buf, width);
  553.     }
  554.    }
  555.   }
  556. }
  557.  
  558.  
  559. // ########################### other functions
  560. //by Cooler_
  561. char *RandomIp(void)
  562. {    
  563.  char *ipRand=NULL;
  564.  int r1,r2,r3,r4;
  565.  
  566.  r1 = 1+(int) (255.0*rand()/(RAND_MAX+1.0));          
  567.  r2 = 1+(int) (255.0*rand()/(RAND_MAX+1.0));          
  568.  r3 = 1+(int) (255.0*rand()/(RAND_MAX+1.0));          
  569.  r4 = 1+(int) (255.0*rand()/(RAND_MAX+1.0));          
  570.  
  571.  ipRand=alloca(12*sizeof(char *));
  572.  sprintf(ipRand,"%d.%d.%d.%d",r1,r2,r3,r4);
  573.  
  574.  return ipRand;
  575. }
  576.  
  577.  
  578. //test if e-mails is valid,
  579. int email_isvalid(const char *address)
  580. {
  581.   int count = 0;
  582.   const char *c, *domain;
  583.   static char *rfc822_specials = "()<>@,;:\\\"[]";
  584.  
  585.   /* first we validate the name portion (name@domain) */
  586.   for (c = address;  *c;  c++)
  587.   {
  588.     if (*c == '\"' && (c == address || *(c - 1) == '.' || *(c - 1) == '\"'))
  589.     {
  590.       while (*++c)
  591.       {
  592.         if (*c == '\"')
  593.          break;
  594.         if (*c == '\\' && (*++c == ' '))
  595.          continue;
  596.         if (*c <= ' ' || *c >= 127)
  597.          return 0;
  598.       }
  599.       if(!*c++)
  600.        return 0;
  601.       if(*c == '@')
  602.        break;
  603.       if(*c != '.')
  604.        return 0;
  605.       continue;
  606.     }
  607.     if(*c == '@')
  608.      break;
  609.     if(*c <= ' ' || *c >= 127)
  610.      return 0;
  611.     if(strchr(rfc822_specials, *c))
  612.      return 0;
  613.   }
  614.   if(c == address || *(c - 1) == '.')
  615.    return 0;
  616.   /* next we validate the domain portion (name@domain) */
  617.   if(!*(domain = ++c))
  618.    return 0;
  619.   do {
  620.     if (*c == '.')
  621.     {
  622.       if (c == domain || *(c - 1) == '.') return 0;
  623.       count++;
  624.     }
  625.     if (*c <= ' ' || *c >= 127) return 0;
  626.     if (strchr(rfc822_specials, *c)) return 0;
  627.   } while (*++c);
  628.   return (count >= 1);
  629. }
  630.  
  631. //use input to escape SQL Injection
  632. char *scapeSQL(const char *input, char quote, int wildcards) {
  633.   char       *out, *ptr;
  634.   const char *c;
  635.    
  636.   /* If every character in the input needs to be escaped, the resulting string
  637.    * would at most double in size.  Also, include room for the surrounding
  638.    * quotes.
  639.    */
  640.   if (quote != '\'' && quote != '\"') return 0;
  641.   if (!(out = ptr = (char *)sbrk(strlen(input) * 2 + 2 + 1))) return 0;
  642.   *ptr++ = quote;
  643.   for (c = input;  *c;  c++) {
  644.     switch (*c) {
  645.       case '\'': case '\"':
  646.         if (quote == *c) *ptr++ = *c;
  647.         *ptr++ = *c;
  648.         break;
  649.       case '%': case '_': case '[': case ']':
  650.         if (wildcards) *ptr++ = '\\';
  651.         *ptr++ = *c;
  652.         break;
  653.       case '\\': *ptr++ = '\\'; *ptr++ = '\\'; break;
  654.       case '\b': *ptr++ = '\\'; *ptr++ = 'b';  break;
  655.       case '\n': *ptr++ = '\\'; *ptr++ = 'n';  break;
  656.       case '\r': *ptr++ = '\\'; *ptr++ = 'r';  break;
  657.       case '\t': *ptr++ = '\\'; *ptr++ = 't';  break;
  658.       default:
  659.         *ptr++ = *c;
  660.         break;
  661.     }
  662.   }
  663.   *ptr++ = quote;
  664.   *ptr = 0;
  665.   return out;
  666. }
  667.  
  668. // func by  m0nad
  669. void urlobfuscator (char * url, char * obf)
  670. {
  671.   int i;
  672.   for (i = 0; i < (int)strlen (url); i++)
  673.    snprintf (obf+strlen(obf), sizeof obf, "%02X", url [i]);
  674. //  obf [strlen (obf)] = 0;
  675.    obf[i*2] = 0;
  676. }
  677.  
  678.  
  679. //func by ryonagana
  680. void changeCharacter(char *dest, const char* str, const char search, const char replace)
  681. {
  682.   while(*dest = *str)
  683.   {
  684.    if(*dest == search)
  685.     *dest =  replace;
  686.    *dest++;
  687.    *str++;
  688.   }
  689. }
  690.  
  691. // return reverse string by Cooler_
  692. char *strrev(char *str)
  693. {
  694.  char *p1, *p2;
  695.  
  696.  if(! str || ! *str)
  697.   return str;
  698.  for(p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
  699.  {
  700.   *p1 ^= *p2;
  701.   *p2 ^= *p1;
  702.   *p1 ^= *p2;
  703.  }
  704.  return str;
  705. }
  706.  
  707.  
  708. // simple split return array of strings between string separator by Cooler_
  709. char **split(char *string, char separator, int arraySize)
  710. {
  711.  int inicio=0,count=2,i=0,x=0;
  712.  char **newarray;
  713.  
  714.  while(string[i] != '\0')
  715.  {
  716. // numero de elementos que tera nosso array
  717.   if(string[i]==separator)
  718.    count++;
  719.   i++;              
  720.  }
  721.  
  722.  arraySize=count-1;
  723.  newarray=calloc(count,sizeof(char*));
  724.  i=0;
  725.  
  726.  while(*string!='\0')
  727.  {
  728.   if(*string==separator)
  729.   {
  730.    newarray[i]=calloc(x-inicio+2,sizeof(char));
  731.    strncpy(newarray[i],string-x+inicio,x-inicio);
  732.    newarray[i][x-inicio+1]='\0';
  733.    inicio=x;
  734.    inicio++;
  735.    i++;
  736.   }
  737.   string++;
  738.   x++;
  739.  }
  740.        
  741.  newarray[i]=calloc(x-inicio+1,sizeof(char));
  742.  strncpy(newarray[i],string-x+inicio,x-inicio);
  743.  newarray[++i]=NULL;
  744.  
  745.  return newarray;
  746. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement