util.c
Go to the documentation of this file.
00001 /*
00002  * util.c
00003  *
00004  * some general memory functions
00005  *
00006  * a Net::DNS like library for C
00007  *
00008  * (c) NLnet Labs, 2004-2006
00009  *
00010  * See the file LICENSE for the license
00011  */
00012 
00013 #include <ldns/config.h>
00014 
00015 #include <ldns/rdata.h>
00016 #include <ldns/rr.h>
00017 #include <ldns/util.h>
00018 #include <strings.h>
00019 #include <stdlib.h>
00020 #include <stdio.h>
00021 #include <sys/time.h>
00022 #include <time.h>
00023 
00024 #ifdef HAVE_SSL
00025 #include <openssl/rand.h>
00026 #endif
00027 
00028 /* put this here tmp. for debugging */
00029 void
00030 xprintf_rdf(ldns_rdf *rd)
00031 {
00032         /* assume printable string */
00033         fprintf(stderr, "size\t:%u\n", (unsigned int)ldns_rdf_size(rd));
00034         fprintf(stderr, "type\t:%u\n", (unsigned int)ldns_rdf_get_type(rd));
00035         fprintf(stderr, "data\t:[%.*s]\n", (int)ldns_rdf_size(rd),
00036                         (char*)ldns_rdf_data(rd));
00037 }
00038 
00039 void
00040 xprintf_rr(ldns_rr *rr)
00041 {
00042         /* assume printable string */
00043         uint16_t count, i;
00044 
00045         count = ldns_rr_rd_count(rr);
00046 
00047         for(i = 0; i < count; i++) {
00048                 fprintf(stderr, "print rd %u\n", (unsigned int) i);
00049                 xprintf_rdf(rr->_rdata_fields[i]);
00050         }
00051 }
00052 
00053 void xprintf_hex(uint8_t *data, size_t len)
00054 {
00055         size_t i;
00056         for (i = 0; i < len; i++) {
00057                 if (i > 0 && i % 20 == 0) {
00058                         printf("\t; %u - %u\n", (unsigned int) i - 19, (unsigned int) i);
00059                 }
00060                 printf("%02x ", (unsigned int) data[i]);
00061         }
00062         printf("\n");
00063 }
00064 
00065 ldns_lookup_table *
00066 ldns_lookup_by_name(ldns_lookup_table *table, const char *name)
00067 {
00068         while (table->name != NULL) {
00069                 if (strcasecmp(name, table->name) == 0)
00070                         return table;
00071                 table++;
00072         }
00073         return NULL;
00074 }
00075 
00076 ldns_lookup_table *
00077 ldns_lookup_by_id(ldns_lookup_table *table, int id)
00078 {
00079         while (table->name != NULL) {
00080                 if (table->id == id)
00081                         return table;
00082                 table++;
00083         }
00084         return NULL;
00085 }
00086 
00087 int
00088 ldns_get_bit(uint8_t bits[], size_t index)
00089 {
00090         /*
00091          * The bits are counted from left to right, so bit #0 is the
00092          * left most bit.
00093          */
00094         return (int) (bits[index / 8] & (1 << (7 - index % 8)));
00095 }
00096 
00097 int
00098 ldns_get_bit_r(uint8_t bits[], size_t index)
00099 {
00100         /*
00101          * The bits are counted from right to left, so bit #0 is the
00102          * right most bit.
00103          */
00104         return (int) bits[index / 8] & (1 << (index % 8));
00105 }
00106 
00107 void
00108 ldns_set_bit(uint8_t *byte, int bit_nr, bool value)
00109 {
00110         /*
00111          * The bits are counted from right to left, so bit #0 is the
00112          * right most bit.
00113          */
00114         if (bit_nr >= 0 && bit_nr < 8) {
00115                 if (value) {
00116                         *byte = *byte | (0x01 << bit_nr);
00117                 } else {
00118                         *byte = *byte & ~(0x01 << bit_nr);
00119                 }
00120         }
00121 }
00122 
00123 int
00124 ldns_hexdigit_to_int(char ch)
00125 {
00126         switch (ch) {
00127         case '0': return 0;
00128         case '1': return 1;
00129         case '2': return 2;
00130         case '3': return 3;
00131         case '4': return 4;
00132         case '5': return 5;
00133         case '6': return 6;
00134         case '7': return 7;
00135         case '8': return 8;
00136         case '9': return 9;
00137         case 'a': case 'A': return 10;
00138         case 'b': case 'B': return 11;
00139         case 'c': case 'C': return 12;
00140         case 'd': case 'D': return 13;
00141         case 'e': case 'E': return 14;
00142         case 'f': case 'F': return 15;
00143         default:
00144                 return -1;
00145         }
00146 }
00147 
00148 char
00149 ldns_int_to_hexdigit(int i)
00150 {
00151         switch (i) {
00152         case 0: return '0';
00153         case 1: return '1';
00154         case 2: return '2';
00155         case 3: return '3';
00156         case 4: return '4';
00157         case 5: return '5';
00158         case 6: return '6';
00159         case 7: return '7';
00160         case 8: return '8';
00161         case 9: return '9';
00162         case 10: return 'a';
00163         case 11: return 'b';
00164         case 12: return 'c';
00165         case 13: return 'd';
00166         case 14: return 'e';
00167         case 15: return 'f';
00168         default:
00169                 abort();
00170         }
00171 }
00172 
00173 int
00174 ldns_hexstring_to_data(uint8_t *data, const char *str)
00175 {
00176         size_t i;
00177 
00178         if (!str || !data) {
00179                 return -1;
00180         }
00181 
00182         if (strlen(str) % 2 != 0) {
00183                 return -2;
00184         }
00185 
00186         for (i = 0; i < strlen(str) / 2; i++) {
00187                 data[i] =
00188                         16 * (uint8_t) ldns_hexdigit_to_int(str[i*2]) +
00189                         (uint8_t) ldns_hexdigit_to_int(str[i*2 + 1]);
00190         }
00191 
00192         return (int) i;
00193 }
00194 
00195 const char *
00196 ldns_version(void)
00197 {
00198         return (char*)LDNS_VERSION;
00199 }
00200 
00201 /* Number of days per month (except for February in leap years). */
00202 static const int mdays[] = {
00203         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
00204 };
00205 
00206 #define LDNS_MOD(x,y) (((x) % (y) < 0) ? ((x) % (y) + (y)) : ((x) % (y)))
00207 #define LDNS_DIV(x,y) (((x) % (y) < 0) ? ((x) / (y) -  1 ) : ((x) / (y)))
00208 
00209 static int
00210 is_leap_year(int year)
00211 {
00212         return LDNS_MOD(year,   4) == 0 && (LDNS_MOD(year, 100) != 0 
00213             || LDNS_MOD(year, 400) == 0);
00214 }
00215 
00216 static int
00217 leap_days(int y1, int y2)
00218 {
00219         --y1;
00220         --y2;
00221         return (LDNS_DIV(y2,   4) - LDNS_DIV(y1,   4)) - 
00222                (LDNS_DIV(y2, 100) - LDNS_DIV(y1, 100)) +
00223                (LDNS_DIV(y2, 400) - LDNS_DIV(y1, 400));
00224 }
00225 
00226 /*
00227  * Code adapted from Python 2.4.1 sources (Lib/calendar.py).
00228  */
00229 time_t
00230 ldns_mktime_from_utc(const struct tm *tm)
00231 {
00232         int year = 1900 + tm->tm_year;
00233         time_t days = 365 * ((time_t) year - 1970) + leap_days(1970, year);
00234         time_t hours;
00235         time_t minutes;
00236         time_t seconds;
00237         int i;
00238 
00239         for (i = 0; i < tm->tm_mon; ++i) {
00240                 days += mdays[i];
00241         }
00242         if (tm->tm_mon > 1 && is_leap_year(year)) {
00243                 ++days;
00244         }
00245         days += tm->tm_mday - 1;
00246 
00247         hours = days * 24 + tm->tm_hour;
00248         minutes = hours * 60 + tm->tm_min;
00249         seconds = minutes * 60 + tm->tm_sec;
00250 
00251         return seconds;
00252 }
00253 
00254 time_t
00255 mktime_from_utc(const struct tm *tm)
00256 {
00257         return ldns_mktime_from_utc(tm);
00258 }
00259 
00260 #if SIZEOF_TIME_T <= 4
00261 
00262 static void
00263 ldns_year_and_yday_from_days_since_epoch(int64_t days, struct tm *result)
00264 {
00265         int year = 1970;
00266         int new_year;
00267 
00268         while (days < 0 || days >= (int64_t) (is_leap_year(year) ? 366 : 365)) {
00269                 new_year = year + (int) LDNS_DIV(days, 365);
00270                 days -= (new_year - year) * 365;
00271                 days -= leap_days(year, new_year);
00272                 year  = new_year;
00273         }
00274         result->tm_year = year;
00275         result->tm_yday = (int) days;
00276 }
00277 
00278 /* Number of days per month in a leap year. */
00279 static const int leap_year_mdays[] = {
00280         31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
00281 };
00282 
00283 static void
00284 ldns_mon_and_mday_from_year_and_yday(struct tm *result)
00285 {
00286         int idays = result->tm_yday;
00287         const int *mon_lengths = is_leap_year(result->tm_year) ? 
00288                                         leap_year_mdays : mdays;
00289 
00290         result->tm_mon = 0;
00291         while  (idays >= mon_lengths[result->tm_mon]) {
00292                 idays -= mon_lengths[result->tm_mon++];
00293         }
00294         result->tm_mday = idays + 1;
00295 }
00296 
00297 static void
00298 ldns_wday_from_year_and_yday(struct tm *result)
00299 {
00300         result->tm_wday = 4 /* 1-1-1970 was a thursday */
00301                         + LDNS_MOD((result->tm_year - 1970), 7) * LDNS_MOD(365, 7)
00302                         + leap_days(1970, result->tm_year)
00303                         + result->tm_yday;
00304         result->tm_wday = LDNS_MOD(result->tm_wday, 7);
00305         if (result->tm_wday < 0) {
00306                 result->tm_wday += 7;
00307         }
00308 }
00309 
00310 static struct tm *
00311 ldns_gmtime64_r(int64_t clock, struct tm *result)
00312 {
00313         result->tm_isdst = 0;
00314         result->tm_sec   = (int) LDNS_MOD(clock, 60);
00315         clock            =       LDNS_DIV(clock, 60);
00316         result->tm_min   = (int) LDNS_MOD(clock, 60);
00317         clock            =       LDNS_DIV(clock, 60);
00318         result->tm_hour  = (int) LDNS_MOD(clock, 24);
00319         clock            =       LDNS_DIV(clock, 24);
00320 
00321         ldns_year_and_yday_from_days_since_epoch(clock, result);
00322         ldns_mon_and_mday_from_year_and_yday(result);
00323         ldns_wday_from_year_and_yday(result);
00324         result->tm_year -= 1900;
00325 
00326         return result;
00327 }
00328 
00329 #endif /* SIZEOF_TIME_T <= 4 */
00330 
00331 static int64_t
00332 ldns_serial_arithmitics_time(int32_t time, time_t now)
00333 {
00334         int32_t offset = time - (int32_t) now;
00335         return (int64_t) now + offset;
00336 }
00337 
00338 
00339 struct tm *
00340 ldns_serial_arithmitics_gmtime_r(int32_t time, time_t now, struct tm *result)
00341 {
00342 #if SIZEOF_TIME_T <= 4
00343         int64_t secs_since_epoch = ldns_serial_arithmitics_time(time, now);
00344         return  ldns_gmtime64_r(secs_since_epoch, result);
00345 #else
00346         time_t  secs_since_epoch = ldns_serial_arithmitics_time(time, now);
00347         return  gmtime_r(&secs_since_epoch, result);
00348 #endif
00349 }
00350 
00362 int
00363 ldns_init_random(FILE *fd, unsigned int size)
00364 {
00365         /* if fp is given, seed srandom with data from file
00366            otherwise use /dev/urandom */
00367         FILE *rand_f;
00368         uint8_t *seed;
00369         size_t read = 0;
00370         unsigned int seed_i;
00371         struct timeval tv;
00372 
00373         /* we'll need at least sizeof(unsigned int) bytes for the
00374            standard prng seed */
00375         if (size < (unsigned int) sizeof(seed_i)){
00376                 size = (unsigned int) sizeof(seed_i);
00377         }
00378 
00379         seed = LDNS_XMALLOC(uint8_t, size);
00380         if(!seed) {
00381                 return 1;
00382         }
00383 
00384         if (!fd) {
00385                 if ((rand_f = fopen("/dev/urandom", "r")) == NULL) {
00386                         /* no readable /dev/urandom, try /dev/random */
00387                         if ((rand_f = fopen("/dev/random", "r")) == NULL) {
00388                                 /* no readable /dev/random either, and no entropy
00389                                    source given. we'll have to improvise */
00390                                 for (read = 0; read < size; read++) {
00391                                         gettimeofday(&tv, NULL);
00392                                         seed[read] = (uint8_t) (tv.tv_usec % 256);
00393                                 }
00394                         } else {
00395                                 read = fread(seed, 1, size, rand_f);
00396                         }
00397                 } else {
00398                         read = fread(seed, 1, size, rand_f);
00399                 }
00400         } else {
00401                 rand_f = fd;
00402                 read = fread(seed, 1, size, rand_f);
00403         }
00404 
00405         if (read < size) {
00406                 LDNS_FREE(seed);
00407                 if (!fd) fclose(rand_f);
00408                 return 1;
00409         } else {
00410 #ifdef HAVE_SSL
00411                 /* Seed the OpenSSL prng (most systems have it seeded
00412                    automatically, in that case this call just adds entropy */
00413                 RAND_seed(seed, (int) size);
00414 #else
00415                 /* Seed the standard prng, only uses the first
00416                  * unsigned sizeof(unsiged int) bytes found in the entropy pool
00417                  */
00418                 memcpy(&seed_i, seed, sizeof(seed_i));
00419                 srandom(seed_i);
00420 #endif
00421                 LDNS_FREE(seed);
00422         }
00423 
00424         if (!fd) {
00425                 if (rand_f) fclose(rand_f);
00426         }
00427 
00428         return 0;
00429 }
00430 
00435 uint16_t
00436 ldns_get_random(void)
00437 {
00438         uint16_t rid = 0;
00439 #ifdef HAVE_SSL
00440         if (RAND_bytes((unsigned char*)&rid, 2) != 1) {
00441                 rid = (uint16_t) random();
00442         }
00443 #else
00444         rid = (uint16_t) random();
00445 #endif
00446         return rid;
00447 }
00448 
00449 /*
00450  * BubbleBabble code taken from OpenSSH
00451  * Copyright (c) 2001 Carsten Raskgaard.  All rights reserved.
00452  */
00453 char *
00454 ldns_bubblebabble(uint8_t *data, size_t len)
00455 {
00456         char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
00457         char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
00458             'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
00459         size_t i, j = 0, rounds, seed = 1;
00460         char *retval;
00461 
00462         rounds = (len / 2) + 1;
00463         retval = LDNS_XMALLOC(char, rounds * 6);
00464         if(!retval) return NULL;
00465         retval[j++] = 'x';
00466         for (i = 0; i < rounds; i++) {
00467                 size_t idx0, idx1, idx2, idx3, idx4;
00468                 if ((i + 1 < rounds) || (len % 2 != 0)) {
00469                         idx0 = (((((size_t)(data[2 * i])) >> 6) & 3) +
00470                             seed) % 6;
00471                         idx1 = (((size_t)(data[2 * i])) >> 2) & 15;
00472                         idx2 = ((((size_t)(data[2 * i])) & 3) +
00473                             (seed / 6)) % 6;
00474                         retval[j++] = vowels[idx0];
00475                         retval[j++] = consonants[idx1];
00476                         retval[j++] = vowels[idx2];
00477                         if ((i + 1) < rounds) {
00478                                 idx3 = (((size_t)(data[(2 * i) + 1])) >> 4) & 15;
00479                                 idx4 = (((size_t)(data[(2 * i) + 1]))) & 15;
00480                                 retval[j++] = consonants[idx3];
00481                                 retval[j++] = '-';
00482                                 retval[j++] = consonants[idx4];
00483                                 seed = ((seed * 5) +
00484                                     ((((size_t)(data[2 * i])) * 7) +
00485                                     ((size_t)(data[(2 * i) + 1])))) % 36;
00486                         }
00487                 } else {
00488                         idx0 = seed % 6;
00489                         idx1 = 16;
00490                         idx2 = seed / 6;
00491                         retval[j++] = vowels[idx0];
00492                         retval[j++] = consonants[idx1];
00493                         retval[j++] = vowels[idx2];
00494                 }
00495         }
00496         retval[j++] = 'x';
00497         retval[j++] = '\0';
00498         return retval;
00499 }