Example #1
0
int main(int ac, char *av[]) {
  int r;
  unsigned int IV[4];
  unsigned int m0[32];
  unsigned int m1[32];
  int c;
  int count;
  FILE *fin;
  FILE *fout;
  callback_t *cb = &progress_printer;
  unsigned int seed = time(NULL) ^ (getpid() << 16);

  /* command line options */
  int iv_only = 0;
  char *collisionfile = NULL;
  char *goodfile = NULL;
  char *evilfile = NULL;
  char *infile = NULL;

  while ((c = getopt_long(ac, av, shortopts, longopts, NULL)) != -1) {
    switch (c) {
    case 'h':
      usage(stdout);
      exit(0);
      break;
    case 'V':
      version(stdout);
      exit(0);
      break;
    case 'L':
      license(stdout);
      exit(0);
      break;
    case 'i':
      iv_only = 1;
      break;
    case 'c':
      collisionfile = optarg;
      break;
    case 'g':
      goodfile = optarg;
      break;
    case 'e':
      evilfile = optarg;
      break;
    case 's':
      seed = strtoul(optarg, NULL, 0);
      break;
    case '?':
      fprintf(stderr, "Try --help for more information.\n");
      exit(1);
      break;
    }
  }
  count = ac-optind;
  if (count < 1) {
    fprintf(stderr, "No filename given. Try --help for more information.\n");
    exit(1);
  } else if (count > 1) {
    fprintf(stderr, "Too many filenames given. Try --help for more information.\n");
    exit(1);
  }
  infile = av[optind];

  if (!goodfile && !evilfile) {
    goodfile = append_string(infile, ".good");
    evilfile = append_string(infile, ".evil");
  }

  if (!collisionfile) {
    
    fin = fopen(infile, "rb");
    if (!fin) {
      fprintf(stderr, "%s: %s: %s\n", NAME, infile, strerror(errno));
      exit(1);
    }
    
    r = find_iv(fin, IV);
    fclose(fin);
    if (r == 1) {
      fprintf(stderr, "%s: %s: no crib found.\n", NAME, infile);
      exit(1);
    }
    
    fprintf(stdout, "Initial vector: 0x%08x 0x%08x 0x%08x 0x%08x\n", IV[0], IV[1], IV[2], IV[3]);
    
    if (iv_only) {
      return 0;
    }
    
    fprintf(stdout, "Searching for MD5 collision (this can take several hours)...\n");
    fprintf(stdout, "Random seed: %u\n", seed);
    srandom(seed);
    md5coll_with_iv(IV, m0, m1, cb);
    fprintf(stdout, "\n");
    fprintf(stdout, "Collision blocks:\n");
    write_collision_file(stdout, m0, m1);

  } else {
    
    fin = fopen(collisionfile, "r");
    if (!fin) {
      fprintf(stderr, "%s: %s: %s\n", NAME, collisionfile, strerror(errno));
      exit(1);
    }
    r = read_collision_file(fin, m0, m1);
    fclose(fin);
    if (r != 64) {
      fprintf(stderr, "%s: %s: bad file format, %d of 64 values read\n", NAME, collisionfile, r);
      exit(1);
    }
  }

  if (goodfile) {
    fin = fopen(infile, "rb");
    if (!fin) {
      fprintf(stderr, "%s: %s: %s\n", NAME, infile, strerror(errno));
      exit(1);
    }
    fout = fopen(goodfile, "wb");
    if (!fout) {
      fprintf(stderr, "%s: %s: %s\n", NAME, goodfile, strerror(errno));
    } else {
      fprintf(stdout, "Writing 'good' file %s.\n", goodfile);
      r = evilize(fin, fout, m1, m1);
      if (r) {
	fprintf(stderr, "%s: %s: not a valid template file, crib not found\n", NAME, infile);
	exit(1);
      }
      fclose(fout);
    }
    fclose(fin);
  }
  
  if (evilfile) {
    fin = fopen(infile, "rb");
    if (!fin) {
      fprintf(stderr, "%s: %s: %s\n", NAME, infile, strerror(errno));
      exit(1);
    }
    fout = fopen(evilfile, "wb");
    if (!fout) {
      fprintf(stderr, "%s: %s: %s\n", NAME, evilfile, strerror(errno));
    } else {
      fprintf(stdout, "Writing 'evil' file %s.\n", evilfile);
      r = evilize(fin, fout, m0, m1);
      if (r) {
	fprintf(stderr, "%s: %s: not a valid template file, crib not found\n", NAME, infile);
	exit(1);
      }
      fclose(fout);
    }
    fclose(fin);
  }
  return 0;
}
Example #2
0
void fuzzy_time_to_words(int hours, int minutes, char* words, size_t length) {
  int fuzzy_hours = hours;
  int fuzzy_minutes = ((minutes + 2) / 5) * 5;

  // Handle hour & minute roll-over.
  if (fuzzy_minutes > 55) {
    fuzzy_minutes = 0;
    fuzzy_hours += 1;
    if (fuzzy_hours > 23) {
      fuzzy_hours = 0;
    }
  }

  if (fuzzy_minutes > 30) {
    fuzzy_hours = (fuzzy_hours + 1) % 24;
  }

  size_t remaining = length;
  memset(words, 0, length);

 
  if (fuzzy_hours == 0 && fuzzy_minutes == 0) {
    remaining -= append_string(words, remaining, STR_MIDNIGHT);
  } else if (fuzzy_hours == 12 && fuzzy_minutes == 0) {
    remaining -= append_string(words, remaining, STR_NOON);
  } else if (fuzzy_hours % 12 == 0) {
    remaining -= append_number(words, 12);
  } else {
    remaining -= append_number(words, fuzzy_hours % 12);
  }

  if (fuzzy_minutes != 0 && (fuzzy_minutes >= 10 || fuzzy_minutes == 5 || fuzzy_hours == 0 || fuzzy_hours == 12)) {
    if (fuzzy_minutes == 15) {
       remaining -= append_string(words, remaining, " ");      
       remaining -= append_string(words, remaining, STR_AFTER);
       remaining -= append_string(words, remaining, " ");
       remaining -= append_string(words, remaining, STR_QUARTER);      
    } else if (fuzzy_minutes == 45) {
       remaining -= append_string(words, remaining, " ");      
       remaining -= append_string(words, remaining, STR_TO);
       remaining -= append_string(words, remaining, " ");
       remaining -= append_string(words, remaining, STR_QUARTER);
    } else if (fuzzy_minutes == 30) {
      remaining -= append_string(words, remaining, " ");
      remaining -= append_string(words, remaining, STR_PAST);
      remaining -= append_string(words, remaining, " ");
      remaining -= append_string(words, remaining, STR_HALF);
    } else if (fuzzy_minutes < 30) {
      remaining -= append_string(words, remaining, " ");
      remaining -= append_string(words, remaining, STR_AFTER);
      remaining -= append_string(words, remaining, " ");
      remaining -= append_number(words, fuzzy_minutes);
    } else {
      remaining -= append_string(words, remaining, " ");
      remaining -= append_string(words, remaining, STR_TO);
      remaining -= append_string(words, remaining, " ");
      remaining -= append_number(words, 60 - fuzzy_minutes);
    }
  }


  if (fuzzy_minutes == 0 && !(fuzzy_hours == 0 || fuzzy_hours == 12)) {
    remaining -= append_string(words, remaining, " ");
    remaining -= append_string(words, remaining, STR_OH_CLOCK);
  }
}
void fuzzy_time_to_words(int hours, int minutes, char* words1, char* words2, char* words3,  size_t length) {
  
  
  size_t remaining1 = length;
  size_t remaining2 = length;
  size_t remaining3 = length;
  memset(words1, 0, length);
	memset(words2,0,length);
	memset(words3,0,length);
  
  if (minutes == 0) {
	  
    if (hours == 0) {
      remaining1 -= append_string(words1, remaining1, "mitter-");
		remaining2 -=append_string(words2,remaining2,"nacht");
    } else {
		remaining1-=append_string(words1,remaining1,"genau");
      if (hours % 12 == 1) {
        remaining2 -= append_string(words2, remaining2, "ein");
      } else {
        remaining2 -= append_string(words2, remaining2, STUNDEN[hours % 12]);
      }
      remaining3 -= append_string(words3, remaining3, "uhr");
      
    }
    return;
  };
  
  if (minutes <= 2) {
    remaining1 -= append_string(words1, remaining1, "kurz");
	remaining2 -= append_string(words2,remaining2,"nach");
  } else if (minutes <= 7) {
    remaining1 -= append_string(words1, remaining1, "fünf");
	remaining2 -= append_string(words2,remaining2,"nach");
  } else if (minutes <= 12) {
    remaining1 -= append_string(words1, remaining1, "zehn");
	remaining2 -= append_string(words2,remaining2,"nach");
  } else if (minutes <= 17) {
    remaining1-= append_string(words1, remaining1, "viertel");
	remaining2 -= append_string(words2,remaining2,"nach");
  } else if (minutes <= 22) {
    remaining1 -= append_string(words1, remaining1, "zwanzig");
	remaining2 -= append_string(words2,remaining2,"nach");
  } else if (minutes <= 27) {
    remaining1 -= append_string(words1, remaining1, "fünf"); 
	remaining2 -= append_string(words2,remaining2,"vor ");
	remaining2 -= append_string(words2,remaining2,"hb");
  } else if (minutes <= 28) {
    remaining1 -= append_string(words1, remaining1, "kurz");
	remaining2 -= append_string(words2,remaining2,"vor ");
	remaining2 -= append_string(words2,remaining2,"hb");
  } else if (minutes <= 30) {
    remaining2 -= append_string(words2, remaining2, "halb");
  } else if (minutes <= 32) {
    remaining1 -= append_string(words1, remaining1, "kurz");
	remaining2 -= append_string(words2, remaining2, "nach ");
	remaining2 -= append_string(words2, remaining2, "hb");
  } else if (minutes <= 37) {
    remaining1 -= append_string(words1, remaining1, "fünf");
	remaining2 -= append_string(words2, remaining2, "nach ");
	remaining2-= append_string(words2, remaining2, "hb");
  } else if (minutes <= 42) {
    remaining1 -= append_string(words1, remaining1, "zwanzig");
	remaining2 -= append_string(words2, remaining2, "vor");
  } else if (minutes <= 47) {
    remaining1 -= append_string(words1, remaining1, "viertel");
	remaining2 -= append_string(words2, remaining2, "vor");
  } else if (minutes <= 52) {
    remaining1 -= append_string(words1, remaining1, "zehn");
	remaining2-= append_string(words2, remaining2, "vor");
  } else if (minutes <= 57) {
    remaining1 -= append_string(words1, remaining1, "fünf");
	remaining2 -= append_string(words2, remaining2, "vor");
  } else if (minutes <= 58) {
    remaining1 -= append_string(words1, remaining1, "kurz");
	remaining2 -= append_string(words2, remaining2, "vor");
  }
  
  if (minutes < 23) {
    remaining3 -= append_string(words3, remaining3, STUNDEN[hours % 12]);
  } else {
    remaining3 -= append_string(words3, remaining3, STUNDEN[(hours+1) % 12]);
  }
}
Example #4
0
void Inspect::operator()(Parent_Selector* p)
{
    append_string("&");
}
Example #5
0
template_t *
template_load(const char *filename)
{
  struct template_chunk *chunk;
  FILE *f;
  char *buf = NULL, *q;
  size_t buf_len, line;
  template_t *tpl = NULL;
  int c;
  char entity[128], *e = NULL;

  RUNTIME_ASSERT(filename != NULL);
  f = safer_fopen(filename, SAFER_FOPEN_RD);
  if (!f) {
    WARN("could not open \"%s\": %s", filename, compat_strerror(errno));
    goto failure;
  }

  tpl = calloc(1, sizeof *tpl);
  if (!tpl) {
    CRIT("Out of memory");
    goto failure;
  }
  tpl->chunks = NULL;
  
  buf_len = 4096;
  buf = calloc(1, buf_len);
  if (!buf) {
    CRIT("Out of memory");
    goto failure;
  }
  
  for (line = 1; /* NOTHING */; line++) {
    char *p;
    
    p = fgets(buf, buf_len, f);
    if (!p) {
      if (!ferror(f))
        break;

      CRIT("fgets() failed: %s", compat_strerror(errno));
      goto failure;
    }

    q = strchr(buf, '\n');
    if (!q) {
      CRIT("Line too long or unterminated: \"%s\"", buf);
      goto failure;
    }
    while (isspace((unsigned char) *q)) {
      *q = '\0';
      if (q == buf)
        break;
      q--;
    }
    
    if (q == buf && *q == '\0')
      break;

    if (line == 1 && 0 == strncmp(buf, "HTTP/", sizeof "HTTP/" - 1)) {
      uint64_t code;
      char *endptr;
      int error;
      struct http_response hres;
      size_t size;
      snode_t *sn;

      p = strchr(buf, ' ');
      if (!p) {
        WARN("Invalid HTTP response: \"%s\"", buf);
        goto failure;
      }
      
      p = skip_spaces(p);
      code = parse_uint64(p, &endptr, 10, &error);
      if (code < 100 || code > 999) {
        WARN("Invalid HTTP result code: \"%s\"", buf);
        goto failure;
      }
      p = skip_spaces(endptr);

      hres.code = code;
      size = sizeof hres.msg;
      append_string(hres.msg, &size, p);
      RUNTIME_ASSERT(hres.msg == (char *) &hres);
      chunk = template_raw_chunk_new(chunk_http_response,
                (char *) &hres, sizeof hres);

      if (NULL == (sn = snode_new(chunk))) {
        CRIT("snode_new() failed");
        goto failure;
      }
      tpl->chunks = snode_prepend(tpl->chunks, sn);
    } else {
      size_t len;
      snode_t *sn;

      if (!isalpha((unsigned char) buf[0]) || NULL == strchr(buf, ':')) {
        WARN("Invalid HTTP header: \"%s\"", buf);
        goto failure;
      }

      for (p = buf; (c = (unsigned char) *p) != ':'; ++p)
        if (!isalpha(c) && c != '-') {
          WARN("Invalid character HTTP in header name: \"%s\"", buf);
          goto failure;
        }
      
      len = strlen(buf) + 1;
      chunk = template_raw_chunk_new(chunk_http_header, buf, len);
      if (NULL == (sn = snode_new(chunk))) {
        CRIT("snode_new() failed");
        goto failure;
      }
      tpl->chunks = snode_prepend(tpl->chunks, sn);
    }
  }

  if (feof(f)) {
    tpl->chunks = snode_reverse(tpl->chunks);
    return tpl;
  }
  
  q = buf;
  e = NULL;
  
  for (;;) {
    c = fgetc(f);
    if (c == EOF) {
      if (!ferror(f))
        break;
      
      CRIT("fgetc() failed: %s", compat_strerror(errno));
      goto failure;
    }
    
    if ((size_t) (q - buf) >= buf_len) {
      char *n;
      
      buf_len += 4096;
      n = realloc(buf, buf_len);
      if (!n) {
        CRIT("Out of memory");
        goto failure;
      }
      q = &n[q - buf];
      buf = n;
    }
    *q++ = c;

    if (c == ';' && e != NULL) {
      RUNTIME_ASSERT(e >= entity && e < &entity[sizeof entity]);
      *e = '\0';
      
      chunk = template_chunk_new(entity);
      if (chunk) {
        struct template_chunk *data;
        size_t data_len;
        snode_t *sn;
     
        data_len = (q - buf) - strlen(entity) - 2;
        RUNTIME_ASSERT(data_len <= INT_MAX);
        if (data_len > 0) {
          data = template_raw_chunk_new(chunk_data, buf, data_len);
          if (NULL == (sn = snode_new(data))) {
            CRIT("snode_new() failed");
            goto failure;
          }
          tpl->chunks = snode_prepend(tpl->chunks, sn);
      
          buf_len = 4096;
          buf = calloc(1, buf_len);
          if (!buf) {
            CRIT("Out of memory");
            goto failure;
          }
        }
        q = buf;
    
        if (NULL == (sn = snode_new(chunk))) {
          CRIT("snode_new() failed");
          goto failure;
        }
        tpl->chunks = snode_prepend(tpl->chunks, sn);
      }

      e = NULL;
    }
    
    if (e) {
      bool b = isalnum(c) || c == '.' || c == '_';
      
      if (b && e < &entity[sizeof entity - 1]) {
        *e++ = c;
      } else {
        e = NULL;
      }
    }
    
    if (c == '&') {
      e = entity;
    }
  }
  fclose(f);
  f = NULL;

  if (q != buf) {
    snode_t *sn;

    chunk = template_raw_chunk_new(chunk_data, buf, q - buf);
    if (NULL == (sn = snode_new(chunk))) {
      CRIT("snode_new() failed");
      goto failure;
    }
    tpl->chunks = snode_prepend(tpl->chunks, sn);
  }
  DO_FREE(buf);
 
  tpl->chunks = snode_reverse(tpl->chunks);
  
#if 0
  {
    size_t n = 0;
    
    snode_t *sn = tpl->chunks;
    while (sn) {
      struct gwc_data_chunk *data = sn->ptr;
      DBUG("data->type=%d; data->buf=%p; data->size=%d",
          (int) data->type, data->buf, (int) data->size);
      sn = sn->next;
      n += data->size;
    }
    
    DBUG("n=%d", (int) n);
  }
#endif
  
  return tpl;

failure:

  CRIT("Loading data template from \"%s\" failed.", filename);

  if (f) {
    fclose(f);
    f = NULL;
  }
  DO_FREE(buf);
  if (tpl) {
    while (tpl->chunks != NULL) {
      snode_t *sn = tpl->chunks->next;
    
      DO_FREE(tpl->chunks);
      tpl->chunks = sn;
    }
    DO_FREE(tpl);
  }
  return NULL;
}
Example #6
0
/*
 Standart behaviour:
   if malformed or missing subtitle id - calculate, continue.
   if malformer or missing timing - skip event competely, text without timing is useless.
   if missing text - skip event, empty event also useless.
 */
bool
parse_srt_file(FILE *infile, srt_file * const file)
  {
    char line[MAXLINE] = "";
    char text_buf[MAXLINE] = "";
    int s_len = 0;
    bool skip_event = false;
    uint16_t parsed = 0; /* num events parsed */
    uint8_t t_detect = 3; /* number of first timing strings to analyze */
    srt_event *event = (srt_event *) 0;
    srt_event **elist_tail = &file->events;

    if (!infile) return false;

    curr_line = unknown;

    while(!feof(infile))
      {
        fgets(line, MAXLINE, infile);
        line_num++;

        /* unicode handle */
        if (line_num == 1)
          charset_type = unicode_check(line, 0);

        prev_line = curr_line;
        curr_line = unknown;

        trim_newline(line);
        log_msg(raw, "%s", line);
        trim_spaces(line, LINE_START | LINE_END);
        s_len = strlen(line);

        if      (s_len == 0)          curr_line = blank;
        else if (strstr(line, "-->")) curr_line = timing;
        else if (prev_line == blank ||
                 prev_line == unknown) curr_line = id;  /* at least, expected */
        else /* prev_line == timing*/ curr_line = text; /* also expected */


        if (feof(infile)) curr_line = blank;

        if (feof(infile) && s_len != 0)
          {
            log_msg(warn, MSG_F_UNEXPEOF, line_num);
            if (prev_line == text)
              append_string(text_buf, line, "\n", MAXLINE, 0);
            else
              strncpy(text_buf, line, MAXLINE);
          }

        log_msg(debug, "Line type: %i", curr_line);

        if (curr_line == id || (curr_line == timing && prev_line == blank))
          {
            CALLOC(event, 1, sizeof(srt_event));
            memset(text_buf, 0x0, MAXLINE);

            if (curr_line != id)
              {
                log_msg(warn, _("Missing subtitle id at line '%u'."), line_num);
                event->id = ++parsed;
              }
          }

        if (prev_line == timing && curr_line == blank)
          {
            log_msg(warn, _("Empty subtitle text at line %u. Event will be skipped."), line_num);
            skip_event = true;
          }

        if (prev_line == id && curr_line == blank)
          {
            log_msg(warn, _("Lonely subtitle id without timing or text. :-("));
            skip_event = true;
          }

        switch (curr_line)
          {
            case id     :
              /* See header for comments */
              event->id = ++parsed;
              /* if ((event->id = atoi(line)) != 0) parsed++; */
              break;
            case timing :
              if (t_detect-- && !(file->flags & SRT_E_STRICT))
                analyze_srt_timing(line, &file->flags);
              skip_event = !parse_srt_timing(event, line, &file->flags);
              if (event->start > event->end)
                {
                  log_msg(warn, _("Negative duration of event at line '%u'. Event will be skipped."), line_num);
                  skip_event = true;
                }
              /*printf("%f --> %f\n", event->start, event->end);*/
              break;
            case text :
              /* TODO: wrapping handling here   */
              if (prev_line == text)
                append_string(text_buf, line, "\n", MAXLINE, 0);
              else
                strncpy(text_buf, line, MAXLINE);
              break;
            case blank :
              if (!skip_event && prev_line != blank)
                {
                  if ((event->text = strndup(text_buf, MAXLINE)) == NULL)
                    log_msg(error, MSG_M_OOM);
                  srt_event_append(&file->events, &elist_tail, event, opts.i_sort);
                  memset(text_buf, 0, MAXLINE);
                }
            case unknown :
            default      :
              continue;
              break;
          }

        if (skip_event)
          {
            /* clean parsed stuff & skip calloc() next time */
            memset(event, 0, sizeof(srt_event));
            memset(text_buf, 0, MAXLINE);
            parsed--;
          }
     }

    return true; /* if we reach this line, no error happens */
  }
Example #7
0
void Inspect::operator()(Binary_Expression* expr)
{
    expr->left()->perform(this);
    switch (expr->type()) {
    case Sass_OP::AND:
        append_string(" and ");
        break;
    case Sass_OP::OR:
        append_string(" or ");
        break;
    case Sass_OP::EQ:
        append_string(" == ");
        break;
    case Sass_OP::NEQ:
        append_string(" != ");
        break;
    case Sass_OP::GT:
        append_string(" > ");
        break;
    case Sass_OP::GTE:
        append_string(" >= ");
        break;
    case Sass_OP::LT:
        append_string(" < ");
        break;
    case Sass_OP::LTE:
        append_string(" <= ");
        break;
    case Sass_OP::ADD:
        append_string(" + ");
        break;
    case Sass_OP::SUB:
        append_string(" - ");
        break;
    case Sass_OP::MUL:
        append_string(" * ");
        break;
    case Sass_OP::DIV:
        append_string(in_media_block ? " / " : "/");
        break;
    case Sass_OP::MOD:
        append_string(" % ");
        break;
    default:
        break; // shouldn't get here
    }
    expr->right()->perform(this);
}
Example #8
0
int save_iptables(const char *table, char **conf, bool all_targets)
{
	int pipefd_out[2];
	int pipefd_err[2];
	pid_t child_pid;
	int error = 0;

	assert(conf);

	child_pid = fork_with_pipes(pipefd_out, pipefd_err);
	if (child_pid < 0) {
		return error;
	}

	if (child_pid == 0) {
		/* child */
		close(pipefd_out[0]);
		close(pipefd_err[0]);

		if (dup2(pipefd_out[1], STDOUT_FILENO) == -1 ||
		    dup2(pipefd_err[1], STDERR_FILENO) == -1) {
			fprintf(stderr, "%s\n", strerror(errno));
			exit(1);
		}
		close(pipefd_out[1]);
		close(pipefd_err[1]);

		execl(IPTABLES_SAVE, "iptables-save", "-t", table, NULL);

		/* an error occured */
		fprintf(stderr, "%s\n", strerror(errno));
		exit(1);
	}
	else {
		/* parent */
		int status;
		pid_t ret;
		char *buffer = NULL;
		size_t buffer_size = 0, read_size = 0;
		ssize_t line_size;
		FILE *input = fdopen(pipefd_out[0], "r");
		FILE *err = fdopen(pipefd_err[0], "r");
		bool filtering = false;
		bool pre_found = false, out_found = false;
		fd_set fds, curfds;
		int max_fd, fd_count;

		if (!input || !err) {
			LOG_ERROR(nfqueue, "iptables-save: %s", errno_error(errno));
			fclose(input);
			fclose(err);
			return errno;
		}

		close(pipefd_out[1]);
		close(pipefd_err[1]);

		pipefd_out[1] = fileno(input);
		pipefd_err[1] = fileno(err);

		FD_ZERO(&fds);
		FD_SET(pipefd_out[1], &fds);
		FD_SET(pipefd_err[1], &fds);
		max_fd = pipefd_out[1] > pipefd_err[1] ? pipefd_out[1] : pipefd_err[1];
		fd_count = 2;

		while (fd_count > 0) {
			int rc;
			curfds = fds;

			rc = select(max_fd+1, &curfds, NULL, NULL, NULL);
			if (rc < 0) {
				LOG_ERROR(nfqueue, "iptables-save: %s", errno_error(errno));
				free(buffer);
				fclose(input);
				fclose(err);
				return errno;
			}

			if (FD_ISSET(pipefd_err[1], &curfds)) {
				line_size = getline(&buffer, &buffer_size, err);
				if (line_size > 1) {
					buffer[line_size-1] = '\0';
					LOG_INFO(nfqueue, "iptables-save: %s", buffer);
				}
				else {
					FD_CLR(pipefd_err[1], &fds);
					--fd_count;
				}
			}

			if (FD_ISSET(pipefd_out[1], &curfds)) {
				line_size = getline(&buffer, &buffer_size, input);
				if (line_size > 0) {
					if (filtering) {
						if (strcmp(buffer, "COMMIT\n") != 0) {
							/*
							 * If all_targets is true, we only want to include the rule in the
							 * targets HAKA_TARGET_PRE and HAKA_TARGET_OUT. So we need to filter
							 * each line to only include those but being careful not to add the
							 * line from another target that jump to one of the haka target
							 * (ie. -A PREROUTING -j haka-pre)
							 */
							char *pattern, *current = buffer;
							bool skip = true;

							while (true) {
								if ((pattern = strstr(current, "-j " HAKA_TARGET))) {
									pattern += 3; /* Skip '-j ' */

									if (check_haka_target(pattern, HAKA_TARGET_PRE) ||
										check_haka_target(pattern, HAKA_TARGET_OUT)) {
										skip = true;
										break;
									}

									/*
									 * Advance one more to avoid the next test case to match
									 * (ie. pattern = strstr(current, HAKA_TARGET))
									 */
									current = pattern+1;
								}
								else if ((pattern = strstr(current, HAKA_TARGET))) {
									if (check_haka_target(pattern, HAKA_TARGET_PRE)) {
										skip = false;
										pre_found = true;
										break;
									}
									else if (check_haka_target(pattern, HAKA_TARGET_OUT)) {
										skip = false;
										out_found = true;
										break;
									}

									current = pattern+1;
								}
								else {
									skip = true;
									break;
								}
							}

							if (!all_targets && skip) {
								continue;
							}
						}
						else {
							/*
							 * The target HAKA_TARGET_PRE or HAKA_TARGET_OUT do not
							 * exist.
							 * In this case, iptables-restore will be unable to remove them.
							 * As a workaround, we just install new empty targets to cleanup
							 * Haka rules. This case only appears when the user sets the option
							 * enable_iptables=no which is not the default.
							 */

							if (!pre_found) {
								if (!append_string(conf, &read_size, iptables_empty_haka_pre_target, -1)) {
									free(buffer);
									fclose(input);
									fclose(err);
									return ENOMEM;
								}
							}

							if (!out_found) {
								if (!append_string(conf, &read_size, iptables_empty_haka_out_target, -1)) {
									free(buffer);
									fclose(input);
									fclose(err);
									return ENOMEM;
								}
							}

							/* COMMIT and the text after it should not be skipped  */
							filtering = false;
						}
					}

					if (buffer[0] == '*') {
						filtering = true;
					}

					if (!append_string(conf, &read_size, buffer, line_size)) {
						free(buffer);
						fclose(input);
						fclose(err);
						return ENOMEM;
					}
				}
				else {
					FD_CLR(pipefd_out[1], &fds);
					--fd_count;
				}
			}
		}

		free(buffer);
		fclose(input);
		fclose(err);

		if (error) {
			free(*conf);
			*conf = NULL;
			return error;
		}

		/* Wait for the child to finish */
		do {
			ret = waitpid(child_pid, &status, 0);
			if (ret == -1) {
				free(*conf);
				*conf = NULL;
				return errno;
			}
		}
		while (!WIFEXITED(status) && !WIFSIGNALED(status));

		if (WEXITSTATUS(status) != 0) {
			free(*conf);
			*conf = NULL;
			return 1;
		}

		return 0;
	}
}
Example #9
0
char *build_uac_cancel(str *headers,str *body,struct cell *cancelledT,
										unsigned int branch, unsigned int *len)
{
	char *cancel_buf, *p, *via;
	unsigned int via_len;
	char branch_buf[MAX_BRANCH_PARAM_LEN];
	str branch_str;
	struct hostport hp;
	str content_length;

	LM_DBG("sing FROM=<%.*s>, TO=<%.*s>, CSEQ_N=<%.*s>\n",
		cancelledT->from.len, cancelledT->from.s, cancelledT->to.len,
		cancelledT->to.s, cancelledT->cseq_n.len, cancelledT->cseq_n.s);

	branch_str.s=branch_buf;
	if (!t_calc_branch(cancelledT,  branch, branch_str.s, &branch_str.len )){
		LM_ERR("failed to create branch !\n");
		goto error;
	}
	set_hostport(&hp,0);
	via=via_builder(&via_len, cancelledT->uac[branch].request.dst.send_sock,
			&branch_str, 0, cancelledT->uac[branch].request.dst.proto, &hp );
	if (!via){
		LM_ERR("no via header got from builder\n");
		goto error;
	}

	/* method, separators, version  */
	*len=CANCEL_LEN + 2 /* spaces */ +SIP_VERSION_LEN + CRLF_LEN;
	*len+=cancelledT->uac[branch].uri.len;
	/*via*/
	*len+= via_len;
	/*From*/
	*len+=cancelledT->from.len;
	/*To*/
	*len+=cancelledT->to.len;
	/*CallId*/
	*len+=cancelledT->callid.len;
	/*CSeq*/
	*len+=cancelledT->cseq_n.len+1+CANCEL_LEN+CRLF_LEN;
	/* User Agent */
	if (server_signature) {
		*len += USER_AGENT_LEN + CRLF_LEN;
	}
	/* Content Length  */
	if (print_content_length(&content_length, body) < 0) {
		LM_ERR("failed to print content-length\n");
		return 0;
	}
	/* Content-Length */
	*len += (body ? (CONTENT_LENGTH_LEN + content_length.len + CRLF_LEN) : 0);
	/*Additional headers*/
	*len += (headers ? headers->len : 0);
	/*EoM*/
	*len+= CRLF_LEN;
	/* Message body */
	*len += (body ? body->len : 0);

	cancel_buf=shm_malloc( *len+1 );
	if (!cancel_buf)
	{
		LM_ERR("no more share memory\n");
		goto error01;
	}
	p = cancel_buf;

	append_string( p, CANCEL, CANCEL_LEN );
	*(p++) = ' ';
	append_string( p, cancelledT->uac[branch].uri.s,
		cancelledT->uac[branch].uri.len);
	append_string( p, " " SIP_VERSION CRLF, 1+SIP_VERSION_LEN+CRLF_LEN );

	/* insert our via */
	append_string(p,via,via_len);

	/*other headers*/
	append_string( p, cancelledT->from.s, cancelledT->from.len );
	append_string( p, cancelledT->callid.s, cancelledT->callid.len );
	append_string( p, cancelledT->to.s, cancelledT->to.len );

	append_string( p, cancelledT->cseq_n.s, cancelledT->cseq_n.len );
	*(p++) = ' ';
	append_string( p, CANCEL, CANCEL_LEN );
	append_string( p, CRLF, CRLF_LEN );

	/* User Agent header */
	if (server_signature) {
		append_string(p,USER_AGENT CRLF, USER_AGENT_LEN+CRLF_LEN );
	}
	/* Content Length*/
	if (body) {
		append_string(p, CONTENT_LENGTH, CONTENT_LENGTH_LEN);
		append_string(p, content_length.s, content_length.len);
		append_string(p, CRLF, CRLF_LEN);
	}
	if(headers && headers->len){
		append_string(p,headers->s,headers->len);
	}
	/*EoM*/
	append_string(p,CRLF,CRLF_LEN);
	if(body && body->len){
		append_string(p,body->s,body->len);
	}
	*p=0;
	pkg_free(via);
	return cancel_buf;
error01:
	pkg_free(via);
error:
	return NULL;
}
Example #10
0
  void Output::operator()(Ruleset* r)
  {
    Selector* s     = r->selector();
    Block*    b     = r->block();
    bool      decls = false;

    // Filter out rulesets that aren't printable (process its children though)
    if (!Util::isPrintable(r, output_style())) {
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        if (dynamic_cast<Has_Block*>(stm)) {
          stm->perform(this);
        }
      }
      return;
    }

    if (b->has_non_hoistable()) {
      decls = true;
      if (output_style() == SASS_STYLE_NESTED) indentation += r->tabs();
      if (ctx && ctx->c_options->source_comments) {
        std::stringstream ss;
        append_indentation();
        ss << "/* line " << r->pstate().line + 1 << ", " << r->pstate().path << " */";
        append_string(ss.str());
        append_optional_linefeed();
      }
      s->perform(this);
      append_scope_opener(b);
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        bool bPrintExpression = true;
        // Check print conditions
        if (typeid(*stm) == typeid(Declaration)) {
          Declaration* dec = static_cast<Declaration*>(stm);
          if (dec->value()->concrete_type() == Expression::STRING) {
            String_Constant* valConst = static_cast<String_Constant*>(dec->value());
            std::string val(valConst->value());
            if (auto qstr = dynamic_cast<String_Quoted*>(valConst)) {
              if (!qstr->quote_mark() && val.empty()) {
                bPrintExpression = false;
              }
            }
          }
          else if (dec->value()->concrete_type() == Expression::LIST) {
            List* list = static_cast<List*>(dec->value());
            bool all_invisible = true;
            for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) {
              Expression* item = (*list)[list_i];
              if (!item->is_invisible()) all_invisible = false;
            }
            if (all_invisible) bPrintExpression = false;
          }
        }
        // Print if OK
        if (!stm->is_hoistable() && bPrintExpression) {
          stm->perform(this);
        }
      }
      if (output_style() == SASS_STYLE_NESTED) indentation -= r->tabs();
      append_scope_closer(b);
    }

    if (b->has_hoistable()) {
      if (decls) ++indentation;
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        if (stm->is_hoistable()) {
          stm->perform(this);
        }
      }
      if (decls) --indentation;
    }
  }
Example #11
0
int
_hx509_Name_to_string(const Name *n, char **str)
{
    size_t total_len = 0;
    int i, j, ret;

    *str = strdup("");
    if (*str == NULL)
	return ENOMEM;

    for (i = n->u.rdnSequence.len - 1 ; i >= 0 ; i--) {
	int len;

	for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
	    DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
	    char *oidname;
	    char *ss;
	
	    oidname = oidtostring(&n->u.rdnSequence.val[i].val[j].type);

	    switch(ds->element) {
	    case choice_DirectoryString_ia5String:
		ss = ds->u.ia5String;
		break;
	    case choice_DirectoryString_printableString:
		ss = ds->u.printableString;
		break;
	    case choice_DirectoryString_utf8String:
		ss = ds->u.utf8String;
		break;
	    case choice_DirectoryString_bmpString: {
	        const uint16_t *bmp = ds->u.bmpString.data;
		size_t bmplen = ds->u.bmpString.length;
		size_t k;

		ret = wind_ucs2utf8_length(bmp, bmplen, &k);
		if (ret)
		    return ret;
		
		ss = malloc(k + 1);
		if (ss == NULL)
		    _hx509_abort("allocation failure"); /* XXX */
		ret = wind_ucs2utf8(bmp, bmplen, ss, NULL);
		if (ret) {
		    free(ss);
		    return ret;
		}
		ss[k] = '\0';
		break;
	    }
	    case choice_DirectoryString_teletexString:
		ss = malloc(ds->u.teletexString.length + 1);
		if (ss == NULL)
		    _hx509_abort("allocation failure"); /* XXX */
		memcpy(ss, ds->u.teletexString.data, ds->u.teletexString.length);
		ss[ds->u.teletexString.length] = '\0';
		break;
	    case choice_DirectoryString_universalString: {
	        const uint32_t *uni = ds->u.universalString.data;
		size_t unilen = ds->u.universalString.length;
		size_t k;

		ret = wind_ucs4utf8_length(uni, unilen, &k);
		if (ret)
		    return ret;

		ss = malloc(k + 1);
		if (ss == NULL)
		    _hx509_abort("allocation failure"); /* XXX */
		ret = wind_ucs4utf8(uni, unilen, ss, NULL);
		if (ret) {
		    free(ss);
		    return ret;
		}
		ss[k] = '\0';
		break;
	    }
	    default:
		_hx509_abort("unknown directory type: %d", ds->element);
		exit(1);
	    }
	    append_string(str, &total_len, oidname, strlen(oidname), 0);
	    free(oidname);
	    append_string(str, &total_len, "=", 1, 0);
	    len = strlen(ss);
	    append_string(str, &total_len, ss, len, 1);
	    if (ds->element == choice_DirectoryString_universalString ||
		ds->element == choice_DirectoryString_bmpString ||
		ds->element == choice_DirectoryString_teletexString)
	    {
		free(ss);
	    }
	    if (j + 1 < n->u.rdnSequence.val[i].len)
		append_string(str, &total_len, "+", 1, 0);
	}

	if (i > 0)
	    append_string(str, &total_len, ",", 1, 0);
    }
    return 0;
}
Example #12
0
static bool
append_string(char*& path, size_t& bytesLeft, const char* toAppend)
{
	return append_string(path, bytesLeft, toAppend, strlen(toAppend));
}
Example #13
0
static char *print_script(widechar *buffer, int length) {
  static char script[BUFSIZE];
  int i = 0;
  int j = 0;
  int action = 0;
  while (i < length) {
    switch (buffer[i]) {
      case pass_first:
      case pass_last:
      case pass_not:
      case pass_startReplace:
      case pass_endReplace:
      case pass_search:
      case pass_copy:
      case pass_omit:
        append_char(script, &j, buffer[i++]);
        break;
      case pass_lookback:
        append_char(script, &j, buffer[i++]);
	if (buffer[i] > 1)
	  append_string(script, &j, print_number(buffer[i++]));
        break;
      case pass_string:
        append_char(script, &j, buffer[i]);
        append_string(script, &j, print_chars(&buffer[i+2], buffer[i+1]));
        append_char(script, &j, buffer[i]);
        i += (2 + buffer[i+1]);
        break;
      case pass_dots:
        append_char(script, &j, buffer[i++]);
        append_string(script, &j, print_dots(&buffer[i+1], buffer[i]));
        i += (1 + buffer[i]);
        break;
      case pass_eq:
      case pass_lt:
      case pass_gt:
      case pass_lteq:
      case pass_gteq:
        append_char(script, &j, '#');
        append_string(script, &j, print_number(buffer[i+1]));
        append_char(script, &j, buffer[i]);
        append_string(script, &j, print_number(buffer[i+2]));
        i += 3;
        break;
      case pass_hyphen:
      case pass_plus:
        append_char(script, &j, '#');
        append_string(script, &j, print_number(buffer[i+1]));
        append_char(script, &j, buffer[i]);
        i += 2;
        break;
      case pass_attributes:
        append_char(script, &j, buffer[i]);
        append_string(script, &j, print_attributes(buffer[i+1] << 16 | buffer[i+2]));
        i += 3;
        if (buffer[i] == 1 && buffer[i+1] == 1) {}
        else if (buffer[i] == 1 && buffer[i+1] == 0xffff)
          append_char(script, &j, pass_until);
        else if (buffer[i] == buffer[i+1])
          append_string(script, &j, print_number(buffer[i]));
        else {
          append_string(script, &j, print_number(buffer[i]));
          append_char(script, &j, '-');
          append_string(script, &j, print_number(buffer[i+1])); }
        i += 2;
        break;
      case pass_endTest:
        append_char(script, &j, '\t');
        action = 1;
        i++;
        break;
      case pass_swap:
      case pass_groupstart:
      case pass_groupend:
      case pass_groupreplace:
        /* TBD */
      default:
        i++;
        break; }}
  script[j] = 0;
  return script;
}
Example #14
0
/**
 * mnt_table_append_trailing_comment:
 * @tb: pointer to tab
 * @comm: comment of NULL
 *
 * Appends to the trailing table comment.
 *
 * Returns: 0 on success or negative number in case of error.
 */
int mnt_table_append_trailing_comment(struct libmnt_table *tb, const char *comm)
{
	if (!tb)
		return -EINVAL;
	return append_string(&tb->comm_tail, comm);
}
Example #15
0
 void Emitter::append_comma_separator()
 {
   // scheduled_space = 0;
   append_string(",");
   append_optional_space();
 }
Example #16
0
/* Build a local request based on a previous request; the only
   customers of this function are local ACK and local CANCEL
 */
char *build_local(struct cell *Trans,unsigned int branch,
	str *method, str *extra, struct sip_msg* rpl, unsigned int *len)
{
	char                *cancel_buf, *p, *via;
	unsigned int         via_len;
	struct hdr_field    *buf_hdrs;
	struct hdr_field    *hdr;
	struct sip_msg      *req;
	char branch_buf[MAX_BRANCH_PARAM_LEN];
	str branch_str;
	struct hostport hp;
	str from;
	str to;
	str cseq_n;

	req = Trans->uas.request;
	cseq_n = Trans->cseq_n;
	buf_hdrs = 0;

	if (rpl && rpl!=FAKED_REPLY) {
		/* take from and to hdrs from reply */
		to.s = rpl->to->name.s;
		to.len = rpl->to->len;
		from.s = rpl->from->name.s;
		from.len = rpl->from->len;
	} else {
		to = Trans->to;
		from = Trans->from;
		if (req && req->msg_flags&(FL_USE_UAC_FROM|FL_USE_UAC_TO)) {
			if ( extract_hdrs( Trans->uac[branch].request.buffer.s,
				Trans->uac[branch].request.buffer.len,
				(req->msg_flags&FL_USE_UAC_FROM)?&from:0 ,
				(req->msg_flags&FL_USE_UAC_TO)?&to:0 , 0 )!=0 ) {
				LM_ERR("build_local: failed to extract UAC hdrs\n");
				goto error;
			}
		}
	}

	LM_DBG("using FROM=<%.*s>, TO=<%.*s>, CSEQ_N=<%.*s>\n",
		from.len,from.s , to.len,to.s , cseq_n.len,cseq_n.s);

	/* method, separators, version  */
	*len=SIP_VERSION_LEN + method->len + 2 /* spaces */ + CRLF_LEN;
	*len+=Trans->uac[branch].uri.len;

	/*via*/
	branch_str.s=branch_buf;
	if (!t_calc_branch(Trans,  branch, branch_str.s, &branch_str.len ))
		goto error;
	set_hostport(&hp, (is_local(Trans))?0:req);
	via=via_builder(&via_len, Trans->uac[branch].request.dst.send_sock,
		&branch_str, 0, Trans->uac[branch].request.dst.proto, &hp );
	if (!via){
		LM_ERR("no via header got from builder\n");
		goto error;
	}
	*len+= via_len;
	/*headers*/
	*len+=from.len+Trans->callid.len+to.len+cseq_n.len+1+method->len+CRLF_LEN;

	/* copy'n'paste Route headers that were sent out */
	if (!is_local(Trans) &&
	( (req && req->route) || /* at least one route was received*/
	(Trans->uac[branch].path_vec.len!=0)) ) /* path was forced */
	{
		buf_hdrs = extract_parsed_hdrs(Trans->uac[branch].request.buffer.s,
			Trans->uac[branch].request.buffer.len );
		if (buf_hdrs==NULL) {
			LM_ERR("failed to reparse the request buffer\n");
			goto error01;
		}
		for ( hdr=buf_hdrs ; hdr ; hdr=hdr->next )
			if (hdr->type==HDR_ROUTE_T)
				*len+=hdr->len;
	}

	/* User Agent */
	if (server_signature) {
		*len += user_agent_header.len + CRLF_LEN;
	}
	/* Content Length, MaxFwd, EoM */
	*len+=LOCAL_MAXFWD_HEADER_LEN + CONTENT_LENGTH_LEN+1 + (extra?extra->len:0)
		+ (Trans->extra_hdrs.s?Trans->extra_hdrs.len:0) + CRLF_LEN + CRLF_LEN;

	cancel_buf=shm_malloc( *len+1 );
	if (!cancel_buf)
	{
		LM_ERR("no more share memory\n");
		goto error02;
	}
	p = cancel_buf;

	append_string( p, method->s, method->len );
	*(p++) = ' ';
	append_string( p, Trans->uac[branch].uri.s, Trans->uac[branch].uri.len);
	append_string( p, " " SIP_VERSION CRLF, 1+SIP_VERSION_LEN+CRLF_LEN );

	/* insert our via */
	append_string(p,via,via_len);

	/*other headers*/
	append_string( p, from.s, from.len );
	append_string( p, Trans->callid.s, Trans->callid.len );
	append_string( p, to.s, to.len );

	append_string( p, cseq_n.s, cseq_n.len );
	*(p++) = ' ';
	append_string( p, method->s, method->len );
	append_string( p, CRLF LOCAL_MAXFWD_HEADER,
		CRLF_LEN+LOCAL_MAXFWD_HEADER_LEN );

	/* add Route hdrs (if any) */
	for ( hdr=buf_hdrs ; hdr ; hdr=hdr->next )
		if(hdr->type==HDR_ROUTE_T) {
			append_string(p, hdr->name.s, hdr->len );
		}

	if (extra)
		append_string(p, extra->s, extra->len );

	if (Trans->extra_hdrs.s)
		append_string(p, Trans->extra_hdrs.s, Trans->extra_hdrs.len );

	/* User Agent header, Content Length, EoM */
	if (server_signature) {
		append_string(p, user_agent_header.s, user_agent_header.len);
		append_string(p, CRLF CONTENT_LENGTH "0" CRLF CRLF ,
			CRLF_LEN+CONTENT_LENGTH_LEN+1 + CRLF_LEN + CRLF_LEN);
	} else {
		append_string(p, CONTENT_LENGTH "0" CRLF CRLF ,
			CONTENT_LENGTH_LEN+1 + CRLF_LEN + CRLF_LEN);
	}
	*p=0;

	pkg_free(via);
	free_hdr_field_lst(buf_hdrs);
	return cancel_buf;
error02:
	free_hdr_field_lst(buf_hdrs);
error01:
	pkg_free(via);
error:
	return NULL;
}
Example #17
0
 void Emitter::append_colon_separator()
 {
   scheduled_space = 0;
   append_string(":");
   append_optional_space();
 }
Example #18
0
/*
 * The function creates an ACK for a local INVITE. If 200 OK, route set 
 * will be created and parsed
 */
char *build_dlg_ack(struct sip_msg* rpl, struct cell *Trans,
							unsigned int branch, str* to, unsigned int *len)
{
	char *req_buf, *p, *via;
	unsigned int via_len;
	char branch_buf[MAX_BRANCH_PARAM_LEN];
	int branch_len;
	str branch_str;
	struct hostport hp;
	struct rte* list;
	str contact, ruri, *cont;
	struct socket_info* send_sock;
	str next_hop;


	if (rpl->first_line.u.reply.statuscode < 300 ) {
		/* build e2e ack for 2xx reply -> we need the route set */
		if (get_contact_uri(rpl, &contact) < 0) {
			return 0;
		}

		if (process_routeset(rpl, &contact, &list, &ruri, &next_hop) < 0) {
			return 0;
		}

		if ((contact.s != ruri.s) || (contact.len != ruri.len)) {
			/* contact != ruri means that the next
			 * hop is a strict router, cont will be non-zero
			 * and print_routeset will append it at the end
			 * of the route set
			 */
			cont = &contact;
		} else {
			/* Next hop is a loose router, nothing to append */
			cont = 0;
		}
	} else {
		/* build hop-by-hop ack for negative reply ->
		 * ruri is the same as in INVITE; no route set */
		ruri = Trans->uac[branch].uri;
		cont = 0;
		list = 0;
	}

	/* method, separators, version: "ACK sip:[email protected] SIP/2.0" */
	*len = SIP_VERSION_LEN + ACK_LEN + 2 /* spaces */ + CRLF_LEN;
	*len += ruri.len;

	/* use same socket as for INVITE -bogdan */
	send_sock = Trans->uac[branch].request.dst.send_sock;

	if (!t_calc_branch(Trans,  branch, branch_buf, &branch_len)) goto error;
	branch_str.s = branch_buf;
	branch_str.len = branch_len;
	set_hostport(&hp, 0);

	/* build via */
	via = via_builder(&via_len, send_sock, &branch_str, 0, 
			send_sock->proto, &hp);
	if (!via) {
		LM_ERR("no via header got from builder\n");
		goto error;
	}
	*len+= via_len;

	/*headers*/
	*len += Trans->from.len + Trans->callid.len + to->len +
		Trans->cseq_n.len + 1 + ACK_LEN + CRLF_LEN;

	/* copy'n'paste Route headers */
	*len += calc_routeset_len(list, cont);

	/* User Agent */
	if (server_signature)
		*len += user_agent_header.len + CRLF_LEN;

	/* Content Length, EoM */
	*len += CONTENT_LENGTH_LEN + 1 + CRLF_LEN + CRLF_LEN;

	req_buf = shm_malloc(*len + 1);
	if (!req_buf) {
		LM_ERR("no more share memory\n");
		goto error01;
	}
	p = req_buf;

	append_string( p, ACK " ", ACK_LEN+1 );
	append_string(p, ruri.s, ruri.len );
	append_string( p, " " SIP_VERSION CRLF, 1 + SIP_VERSION_LEN + CRLF_LEN);

	/* insert our via */
	append_string(p, via, via_len);

	/*other headers*/
	append_string(p, Trans->from.s, Trans->from.len);
	append_string(p, Trans->callid.s, Trans->callid.len);
	append_string(p, to->s, to->len);

	append_string(p, Trans->cseq_n.s, Trans->cseq_n.len);
	*(p++) = ' ';
	append_string(p, ACK CRLF, ACK_LEN+CRLF_LEN);

	/* Routeset */
	p = print_rs(p, list, cont);

	/* User Agent header, Content Length, EoM */
	if (server_signature) {
		append_string(p, user_agent_header.s, user_agent_header.len);
		append_string(p, CRLF CONTENT_LENGTH "0" CRLF CRLF,
			CRLF_LEN+CONTENT_LENGTH_LEN + 1 + CRLF_LEN + CRLF_LEN);
	} else {
		append_string(p, CONTENT_LENGTH "0" CRLF CRLF,
			CONTENT_LENGTH_LEN + 1 + CRLF_LEN + CRLF_LEN);
	}
	*p = 0;

	pkg_free(via);
	free_rte_list(list);
	return req_buf;
error01:
	pkg_free(via);
error:
	free_rte_list(list);
	return 0;
}
Example #19
0
void fuzzy_time_to_words(int hours, int minutes, char* words, size_t length) {
  
  size_t remaining = length;
  memset(words, 0, length);
  
  if (minutes == 0) {
    if (hours == 0) {
      remaining -= append_string(words, remaining, "mitter- nacht");
    } else {
      if (hours % 12 == 1) {
        remaining -= append_string(words, remaining, "ein");
      } else {
        remaining -= append_string(words, remaining, STUNDEN[hours % 12]);
      }
      remaining -= append_string(words, remaining, "   uhr");
      if (hours  < 5 || hours > 21) {
        remaining -= append_string(words, remaining, " nachts");
      } else if ( hours < 12) {
        remaining -= append_string(words, remaining, " morgens");
      } else if ( hours < 13) {
        remaining -= append_string(words, remaining, " mittags");
      } else if ( hours < 18) {
        remaining -= append_string(words, remaining, " nach- mittags");
      } else {
        remaining -= append_string(words, remaining, " abends");
      }
    }
    return;
  };
  
  if (minutes <= 3) {
    remaining -= append_string(words, remaining, "kurz nach");
  } else if (minutes <= 8) {
    remaining -= append_string(words, remaining, "fünf nach");
  } else if (minutes <= 12) {
    remaining -= append_string(words, remaining, "zehn nach");
  } else if (minutes <= 17) {
    remaining -= append_string(words, remaining, "viertel nach");
  } else if (minutes <= 22) {
    remaining -= append_string(words, remaining, "zwanzig nach");
  } else if (minutes <= 28) {
    remaining -= append_string(words, remaining, "fünf vor halb");
  } else if (minutes <= 29) {
    remaining -= append_string(words, remaining, "kurz vor halb");
  } else if (minutes <= 30) {
    remaining -= append_string(words, remaining, "halb");
  } else if (minutes <= 32) {
    remaining -= append_string(words, remaining, "kurz nach halb");
  } else if (minutes <= 37) {
    remaining -= append_string(words, remaining, "fünf nach halb");
  } else if (minutes <= 43) {
    remaining -= append_string(words, remaining, "zwanzig vor");
  } else if (minutes <= 48) {
    remaining -= append_string(words, remaining, "viertel vor");
  } else if (minutes <= 53) {
    remaining -= append_string(words, remaining, "zehn vor");
  } else if (minutes <= 57) {
    remaining -= append_string(words, remaining, "fünf vor");
  } else if (minutes <= 59) {
    remaining -= append_string(words, remaining, "kurz vor");
  }
  
  remaining -= append_string(words, remaining, " ");
  if (minutes < 23) {
    remaining -= append_string(words, remaining, STUNDEN[hours % 12]);
  } else {
    remaining -= append_string(words, remaining, STUNDEN[(hours+1) % 12]);
  }
}
Example #20
0
/*
 * Print Call-ID header field
 * created an extra function for pure header field creation, that is used by t_cancel for 
 * t_uac_cancel FIFO function.
 */
char* print_callid_mini(char* target, str callid) {
	append_string(target, CALLID, CALLID_LEN);
	append_string(target, callid.s, callid.len);
	append_string(target, CRLF, CRLF_LEN);
	return target;
}
Example #21
0
void Inspect::operator()(Unary_Expression* expr)
{
    if (expr->type() == Unary_Expression::PLUS) append_string("+");
    else                                        append_string("-");
    expr->operand()->perform(this);
}
Example #22
0
/*
 * Create a request
 */
char* build_uac_req(str* method, str* headers, str* body, dlg_t* dialog, 
										int branch, struct cell *t, int* len)
{
	char* buf, *w;
	str content_length, cseq, via;

	if (!method || !dialog) {
		LM_ERR("inalid parameter value\n");
		return 0;
	}
	if (print_content_length(&content_length, body) < 0) {
		LM_ERR("failed to print content-length\n");
		return 0;
	}
	if (print_cseq_num(&cseq, dialog) < 0) {
		LM_ERR("failed to print CSeq number\n");
		return 0;
	}
	*len = method->len + 1 + dialog->hooks.request_uri->len + 1 + 
		SIP_VERSION_LEN + CRLF_LEN;

	if (assemble_via(&via, t, dialog->send_sock, branch) < 0) {
		LM_ERR("failed to assemble Via\n");
		return 0;
	}
	*len += via.len;

	/* To */
	*len += TO_LEN 
		+ (dialog->rem_dname.len ? dialog->rem_dname.len+1 : 0)
		+ dialog->rem_uri.len
		+ (dialog->id.rem_tag.len ? TOTAG_LEN + dialog->id.rem_tag.len : 0)
		+ (dialog->rem_dname.len || dialog->id.rem_tag.len ? 2 : 0)
		+ CRLF_LEN;
	/* From */
	*len += FROM_LEN 
		+ (dialog->loc_dname.len ? dialog->loc_dname.len+1 : 0)
		+ dialog->loc_uri.len
		+ (dialog->id.loc_tag.len ? FROMTAG_LEN + dialog->id.loc_tag.len : 0)
		+ (dialog->loc_dname.len || dialog->id.loc_tag.len ? 2 : 0)
		+ CRLF_LEN;
	/* Call-ID */
	*len += CALLID_LEN + dialog->id.call_id.len + CRLF_LEN;
	/* CSeq */
	*len += CSEQ_LEN + cseq.len + 1 + method->len + CRLF_LEN;
	/* Route set */
	*len += calculate_routeset_length(dialog);
	/* Content-Length */
	*len += CONTENT_LENGTH_LEN + content_length.len + CRLF_LEN;
	/* Signature */
	*len += (server_signature ? (user_agent_header.len + CRLF_LEN) : 0);
	/* Additional headers */
	*len += (headers ? headers->len : 0);
	/* Message body */
	*len += (body ? body->len : 0);
	/* End of Header */
	*len += CRLF_LEN;

	buf = shm_malloc(*len + 1);
	if (!buf) {
		LM_ERR("no more share memory\n");
		goto error;
	}
	
	w = buf;

	w = print_request_uri(w, method, dialog, t, branch);  /* Request-URI */
	append_string(w, via.s, via.len);                     /* Top-most Via */
	w = print_to(w, dialog, t);                           /* To */
	w = print_from(w, dialog, t);                         /* From */
	w = print_cseq(w, &cseq, method, t);                  /* CSeq */
	w = print_callid(w, dialog, t);                       /* Call-ID */
	w = print_routeset(w, dialog);                        /* Route set */

	/* Content-Length */
	append_string(w, CONTENT_LENGTH, CONTENT_LENGTH_LEN);
	append_string(w, content_length.s, content_length.len);
	append_string(w, CRLF, CRLF_LEN);

	/* Server signature */
	if (server_signature) {
		append_string(w, user_agent_header.s, user_agent_header.len);
		append_string(w, CRLF, CRLF_LEN);
	}
	if (headers)
		append_string(w, headers->s, headers->len);
	append_string(w, CRLF, CRLF_LEN);
	if (body)
		append_string(w, body->s, body->len);

#ifdef EXTRA_DEBUG
	if (w-buf != *len ) abort();
#endif

	pkg_free(via.s);
	return buf;

 error:
	pkg_free(via.s);
	return 0;
}
Example #23
0
struct mem_buf *
template_get_chunk(struct template_chunk *chunk, const gwc_full_stats_t *stats)
{
  char buf[1024], *p = buf;
  size_t avail = sizeof buf;

  switch (chunk->type) {
  case chunk_http_response:
  case chunk_http_header:
  case chunk_data:
    /* Must be handled elsewhere */
    p = NULL;
    RUNTIME_ASSERT(0);
    break;

  case crab_stats_total_updates:
    p = append_uint64(buf, &avail, stats->total.updates);
    break;
  case crab_stats_total_updates_ip:
    p = append_uint64(buf, &avail, stats->total.ip_updates);
    break;
  case crab_stats_total_updates_url:
    p = append_uint64(buf, &avail, stats->total.url_updates);
    break;
  case crab_stats_total_requests:
    p = append_uint64(buf, &avail, stats->total.requests);
    break;
  case crab_stats_total_requests_base:
    p = append_uint64(buf, &avail, stats->total.base_requests);
    break;
  case crab_stats_total_requests_data:
    p = append_uint64(buf, &avail, stats->total.data_requests);
    break;
  case crab_stats_total_requests_get:
    p = append_uint64(buf, &avail, stats->total.get_requests);
    break;
  case crab_stats_total_requests_hostfile:
    p = append_uint64(buf, &avail, stats->total.hostfile_requests);
    break;
  case crab_stats_total_requests_urlfile:
    p = append_uint64(buf, &avail, stats->total.urlfile_requests);
    break;
  case crab_stats_total_requests_ping:
    p = append_uint64(buf, &avail, stats->total.ping_requests);
    break;
  case crab_stats_total_requests_statfile:
    p = append_uint64(buf, &avail, stats->total.statfile_requests);
    break;
  case crab_stats_total_accepts:
    p = append_uint64(buf, &avail, stats->total.accepts);
    break;
  case crab_stats_total_blocked:
    p = append_uint64(buf, &avail, stats->total.blocked);
    break;
  case crab_stats_total_errors:
    p = append_uint64(buf, &avail, stats->total.errors);
    break;
  case crab_stats_total_http_400s:
    p = append_uint64(buf, &avail, stats->total.http_400s);
    break;
  case crab_stats_total_http_404s:
    p = append_uint64(buf, &avail, stats->total.http_404s);
    break;
  case crab_stats_total_too_early:
    p = append_uint64(buf, &avail, stats->total.too_early);
    break;
  case crab_stats_total_rx:
    p = append_size(buf, &avail, stats->total.rx);
    break;
  case crab_stats_total_tx:
    p = append_size(buf, &avail, stats->total.tx);
    break;

  case crab_stats_hourly_updates:
    p = append_uint64(buf, &avail, stats->hourly.updates);
    break;
  case crab_stats_hourly_updates_ip:
    p = append_uint64(buf, &avail, stats->hourly.ip_updates);
    break;
  case crab_stats_hourly_updates_url:
    p = append_uint64(buf, &avail, stats->hourly.url_updates);
    break;
  case crab_stats_hourly_requests:
    p = append_uint64(buf, &avail, stats->hourly.requests);
    break;
  case crab_stats_hourly_requests_base:
    p = append_uint64(buf, &avail, stats->hourly.base_requests);
    break;
  case crab_stats_hourly_requests_data:
    p = append_uint64(buf, &avail, stats->hourly.data_requests);
    break;
  case crab_stats_hourly_requests_get:
    p = append_uint64(buf, &avail, stats->hourly.get_requests);
    break;
  case crab_stats_hourly_requests_hostfile:
    p = append_uint64(buf, &avail, stats->hourly.hostfile_requests);
    break;
  case crab_stats_hourly_requests_urlfile:
    p = append_uint64(buf, &avail, stats->hourly.urlfile_requests);
    break;
  case crab_stats_hourly_requests_ping:
    p = append_uint64(buf, &avail, stats->hourly.ping_requests);
    break;
  case crab_stats_hourly_requests_statfile:
    p = append_uint64(buf, &avail, stats->hourly.statfile_requests);
    break;
  case crab_stats_hourly_accepts:
    p = append_uint64(buf, &avail, stats->hourly.accepts);
    break;
  case crab_stats_hourly_blocked:
    p = append_uint64(buf, &avail, stats->hourly.blocked);
    break;
  case crab_stats_hourly_errors:
    p = append_uint64(buf, &avail, stats->hourly.errors);
    break;
  case crab_stats_hourly_http_400s:
    p = append_uint64(buf, &avail, stats->hourly.http_400s);
    break;
  case crab_stats_hourly_http_404s:
    p = append_uint64(buf, &avail, stats->hourly.http_404s);
    break;
  case crab_stats_hourly_too_early:
    p = append_uint64(buf, &avail, stats->hourly.too_early);
    break;
  case crab_stats_hourly_rx:
    p = append_size(buf, &avail, stats->hourly.rx);
    break;
  case crab_stats_hourly_tx:
    p = append_size(buf, &avail, stats->hourly.tx);
    break;

  case crab_startup_time:
    p = append_date(buf, &avail, stats->start_time.tv_sec);
    break;
    
  case crab_user_agent:
    p = append_string(buf, &avail, GWC_USER_AGENT);
    break;

  case crab_uri:
    p = append_string(buf, &avail, OPTION(gwc_uri));
    break;

  case crab_url:
    p = append_string(buf, &avail, OPTION(gwc_url));
    break;

  case crab_network_id:
    p = append_string(buf, &avail,
          OPTION(network_id) ? OPTION(network_id) : "gnutella");
    break;
    
  case crab_contact_address:
    p = append_string(buf, &avail,
          OPTION(contact_address) ? OPTION(contact_address) : "");
    break;

#if defined(HAVE_GETRUSAGE)
#define RU_TIME(x) stats->ru.x
#else
#define RU_TIME(x) 0
#endif /* HAVE_GETRUSAGE */
 
  case crab_rusage_utime:
    {
      uint64_t v;

      v = (uint64_t) RU_TIME(ru_utime.tv_sec) * 1000000 +
        RU_TIME(ru_utime.tv_usec);
      p = append_uint64(buf, &avail, v);
    }
    break;
  case crab_rusage_stime:
    {
      uint64_t v;

      v = (uint64_t) RU_TIME(ru_stime.tv_sec) * 1000000 +
        RU_TIME(ru_stime.tv_usec);
      p = append_uint64(buf, &avail, v);
    }
    break;
    
   case crab_rusage_utime_percent:
    {
      uint64_t v;

      v = (uint64_t) RU_TIME(ru_utime.tv_sec) * 1000000 +
        RU_TIME(ru_utime.tv_usec);
      p = append_uint64(buf, &avail, v);
    }
    break;
  case crab_rusage_stime_percent:
    {
      uint64_t v;

      v = (uint64_t) RU_TIME(ru_stime.tv_sec) * 1000000 +
        RU_TIME(ru_stime.tv_usec);
      p = append_uint64(buf, &avail, v);
    }
    break;
    
#if defined(HAVE_GETRUSAGE) && defined(HAVE_BSD_STRUCT_RUSAGE)
#define RU(x) stats->ru.x
#else
#define RU(x) 0
#endif /* HAVE_GETRUSAGE && HAVE_BSD_STRUCT_RUSAGE */
    
  case crab_rusage_maxrss:
    p = append_uint64(buf, &avail, RU(ru_maxrss));
    break;
  case crab_rusage_ixrss:
    p = append_uint64(buf, &avail, RU(ru_ixrss));
    break;
  case crab_rusage_idrss:
    p = append_uint64(buf, &avail, RU(ru_idrss));
    break;
  case crab_rusage_isrss:
    p = append_uint64(buf, &avail, RU(ru_isrss));
    break;
  case crab_rusage_minflt:
    p = append_uint64(buf, &avail, RU(ru_minflt));
    break;
  case crab_rusage_majflt:
    p = append_uint64(buf, &avail, RU(ru_majflt));
    break;
  case crab_rusage_nswap:
    p = append_uint64(buf, &avail, RU(ru_nswap));
    break;
  case crab_rusage_inblock:
    p = append_uint64(buf, &avail, RU(ru_inblock));
    break;
  case crab_rusage_oublock:
    p = append_uint64(buf, &avail, RU(ru_oublock));
    break;
  case crab_rusage_msgsnd:
    p = append_uint64(buf, &avail, RU(ru_msgsnd));
    break;
  case crab_rusage_msgrcv:
    p = append_uint64(buf, &avail, RU(ru_msgrcv));
    break;
  case crab_rusage_nsignals:
    p = append_uint64(buf, &avail, RU(ru_nsignals));
    break;
  case crab_rusage_nvcsw:
    p = append_uint64(buf, &avail, RU(ru_nvcsw));
    break;
  case crab_rusage_nivcsw:
    p = append_uint64(buf, &avail, RU(ru_nivcsw));
    break;
    
#undef RU

  default:
    CRIT("Unknown chunk type (%u)", (unsigned) chunk->type);
    p = NULL;
    RUNTIME_ASSERT(0);
  }

  if (p && p != buf) {
    return mem_buf_new_copy(buf, p - buf);
  }
  return NULL;
}
Example #24
0
static int
make_env_block(char* env_block, size_t block_size, const char **env, int env_count)
{
	size_t cursor = 0;
	char *p = win32_env_block;
	unsigned char used_env[1024];

	if (env_count > sizeof(used_env))
		return 1;

	memset(used_env, 0, sizeof(used_env));

	while (*p)
	{
		int i;
		int replaced = 0;
		size_t len;

		for (i = 0; i < env_count; ++i)
		{
			const char *equals;

			if (used_env[i])
				continue;

			equals = strchr(env[i], '=');

			if (!equals)
				continue;

			if (0 == _strnicmp(p, env[i], equals - env[i] + 1))
			{
				if (0 != append_string(env_block, block_size, &cursor, env[i]))
					return 1;
				used_env[i] = 1;
				replaced = 1;
				break;
			}
		}

		len = strlen(p);

		/* skip items without name that win32 seems to include for itself */
		if (!replaced && p[0] != '=')
		{
			if (0 != append_string(env_block, block_size, &cursor, p))
				return 1;
		}

		p = p + len + 1;
	}

	{
		int i;
		for (i = 0; i < env_count; ++i)
		{
			if (used_env[i])
				continue;
			if (0 != append_string(env_block, block_size, &cursor, env[i]))
				return 1;
		}
	}

	env_block[cursor] = '\0';
	env_block[cursor+1] = '\0';
	return 0;
}
Example #25
0
mqtt_message_t* ICACHE_FLASH_ATTR mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_info_t* info)
{
  struct mqtt_connect_variable_header* variable_header;

  init_message(connection);

  if(connection->message.length + sizeof(*variable_header) > connection->buffer_length)
    return fail_message(connection);
  variable_header = (void*)(connection->buffer + connection->message.length);
  connection->message.length += sizeof(*variable_header);

  variable_header->lengthMsb = 0;
#if defined(PROTOCOL_NAMEv31)
  variable_header->lengthLsb = 6;
  memcpy(variable_header->magic, "MQIsdp", 6);
  variable_header->version = 3;
#elif defined(PROTOCOL_NAMEv311)
  variable_header->lengthLsb = 4;
  memcpy(variable_header->magic, "MQTT", 4);
  variable_header->version = 4;
#else
#error "Please define protocol name"
#endif

  variable_header->flags = 0;
  variable_header->keepaliveMsb = info->keepalive >> 8;
  variable_header->keepaliveLsb = info->keepalive & 0xff;

  if(info->clean_session)
    variable_header->flags |= MQTT_CONNECT_FLAG_CLEAN_SESSION;

  if(info->client_id != NULL && info->client_id[0] != '\0')
  {
    if(append_string(connection, info->client_id, strlen(info->client_id)) < 0)
      return fail_message(connection);
  }
  else
    return fail_message(connection);

  if(info->will_topic != NULL && info->will_topic[0] != '\0')
  {
    if(append_string(connection, info->will_topic, strlen(info->will_topic)) < 0)
      return fail_message(connection);

    if(append_string(connection, info->will_message, strlen(info->will_message)) < 0)
      return fail_message(connection);

    variable_header->flags |= MQTT_CONNECT_FLAG_WILL;
    if(info->will_retain)
      variable_header->flags |= MQTT_CONNECT_FLAG_WILL_RETAIN;
    variable_header->flags |= (info->will_qos & 3) << 3;
  }

  if(info->username != NULL && info->username[0] != '\0')
  {
    if(append_string(connection, info->username, strlen(info->username)) < 0)
      return fail_message(connection);

    variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME;
  }

  if(info->password != NULL && info->password[0] != '\0')
  {
    if(append_string(connection, info->password, strlen(info->password)) < 0)
      return fail_message(connection);

    variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD;
  }

  return fini_message(connection, MQTT_MSG_TYPE_CONNECT, 0, 0, 0);
}
Example #26
0
void time_to_words(int hours, int minutes, char* words, size_t length) {

  size_t remaining = length;
  memset(words, 0, length);

  // Fuzzy time
  minutes = (minutes + 3) / 5 * 5;

  // Handle minute wrapping
  if (minutes > 55)
  {
    minutes -= 60;
    hours++;
  }

  
  switch (minutes)
  {
    case 0:
      break;
    case 20:
      remaining -= append_number(words, minutes);
      remaining -= append_string(words, remaining, " ");
      remaining -= append_string(words, remaining, PAST);
      remaining -= append_string(words, remaining, " ");
      break;
    case 15:
      //remaining -= append_string(words, remaining, QUART);
      //remaining -= append_string(words, remaining, " ");
      //remaining -= append_string(words, remaining, PAST);
      //remaining -= append_string(words, remaining, " ");
		remaining -= append_string(words, remaining, QUART);
		remaining -= append_string(words, remaining, " de ");
		hours++;
      break;
    case 25:
		remaining -= append_number(words, 2);
		remaining -= append_string(words, remaining, " ");
		remaining -= append_string(words, remaining, QUARTS);
		remaining -= append_string(words, remaining, " ");    
		remaining -= append_string(words, remaining, MENYS);
		remaining -= append_string(words, remaining, " ");   
		remaining -= append_number(words, 5);
		remaining -= append_string(words, remaining, " de ");	  
		hours++;		
		break;
    case 30:
		remaining -= append_number(words, 2);
		remaining -= append_string(words, remaining, " ");
		remaining -= append_string(words, remaining, QUARTS);
		remaining -= append_string(words, remaining, " de ");
		hours++;
		break;
    case 35:
      remaining -= append_number(words, 20);
      remaining -= append_string(words, remaining, " ");
      remaining -= append_number(words, 5);
      remaining -= append_string(words, remaining, " ");    
      remaining -= append_string(words, remaining, TO);
      remaining -= append_string(words, remaining, " ");    
      hours++;
      break;
    case 40:
		remaining -= append_number(words, 3);
		remaining -= append_string(words, remaining, " ");
		remaining -= append_string(words, remaining, QUARTS);
		remaining -= append_string(words, remaining, " ");    
		remaining -= append_string(words, remaining, MENYS);
		remaining -= append_string(words, remaining, " ");   
		remaining -= append_number(words, 5);
		remaining -= append_string(words, remaining, " de ");	
		hours++;
		break;
    case 50:
		remaining -= append_number(words, 3);
		remaining -= append_string(words, remaining, " ");
		remaining -= append_string(words, remaining, QUARTS);
		remaining -= append_string(words, remaining, " i ");    
		remaining -= append_number(words, 5);
		remaining -= append_string(words, remaining, " de ");	
		hours++;
		break;	
    case 55:
      remaining -= append_number(words, 60 - minutes);
      remaining -= append_string(words, remaining, " ");
      remaining -= append_string(words, remaining, TO);
      remaining -= append_string(words, remaining, " ");
      hours++;
      break;
    case 45:
		remaining -= append_number(words, 3);
		remaining -= append_string(words, remaining, " ");
		remaining -= append_string(words, remaining, QUARTS);
		remaining -= append_string(words, remaining, " de ");
		hours++;
		break;	
  }

  // Handle hour wrapping
  hours += 12; // If hours == 0
  while (hours > 12)
  {
    hours -= 12;
  }

  
  // Singular o Plural depenent de la hora
  if (hours == 13 || hours == 1)
  {
	remaining -= append_string(words, remaining, SINGULAR);
	remaining -= append_string(words, remaining, " ");	
  }  
  else
  {
	//remaining -= append_string(words, remaining, PLURAL);
	//remaining -= append_string(words, remaining, " ");	
  }

  remaining -= append_string(words, remaining, "*"); // Make hours bold
  
  remaining -= append_number(words, hours);
  remaining -= append_string(words, remaining, " ");

  
  switch(minutes)
  {
  case 0:
	// Add o'clock to whole hours
	remaining -= append_string(words, remaining, ENPUNT);
	remaining -= append_string(words, remaining, " ");
    
	case 5:
	case 10:
		remaining -= append_number(words, minutes);
		break;
  }

  
}
Example #27
0
static int build_csv_record(char *buf, size_t bufsize, struct ast_cdr *cdr)
{

	buf[0] = '\0';
	/* Account code */
	append_string(buf, cdr->accountcode, bufsize);
	/* Source */
	append_string(buf, cdr->src, bufsize);
	/* Destination */
	append_string(buf, cdr->dst, bufsize);
	/* Destination context */
	append_string(buf, cdr->dcontext, bufsize);
	/* Caller*ID */
	append_string(buf, cdr->clid, bufsize);
	/* Channel */
	append_string(buf, cdr->channel, bufsize);
	/* Destination Channel */
	append_string(buf, cdr->dstchannel, bufsize);
	/* Last Application */
	append_string(buf, cdr->lastapp, bufsize);
	/* Last Data */
	append_string(buf, cdr->lastdata, bufsize);
	/* Start Time */
	append_date(buf, cdr->start, bufsize);
	/* Answer Time */
	append_date(buf, cdr->answer, bufsize);
	/* End Time */
	append_date(buf, cdr->end, bufsize);
	/* Duration */
	append_int(buf, cdr->duration, bufsize);
	/* Billable seconds */
	append_int(buf, cdr->billsec, bufsize);
	/* Disposition */
	append_string(buf, ast_cdr_disp2str(cdr->disposition), bufsize);
	/* AMA Flags */
	append_string(buf, ast_channel_amaflags2string(cdr->amaflags), bufsize);
	/* Unique ID */
	if (loguniqueid)
		append_string(buf, cdr->uniqueid, bufsize);
	/* append the user field */
	if(loguserfield)
		append_string(buf, cdr->userfield,bufsize);
	/* If we hit the end of our buffer, log an error */
	if (strlen(buf) < bufsize - 5) {
		/* Trim off trailing comma */
		buf[strlen(buf) - 1] = '\0';
		strncat(buf, "\n", bufsize - strlen(buf) - 1);
		return 0;
	}
	return -1;
}
Example #28
0
static krb5_error_code
entry2string_int (krb5_context context, krb5_storage *sp, hdb_entry *ent)
{
    char *p;
    int i;
    krb5_error_code ret;

    /* --- principal */
    ret = krb5_unparse_name(context, ent->principal, &p);
    if(ret)
	return ret;
    append_string(context, sp, "%s ", p);
    free(p);
    /* --- kvno */
    append_string(context, sp, "%d", ent->kvno);
    /* --- keys */
    for(i = 0; i < ent->keys.len; i++){
	/* --- mkvno, keytype */
	if(ent->keys.val[i].mkvno)
	    append_string(context, sp, ":%d:%d:", 
			  *ent->keys.val[i].mkvno, 
			  ent->keys.val[i].key.keytype);
	else
	    append_string(context, sp, "::%d:", 
			  ent->keys.val[i].key.keytype);
	/* --- keydata */
	append_hex(context, sp, &ent->keys.val[i].key.keyvalue);
	append_string(context, sp, ":");
	/* --- salt */
	if(ent->keys.val[i].salt){
	    append_string(context, sp, "%u/", ent->keys.val[i].salt->type);
	    append_hex(context, sp, &ent->keys.val[i].salt->salt);
	}else
	    append_string(context, sp, "-");
    }
    append_string(context, sp, " ");
    /* --- created by */
    append_event(context, sp, &ent->created_by);
    /* --- modified by */
    append_event(context, sp, ent->modified_by);

    /* --- valid start */
    if(ent->valid_start)
	append_string(context, sp, "%s ", time2str(*ent->valid_start));
    else
	append_string(context, sp, "- ");

    /* --- valid end */
    if(ent->valid_end)
	append_string(context, sp, "%s ", time2str(*ent->valid_end));
    else
	append_string(context, sp, "- ");
    
    /* --- password ends */
    if(ent->pw_end)
	append_string(context, sp, "%s ", time2str(*ent->pw_end));
    else
	append_string(context, sp, "- ");

    /* --- max life */
    if(ent->max_life)
	append_string(context, sp, "%d ", *ent->max_life);
    else
	append_string(context, sp, "- ");

    /* --- max renewable life */
    if(ent->max_renew)
	append_string(context, sp, "%d ", *ent->max_renew);
    else
	append_string(context, sp, "- ");
    
    /* --- flags */
    append_string(context, sp, "%d ", HDBFlags2int(ent->flags));

    /* --- generation number */
    if(ent->generation) {
	append_string(context, sp, "%s:%d:%d", time2str(ent->generation->time),
		      ent->generation->usec,
		      ent->generation->gen);
    } else
	append_string(context, sp, "-");
    
    return 0;
}
Example #29
0
File: defun.c Project: AltSysrq/tgl
/* Common function for v and V.
 *
 * aux: if non-NULL, any code to evaluate before the defun
 * defun: command to run to define the command.
 */
static int builtin_defunlibrary_common(interpreter* interp,
                                       string aux,
                                       byte defun) {
  string name, body, code;
  struct tm* now;
  time_t seconds;
  char header[256], date[64];
  FILE* out;
  unsigned i;

  if (!stack_pop_strings(interp, 2, &body, &name)) UNDERFLOW;

  /* We can't allow the name to have parentheses or the NUL character. */
  for (i = 0; i < name->len; ++i)
    if (string_data(name)[i] == '(' || string_data(name)[i] == ')' ||
        string_data(name)[i] == 0) {
      print_error_s("Invalid command name (for use with v/V)", name);
      stack_push(interp, name);
      stack_push(interp, body);
      return 0;
    }

  /* Build code */
  time(&seconds);
  now = localtime(&seconds);
  strftime(date, sizeof(date)-1, "%A, %Y.%m.%d %H:%M:%S", now);
  snprintf(header, sizeof(header), "\n(Added by %s on %s);\n",
           getenv("USER"), date);
  code = convert_string(header);
  if (aux)
    code = append_string(code, aux);
  code = append_cstr(code, "(");
  code = append_string(code, name);
  code = append_cstr(code, ")(");
  code = append_string(code, body);
  code = append_cstr(code, ")");
  code = append_data(code, &defun, (&defun)+1);
  code = append_cstr(code, "\n");

  /* Evaluate in current */
  if (!exec_code(interp, code)) {
    print_error("not adding function to library due to error(s)");
    stack_push(interp, name);
    stack_push(interp, code);
    return 0;
  }

  /* Don't need name or code anymore. */
  free(name);
  free(body);

  /* OK, write out */
  out = fopen(user_library_file, "a");
  if (!out) {
    fprintf(stderr, "tgl: error: unable to open %s: %s\n",
            user_library_file, strerror(errno));
    free(code);
    return 0;
  }
  if (code->len !=
      fwrite(string_data(code), 1, code->len, out)) {
    fprintf(stderr, "tgl: error writing to %s: %s\n",
            user_library_file, strerror(errno));
    free(code);
    fclose(out);
    return 0;
  }

  /* Success */
  fclose(out);
  free(code);
  return 1;
}
Example #30
0
static void xbt_log_layout_format_dynamic(xbt_log_layout_t l,
                                          xbt_log_event_t ev,
                                          const char *fmt,
                                          xbt_log_appender_t app)
{
  xbt_strbuff_t buff = xbt_strbuff_new();
  char tmpfmt[50];
  int precision = -1;
  int length = -1;
  char *q = l->data;
  char *tmp;
  char *tmp2;

  while (*q != '\0') {
    if (*q == '%') {
      q++;
    handle_modifier:
      switch (*q) {
      case '\0':
        fprintf(stderr, "Layout format (%s) ending with %%\n",
                (char *) l->data);
        abort();
      case '%':
        xbt_strbuff_append(buff, "%");
        break;
      case 'n':                /* platform-dependant line separator (LOG4J compliant) */
        xbt_strbuff_append(buff, "\n");
        break;
      case 'e':                /* plain space (SimGrid extension) */
        xbt_strbuff_append(buff, " ");
        break;

      case '.':                /* precision specifyier */
        q++;
        sscanf(q, "%d", &precision);
        q += (precision>9?2:1);
        goto handle_modifier;

      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9': /* length modifier */
        sscanf(q, "%d", &length);
        q += (length>9?2:1);
        goto handle_modifier;

      case 'c':                /* category name; LOG4J compliant
                                   should accept a precision postfix to show the hierarchy */
        append_string(ev->cat->name);
        break;
      case 'p':                /* priority name; LOG4J compliant */
        append_string(xbt_log_priority_names[ev->priority]);
        break;

      case 'h':                /* host name; SimGrid extension */
        append_string(gras_os_myname());
        break;
      case 't':                /* thread name; LOG4J compliant */
        append_string(xbt_thread_self_name());
        break;
      case 'P':                /* process name; SimGrid extension */
        append_string(xbt_procname());
        break;
      case 'i':                /* process PID name; SimGrid extension */
        append_int((*xbt_getpid) ());
        break;

      case 'F':                /* file name; LOG4J compliant */
        append_string(ev->fileName);
        break;
      case 'l':                /* location; LOG4J compliant */
        append2("%s:%d", ev->fileName, ev->lineNum);
        precision = -1;         /* Ignored */
        break;
      case 'L':                /* line number; LOG4J compliant */
        append_int(ev->lineNum);
        break;
      case 'M':                /* method (ie, function) name; LOG4J compliant */
        append_string(ev->functionName);
        break;
      case 'b':                /* backtrace; called %throwable in LOG4J */
      case 'B':                /* short backtrace; called %throwable{short} in LOG4J */
#if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE)
        {
          xbt_ex_t e;
          int i;

          e.used = backtrace((void **) e.bt, XBT_BACKTRACE_SIZE);
          e.bt_strings = NULL;
          e.msg = NULL;
          e.remote = 0;
          xbt_backtrace_current(&e);
          if (*q == 'B') {
            append_string(e.bt_strings[2] + 8);
          } else {
            for (i = 2; i < e.used; i++) {
              append_string(e.bt_strings[i] + 8);
              xbt_strbuff_append(buff, "\n");
            }
          }

          xbt_ex_free(e);
        }
#else
        append_string("(no backtrace on this arch)");
#endif
        break;

      case 'd':                /* date; LOG4J compliant */
        append_double(gras_os_time());
        break;
      case 'r':                /* application age; LOG4J compliant */
        append_double(gras_os_time() - format_begin_of_time);
        break;

      case 'm':                /* user-provided message; LOG4J compliant */
        tmp2 = bvprintf(fmt, ev->ap_copy);
        append_string(tmp2);
        free(tmp2);
        break;

      default:
        fprintf(stderr, ERRMSG, *q, (char *) l->data);
        abort();
      }
      q++;
    } else {
      char tmp2[2];
      tmp2[0] = *(q++);
      tmp2[1] = '\0';
      xbt_strbuff_append(buff, tmp2);
    }
  }
  app->do_append(app, buff->data);
  xbt_strbuff_free(buff);
}