#include "../apache.h"

char *get_tag(char *tag, int tagbuf_len)
{
  char *tag_val, c, term;
  char *t;

  t = tag;

  --tagbuf_len;

  do {
    GET_CHAR(c, NULL);
  } while (ap_isspace(c));

  if (c == '-') {
    GET_CHAR(c, NULL);
    if (c == '-') {
      do {
        GET_CHAR(c, NULL);
      } while (ap_isspace(c));
      if (c == '>') {
        ap_cpystrn(tag, "done", tagbuf_len);
        return tag;
      }
    }
    return NULL;
  }

  while (1) {
    if (t == tag + tagbuf_len) {
      *t = EOS;
      return NULL;
    }
    if (c == '=' || ap_isspace(c)) {
      break;
    }
    *t = ap_tolower(c);
    t++;
    GET_CHAR(c, NULL);
  }

  *t = EOS;
  t++;
  tag_val = t;

  while (ap_isspace(c)) {
    GET_CHAR(c, NULL);
  }
  if (c != '=') {
    return NULL;
  }

  do {
    GET_CHAR(c, NULL);
  } while (ap_isspace(c));

  if (c != '"' && c != '\'') {
    return NULL;
  }
  term = c;
  while (1) {
    GET_CHAR(c, NULL);
    if (t == tag + tagbuf_len) { /* Suppose t == tag + tagbuf_len - 1 */
      *t = EOS;
      return NULL;
    }

    if (c == '\\') {
      /* BAD */
      *t = c;
      t++;               /* Now t == tag + tagbuf_len */
      GET_CHAR(c, NULL);
      if (c == term) {   /* Assume this branch isn't taken */
        --t;
        /* BAD */
        *t = c;
      }
    }
    else if (c == term) {
      break;
    }

    /* BAD */
    *t = c;    
    t++;                /* Now t == tag + tagbuf_len + 1 
                         * So the bounds check (t == tag + tagbuf_len) will fail */
  }
  /* BAD */
  *t = EOS;

  return tag;
}

int main ()
{
  char tag[MAX_STRING_LEN];

  /* The caller always passes in (tag, sizeof(tag)) */
  get_tag (tag, MAX_STRING_LEN);

  return 0;
}
