示例#1
0
server_var::server_var(const char* szline)
{
    vector<string> vVars;
    vSplitString(szline, vVars, ";", TRUE);
    vector<string>::iterator iter_c;
        
    ServerVarParsePhase phase = SERVER_VAR_CREATE;
    for(iter_c = vVars.begin(); iter_c != vVars.end(); iter_c++)
    {
        string strField(*iter_c);
        strtrim(strField);
        
        if(phase == SERVER_VAR_CREATE)
        {
            m_create = atoi(strField.c_str());
            phase = SERVER_VAR_ACCESS;
        }
        else if(phase == SERVER_VAR_ACCESS)
        {
            m_access = atoi(strField.c_str());
            phase = SERVER_VAR_KEYVAL;
        }
        else if(phase == SERVER_VAR_KEYVAL)
        {
            strcut(strField.c_str(), NULL, "=", m_name);
            strcut(strField.c_str(), "=", NULL, m_value);
            strtrim(m_name);
            strtrim(m_value);
            phase = SERVER_VAR_OPTION;
        }
    }
}
示例#2
0
文件: cfmt.c 项目: wjlei1990/WORKFLOW
/** 
 * Format and send a error message containing the current command
 * 
 * @param kmsg2 
 *    Second line of error message with a "$" appended to it
 *    A point to the bad token will be added to this line.
 *    The first line will contain a standard error message 
 *    with the current command appended to it.
 * @param kmsg2_s 
 *    Length of \p kmsg2
 *
 * @date   820615:  Added call to CERR to set error condition.
 * @date   820420:  Original version.
 *
 */
void 
cfmt(char *kmsg2, 
     int   kmsg2_s) {

	static char kmsg1[28] = "ERROR interpreting command:";

	/* - Raise command syntax error condition. */
	cerr( 1001 );
  
  char *s = strcut(kmsg2, 1, indexb(kmsg2, kmsg2_s));
  bell();
  fprintf(stdout, " %s  %s \n", kmsg1, lexer_input());
  if(arg()) {
    fprintf(stdout, " %*s  %*s\n", -(int)strlen(kmsg1), s, arg()->col, "^");
  } else {
    fprintf(stdout, " %*s  %*s\n", -(int)strlen(kmsg1), s, (int)strlen(lexer_input()), "^");
  }
  
  FREE(s);

  return;

	return;

} /* end of function */
示例#3
0
char *
strcut_wrapper(char *hay, char *needle)
{
	strcut(hay, needle);

	return hay;
}
示例#4
0
char *strcutpad( char *string, int length )
{
    if ( colorlen(string) > length )
        return strcut(string,length);
    else if ( colorlen(string) < length )
        return strpad(string,length);
    else return string;
}
示例#5
0
文件: prop.cpp 项目: nmmmnu/ccc
void Properties::putParsedStr(const char *s, char delim){
   if (isempty(s))
      return;

   StringTokenizer *st = new StringTokenizer(s, delim);

   char *tmp1 = strdupn(st->nextToken());
   char *tmp2 = strdupn(st->nextToEnd());

   const char *name = strcut(tmp1);
   const char *value = strcut(tmp2);

   put(name, value); 

   free(tmp1);
   free(tmp2);
   delete(st);
};
示例#6
0
/** 
 * Append alphanumberic string \p kalpha to current message
 *
 * \param kalpha
 *    Alphanumberic string to append to current message
 * \param kalpha_s
 *    Length of string \p kalpha
 *
 * \return Nothing
 *
 * \see indexb outmsg clrmsg
 * \see t_cmmsg.nlimsg
 * \see t_cmmsg.nchmsg
 * \see t_cmmsg.autoout
 * \see t_cmmsg.itpmsg
 * \see t_kmmsg.klimsg
 *
 * \date   900518:  Added logic to test for an empty string. 
 *                    This corrects a problem with VAX VMS version.
 * \date   890104:  Added automatic output mode coding.
 * \date   830916:  Original version.
 * \date   890104:  Documented/Reviewed
 */
void 
apcmsg(char *kalpha, 
       int   kalpha_s)
{
	int isave, nalpha, nchmax;
        char *s1;

	/* - Determine length of string without trailing blanks. */
	nalpha = indexb( kalpha,kalpha_s );

	/* - Decrease maximum length of first line of message to
	 *   allow room for a prefix to be added later when written. */

	nchmax = MCMSG;
	if( cmmsg.nlimsg == 1 )
	     nchmax = nchmax - 10;

	/* - Start new line of message if there is not enough room. */

	if( (cmmsg.nchmsg + nalpha + 1) > nchmax ){
	     if( cmmsg.nlimsg < MLIMSG ){
		cmmsg.nlimsg = cmmsg.nlimsg + 1;
	     }
	     else if( cmmsg.autoout ){
		outmsg();
		isave = cmmsg.itpmsg;
		clrmsg();
		cmmsg.itpmsg = isave;
	     }
	     else{
		fstrncpy( kmmsg.klimsg[cmmsg.nlimsg - 1], MCMSG, " ", 1 );
	     }
	     cmmsg.nchmsg = 0;
	}

	/* - Append alphanumeric string to current message line.
	 *   Include one trailing blank.  Update character counter. */


	if( nalpha > 0 ){
        s1 = strcut(kalpha, 1, nalpha);
	    subscpy( kmmsg.klimsg[cmmsg.nlimsg - 1], cmmsg.nchmsg,
		     cmmsg.nchmsg + nalpha + 1, MCMSG, s1);
        free(s1);
	}
	cmmsg.nchmsg = cmmsg.nchmsg + nalpha + 1;

	return;
}
示例#7
0
文件: semver.c 项目: fhunleth/fwup
int
semver_clean (char *s) {
  size_t i, len, mlen;
  int res;
  if (has_valid_length(s) == 0) return -1;

  len = strlen(s);
  mlen = strlen(VALID_CHARS);

  for (i = 0; i < len; i++) {
    if (contains(s[i], VALID_CHARS, mlen) == 0) {
      res = strcut(s, i, 1);
      if(res == -1) return -1;
      --len; --i;
    }
  }

  return 0;
}
示例#8
0
/** 
 * Read a vars list from disk to memory
 * 
 * @param fullvars 
 *     Full (absolute) name of the vars disk file
 * @param fullvars_s 
 *     Length of \p fullvars
 * @param node
 *     Output vars storage system node number
 * @param nerr 
 *     Error Return Flag
 *     - 0 on Success
 *     - Non-Zero on Error
 *
 * @date   890227:  Changed argument list.
 * @date   881115:  Added output of node number.
 * @date   880321:  Included logic to find and save nil index after read.
 * @date   870916:  Original version.
 * @date   870916:  Documented/Reviewed
 *
 */
void 
readvfile(char *fullvars, 
          int   fullvars_s, 
          int  *node, 
          int  *nerr) {

  char *s1;

	*nerr = 0;
	*node = 0;

  s1 = strcut(fullvars, 1, indexb(fullvars, fullvars_s));
  if((*nerr = sac_vars_read(s1))) {
    error(*nerr, "%s", s1);
  }
  free(s1);

  return;
}
示例#9
0
/*
 * Print gopher menu line
 */
void info(state *st, char *str, char type)
{
	char buf[BUFSIZE];
	char selector[16];

	/* Convert string to output charset */
	if (st->opt_iconv) sstrniconv(st->out_charset, buf, str);
	else sstrlcpy(buf, str);

	/* Handle gopher title resources */
	strclear(selector);
	if (type == TYPE_TITLE) {
		sstrlcpy(selector, "TITLE");
		type = TYPE_INFO;
	}

	/* Output info line */
	strcut(buf, st->out_width);
	printf("%c%s\t%s\t%s" CRLF,
		type, buf, selector, DUMMY_HOST);
}
示例#10
0
/////////////////////////////////////////////////////////////////////////////////////
// Print out full alignment in HHR format
/////////////////////////////////////////////////////////////////////////////////////
void FullAlignment::PrintHHR(std::stringstream& out, Hit& hit, const char showconf, const char showcons, const char showdssp, const char showpred, const int aliwidth, const int maxseq) {
  const int NLEN = 14;  //Length of name field in front of multiple alignment
  int h = 0;    //counts position (column) in alignment
  int hh = 0;   //points to column at start of present output block of alignment
  int k;      //counts sequences in query and template 
  short unsigned int* lq = new short unsigned int[maxseq]; // lq[k] counts index of residue from query sequence k to be printed next;
  short unsigned int* lt = new short unsigned int[maxseq]; // lt[k] counts index of residue from template sequence k to be printed next;
  char namestr[NAMELEN]; //name of sequence
  int iq = hit.i1; // match state counter for query HMM (displayed in consensus line)
  int jt = hit.j1; // match state counter for template HMM (displayed in consensus line)

  for (k = 0; k < qa->n; k++)
    lq[k] = qa->l[k][hit.i1];
  for (k = 0; k < ta->n; k++)
    lt[k] = ta->l[k][hit.j1];
  
  char line[LINELEN];
  while (hh < ta->pos - 1) // print alignment block
  {
    // Print query secondary structure sequences
    for (k = 0; k < qa->n; k++) {
      if (!(k == qa->nss_dssp || k == qa->nsa_dssp || k == qa->nss_pred || k == qa->nss_conf))
        continue;
      if (k == qa->nsa_dssp)
        continue;
      if (k == qa->nss_dssp && !showdssp)
        continue;
      if ((k == qa->nss_pred || k == qa->nss_conf) && !showpred)
        continue;
      if (k == qa->nss_conf && !showconf)
        continue;
      strmcpy(namestr, qa->sname[k], NAMELEN - 1);
      strcut(namestr);
      sprintf(line, "Q %-*.*s      ", NLEN, NLEN, namestr);
      out << line;

      if (k == qa->nss_pred && qa->nss_conf >= 0)
        for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) {
          sprintf(line, "%1c",
              qa->s[qa->nss_conf][h] <= '6' && qa->s[qa->nss_conf][h] >= '0' ?
                  qa->s[k][h] + 32 : qa->s[k][h]);
          out << line;
        }
      else
        for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) {
          sprintf(line, "%1c", qa->s[k][h]);
          out << line;
        }
      out << std::endl;
    }

    // Print query sequences
    for (k = 0; k < qa->n; k++) {
      if (k == qa->nss_dssp || k == qa->nsa_dssp || k == qa->nss_pred
          || k == qa->nss_conf || k == qa->ncons)
        continue;
      strmcpy(namestr, qa->sname[k], NAMELEN - 1);
      strcut(namestr);
      sprintf(line, "Q %-*.*s %4i ", NLEN, NLEN, namestr, lq[k]);
      out << line;
      for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) {
        sprintf(line, "%1c", qa->s[k][h]);
        out << line;
        lq[k] += WordChr(qa->s[k][h]);
      }  //WordChr() returns 1 if a-z or A-Z; 0 otherwise
      sprintf(line, " %4i (%i)\n", lq[k] - 1, qa->l[k][qa->L + 1]);
      out << line;
    }

    // Print query consensus sequence
    if (showcons && qa->ncons >= 0) {
      k = qa->ncons;
      strmcpy(namestr, qa->sname[k], NAMELEN - 1);
      strcut(namestr);
      sprintf(line, "Q %-*.*s %4i ", NLEN, NLEN, namestr, iq);
      out << line;
      for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) {
        if (qa->s[k][h] == 'x')
          qa->s[k][h] = '~';
        if (qa->s[k][h] != '-' && qa->s[k][h] != '.')
          iq++;
        sprintf(line, "%1c", qa->s[k][h]);
        out << line;
      }
      sprintf(line, " %4i (%i)\n", iq - 1, qa->L);
      out << line;
    }

    // Print symbols representing the score
    sprintf(line, "  %*.*s      ", NLEN, NLEN, " ");
    out << line;
    for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) {
      sprintf(line, "%1c", symbol[h]);
      out << line;
    }
    out << std::endl;

    // Print template consensus sequence
    if (showcons && ta->ncons >= 0) {
      k = ta->ncons;
      strmcpy(namestr, ta->sname[k], NAMELEN - 1);
      strcut(namestr);
      sprintf(line, "T %-*.*s %4i ", NLEN, NLEN, namestr, jt);
      out << line;
      for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) {
        if (ta->s[k][h] == 'x')
          ta->s[k][h] = '~';
        if (ta->s[k][h] != '-' && ta->s[k][h] != '.')
          jt++;
        sprintf(line, "%1c", ta->s[k][h]);
        out << line;
      }
      sprintf(line, " %4i (%i)\n", jt - 1, ta->L);
      out << line;
    }
    // Print template sequences
    for (k = 0; k < ta->n; k++) {
      if (k == ta->nss_dssp || k == ta->nsa_dssp || k == ta->nss_pred
          || k == ta->nss_conf || k == ta->ncons)
        continue;
      strmcpy(namestr, ta->sname[k], NAMELEN - 1);
      strcut(namestr);
      sprintf(line, "T %-*.*s %4i ", NLEN, NLEN, namestr, lt[k]);
      out << line;
      for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) {
        sprintf(line, "%1c", ta->s[k][h]);
        out << line;
        lt[k] += WordChr(ta->s[k][h]);
      }  //WordChr() returns 1 if a-z or A-Z; 0 otherwise
      sprintf(line, " %4i (%i)\n", lt[k] - 1, ta->l[k][ta->L + 1]);
      out << line;
    }

    // Print template secondary structure sequences
    for (k = 0; k < ta->n; k++) {
      if (!(k == ta->nss_dssp || k == ta->nss_pred || k == ta->nss_conf))
        continue;
      if (k == ta->nsa_dssp)
        continue;
      if (k == ta->nss_dssp && !showdssp)
        continue;
      if ((k == ta->nss_pred || k == ta->nss_conf) && !showpred)
        continue;
      if (k == ta->nss_conf && !showconf)
        continue;
      strmcpy(namestr, ta->sname[k], NAMELEN - 1);
      strcut(namestr);
      sprintf(line, "T %-*.*s      ", NLEN, NLEN, namestr);
      out << line;
      if (k == ta->nss_pred && ta->nss_conf >= 0)
        for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) {
          sprintf(line, "%1c",
              ta->s[ta->nss_conf][h] <= '6' && ta->s[ta->nss_conf][h] >= '0' ?
                  ta->s[k][h] + 32 : ta->s[k][h]);
          out << line;
        }
      else
        for (h = hh; h < imin(hh + aliwidth, ta->pos - 1); h++) {
          sprintf(line, "%1c", ta->s[k][h]);
          out << line;
        }
      out << std::endl;
    }

    // Print alignment confidence values (posterior probabilities)?
    if (posterior[0] != '\0') {
      sprintf(line, "%-*.*s        ", NLEN, NLEN,
          "Confidence                     ");
      out << line;
      for (h = hh; h < imin(hh + aliwidth, qa->pos - 1); h++) {
        sprintf(line, "%1c", posterior[h]);
        out << line;
      }
      out << std::endl;
    }
    hh = h;
    out << std::endl << std::endl;
  }
  delete [] lq;
  delete [] lt;
}
示例#11
0
/* laden von EPHEM VERSION 4.0 Bahnelementdateien */
short elemente_laden( const char datei_name[], ELEMENT& e )
{
   FILE *f;
   int dummy;
   char string[100],a_string[20];

   f=fopen(datei_name,"rt");
   if (f==NULL)
   {
      fprintf(stderr,"Kann Datei %s nicht oeffnen!\n",datei_name);
      return 0;
   }
   fgets(string,100,f);
   if (strcmp("EPHEM4\n",string)!=0) // keine EPHEM 4.0 Bahnelementdatei
   {
      fclose(f);
      fprintf(stderr,"Die Datei %s ist keine EPHEM 4.x Bahnelementedatei.\n",datei_name);
      return 0;
   }

   fgets(string,100,f);
   sscanf(string,"%d",&dummy);
   e.komet=AUS_EIN(dummy % 2);
   fgets(string,100,f);
   strcut(string);
   string[strlen(string)-1]=0; /* '\n' rauswerfen */
   strcut(string);
   strcpy(e.name,string);
   fgets(string,100,f);
   sscanf(string,"%s",a_string);
   strdel(a_string,string);
   if (strcmp("des_datums",string)==0)
   {
      e.a_jd=0.0;
      e.a_mo=des_datums;
   }
   else if (strcmp("j2000",string)==0)
   {
      e.a_jd=J2000;
      e.a_mo=j2000;
   }
   else if (strcmp("b1950",string)==0)
   {
      e.a_jd=B1950;
      e.a_mo=b1950;
   }
   else
   {
      sscanf(string,"%lg",&e.a_jd);
      e.a_mo=anderes;
   }
   fgets(string,100,f); sscanf(string,"%lg",&e.e);
   fgets(string,100,f); sscanf(string,"%lg",&e.q);
   fgets(string,100,f); sscanf(string,"%lg",&e.M);
   fgets(string,100,f); sscanf(string,"%lg",&e.t);
   fgets(string,100,f); sscanf(string,"%lg",&e.om);
   fgets(string,100,f); sscanf(string,"%lg",&e.kl);
   fgets(string,100,f); sscanf(string,"%lg",&e.i);
   fgets(string,100,f); sscanf(string,"%lg",&e.mag0);
   fgets(string,100,f); sscanf(string,"%lg",&e.mag1);

   if (e.e<1.0)       /* Elliptische Bahn */
   {
      e.a=e.q/(1.0-e.e);
      e.n=M_2PI/sqrt(e.a*e.a*e.a*4.0*PI*PI/KGAUSS2);
   }
   else if (e.e>1.0)  /* Hyperbolische Bahn */
   {
      e.a=e.q/(1.0-e.e);
   }
   if (e.M==0.0)
      e.t0=e.t;

   e.M  *= DEG2RAD;
   e.om *= DEG2RAD;
   e.kl *= DEG2RAD;
   e.i  *= DEG2RAD;
   e.pi=mod(e.om+e.kl,M_2PI);

   fclose(f);

   return 1;
}
示例#12
0
文件: dovecot.c 项目: fanf2/exim
int auth_dovecot_server(auth_instance *ablock, uschar *data)
{
       auth_dovecot_options_block *ob =
               (auth_dovecot_options_block *)(ablock->options_block);
       struct sockaddr_un sa;
       uschar buffer[4096];
       uschar *args[8];
       uschar *auth_command;
       uschar *auth_extra_data = US"";
       int nargs, tmp;
       int cuid = 0, cont = 1, found = 0, fd, ret = DEFER;

       HDEBUG(D_auth) debug_printf("dovecot authentication\n");

       memset(&sa, 0, sizeof(sa));
       sa.sun_family = AF_UNIX;

       /* This was the original code here: it is nonsense because strncpy()
       does not return an integer. I have converted this to use the function
       that formats and checks length. PH */

       /*
       if (strncpy(sa.sun_path, ob->server_socket, sizeof(sa.sun_path)) < 0) {
       */

       if (!string_format(US sa.sun_path, sizeof(sa.sun_path), "%s",
                          ob->server_socket)) {
               auth_defer_msg = US"authentication socket path too long";
               return DEFER;
       }

       auth_defer_msg = US"authentication socket connection error";

       fd = socket(PF_UNIX, SOCK_STREAM, 0);
       if (fd < 0)
               return DEFER;

       if (connect(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
               goto out;

       auth_defer_msg = US"authentication socket protocol error";

       sbp = 0;  /* Socket buffer pointer */
       while (cont) {
               if (dc_gets(buffer, sizeof(buffer), fd) == NULL)
                       OUT("authentication socket read error or premature eof");

               buffer[Ustrlen(buffer) - 1] = 0;
               HDEBUG(D_auth) debug_printf("received: %s\n", buffer);
               nargs = strcut(buffer, args, sizeof(args) / sizeof(args[0]));

               /* Code below rewritten by Kirill Miazine ([email protected]). Only check commands that
                  Exim will need. Original code also failed if Dovecot server sent unknown
                  command. E.g. COOKIE in version 1.1 of the protocol would cause troubles. */
               if (Ustrcmp(args[0], US"CUID") == 0) {
                       CHECK_COMMAND("CUID", 1, 1);
                       cuid = Uatoi(args[1]);
               } else if (Ustrcmp(args[0], US"VERSION") == 0) {
                       CHECK_COMMAND("VERSION", 2, 2);
                       if (Uatoi(args[1]) != VERSION_MAJOR)
                               OUT("authentication socket protocol version mismatch");
               } else if (Ustrcmp(args[0], US"MECH") == 0) {
                       CHECK_COMMAND("MECH", 1, INT_MAX);
                       if (strcmpic(US args[1], ablock->public_name) == 0)
                               found = 1;
               } else if (Ustrcmp(args[0], US"DONE") == 0) {
                       CHECK_COMMAND("DONE", 0, 0);
                       cont = 0;
               }
       }

       if (!found)
               goto out;

       /* Added by PH: data must not contain tab (as it is
       b64 it shouldn't, but check for safety). */

       if (Ustrchr(data, '\t') != NULL) {
               ret = FAIL;
               goto out;
       }

       /* Added by PH: extra fields when TLS is in use or if the TCP/IP
       connection is local. */

       if (tls_cipher != NULL)
               auth_extra_data = string_sprintf("secured\t%s%s",
                   tls_certificate_verified? "valid-client-cert" : "",
                   tls_certificate_verified? "\t" : "");
       else if (interface_address != NULL &&
                Ustrcmp(sender_host_address, interface_address) == 0)
               auth_extra_data = US"secured\t";


/****************************************************************************
   The code below was the original code here. It didn't work. A reading of the
   file auth-protocol.txt.gz that came with Dovecot 1.0_beta8 indicated that
   this was not right. Maybe something changed. I changed it to move the
   service indication into the AUTH command, and it seems to be better. PH

       fprintf(f, "VERSION\t%d\t%d\r\nSERVICE\tSMTP\r\nCPID\t%d\r\n"
               "AUTH\t%d\t%s\trip=%s\tlip=%s\tresp=%s\r\n",
               VERSION_MAJOR, VERSION_MINOR, getpid(), cuid,
               ablock->public_name, sender_host_address, interface_address,
               data ? (char *) data : "");

   Subsequently, the command was modified to add "secured" and "valid-client-
   cert" when relevant.

   The auth protocol is documented here:
        http://wiki.dovecot.org/Authentication_Protocol
****************************************************************************/

       auth_command = string_sprintf("VERSION\t%d\t%d\nCPID\t%d\n"
               "AUTH\t%d\t%s\tservice=smtp\t%srip=%s\tlip=%s\tnologin\tresp=%s\n",
               VERSION_MAJOR, VERSION_MINOR, getpid(), cuid,
               ablock->public_name, auth_extra_data, sender_host_address,
               interface_address, data ? (char *) data : "");

       if (write(fd, auth_command, Ustrlen(auth_command)) < 0)
              HDEBUG(D_auth) debug_printf("error sending auth_command: %s\n",
                strerror(errno));

       HDEBUG(D_auth) debug_printf("sent: %s", auth_command);

       while (1) {
               uschar *temp;
               uschar *auth_id_pre = NULL;
               int i;

               if (dc_gets(buffer, sizeof(buffer), fd) == NULL) {
                       auth_defer_msg = US"authentication socket read error or premature eof";
                       goto out;
               }

               buffer[Ustrlen(buffer) - 1] = 0;
               HDEBUG(D_auth) debug_printf("received: %s\n", buffer);
               nargs = strcut(buffer, args, sizeof(args) / sizeof(args[0]));

               if (Uatoi(args[1]) != cuid)
                       OUT("authentication socket connection id mismatch");

               switch (toupper(*args[0])) {
               case 'C':
                       CHECK_COMMAND("CONT", 1, 2);

                       tmp = auth_get_no64_data(&data, US args[2]);
                       if (tmp != OK) {
                               ret = tmp;
                               goto out;
                       }

                       /* Added by PH: data must not contain tab (as it is
                       b64 it shouldn't, but check for safety). */

                       if (Ustrchr(data, '\t') != NULL) {
                               ret = FAIL;
                               goto out;
                       }

                       temp = string_sprintf("CONT\t%d\t%s\n", cuid, data);
                       if (write(fd, temp, Ustrlen(temp)) < 0)
                               OUT("authentication socket write error");
                       break;

               case 'F':
                       CHECK_COMMAND("FAIL", 1, -1);

                       for (i=2; (i<nargs) && (auth_id_pre == NULL); i++)
                       {
                               if ( Ustrncmp(args[i], US"user="******"OK", 2, -1);

                       /*
                        * Search for the "user=$USER" string in the args array
                        * and return the proper value.
                        */
                       for (i=2; (i<nargs) && (auth_id_pre == NULL); i++)
                       {
                               if ( Ustrncmp(args[i], US"user="******"authentication socket protocol error, username missing");

                       ret = OK;
                       /* fallthrough */

               default:
                       goto out;
               }
       }

out:
       /* close the socket used by dovecot */
       if (fd >= 0)
              close(fd);

       /* Expand server_condition as an authorization check */
       return (ret == OK)? auth_check_serv_cond(ablock) : ret;
}
示例#13
0
文件: dovecot.c 项目: Exim/exim
int
auth_dovecot_server(auth_instance * ablock, uschar * data)
{
auth_dovecot_options_block *ob =
       (auth_dovecot_options_block *) ablock->options_block;
struct sockaddr_un sa;
uschar buffer[DOVECOT_AUTH_MAXLINELEN];
uschar *args[DOVECOT_AUTH_MAXFIELDCOUNT];
uschar *auth_command;
uschar *auth_extra_data = US"";
uschar *p;
int nargs, tmp;
int crequid = 1, cont = 1, fd = -1, ret = DEFER;
BOOL found = FALSE, have_mech_line = FALSE;

HDEBUG(D_auth) debug_printf("dovecot authentication\n");

if (!data)
  {
  ret = FAIL;
  goto out;
  }

memset(&sa, 0, sizeof(sa));
sa.sun_family = AF_UNIX;

/* This was the original code here: it is nonsense because strncpy()
does not return an integer. I have converted this to use the function
that formats and checks length. PH */

/*
if (strncpy(sa.sun_path, ob->server_socket, sizeof(sa.sun_path)) < 0) {
}
*/

if (!string_format(US sa.sun_path, sizeof(sa.sun_path), "%s",
		  ob->server_socket))
  {
  auth_defer_msg = US"authentication socket path too long";
  return DEFER;
  }

auth_defer_msg = US"authentication socket connection error";

if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
  return DEFER;

if (connect(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
  goto out;

auth_defer_msg = US"authentication socket protocol error";

socket_buffer_left = 0;  /* Global, used to read more than a line but return by line */
while (cont)
  {
  if (dc_gets(buffer, sizeof(buffer), fd) == NULL)
    OUT("authentication socket read error or premature eof");
  p = buffer + Ustrlen(buffer) - 1;
  if (*p != '\n')
    OUT("authentication socket protocol line too long");

  *p = '\0';
  HDEBUG(D_auth) debug_printf("received: %s\n", buffer);

  nargs = strcut(buffer, args, sizeof(args) / sizeof(args[0]));

  /* HDEBUG(D_auth) debug_strcut(args, nargs, sizeof(args) / sizeof(args[0])); */

  /* Code below rewritten by Kirill Miazine ([email protected]). Only check commands that
    Exim will need. Original code also failed if Dovecot server sent unknown
    command. E.g. COOKIE in version 1.1 of the protocol would cause troubles. */
  /* pdp: note that CUID is a per-connection identifier sent by the server,
    which increments at server discretion.
    By contrast, the "id" field of the protocol is a connection-specific request
    identifier, which needs to be unique per request from the client and is not
    connected to the CUID value, so we ignore CUID from server.  It's purely for
    diagnostics. */

  if (Ustrcmp(args[0], US"VERSION") == 0)
    {
    CHECK_COMMAND("VERSION", 2, 2);
    if (Uatoi(args[1]) != VERSION_MAJOR)
      OUT("authentication socket protocol version mismatch");
    }
  else if (Ustrcmp(args[0], US"MECH") == 0)
    {
    CHECK_COMMAND("MECH", 1, INT_MAX);
    have_mech_line = TRUE;
    if (strcmpic(US args[1], ablock->public_name) == 0)
      found = TRUE;
    }
  else if (Ustrcmp(args[0], US"SPID") == 0)
    {
    /* Unfortunately the auth protocol handshake wasn't designed well
    to differentiate between auth-client/userdb/master. auth-userdb
    and auth-master send VERSION + SPID lines only and nothing
    afterwards, while auth-client sends VERSION + MECH + SPID +
    CUID + more. The simplest way that we can determine if we've
    connected to the correct socket is to see if MECH line exists or
    not (alternatively we'd have to have a small timeout after SPID
    to see if CUID is sent or not). */

    if (!have_mech_line)
      OUT("authentication socket type mismatch"
	" (connected to auth-master instead of auth-client)");
    }
  else if (Ustrcmp(args[0], US"DONE") == 0)
    {
    CHECK_COMMAND("DONE", 0, 0);
    cont = 0;
    }
  }

if (!found)
  {
  auth_defer_msg = string_sprintf(
    "Dovecot did not advertise mechanism \"%s\" to us", ablock->public_name);
  goto out;
  }

/* Added by PH: data must not contain tab (as it is
b64 it shouldn't, but check for safety). */

if (Ustrchr(data, '\t') != NULL)
  {
  ret = FAIL;
  goto out;
  }

/* Added by PH: extra fields when TLS is in use or if the TCP/IP
connection is local. */

if (tls_in.cipher != NULL)
  auth_extra_data = string_sprintf("secured\t%s%s",
     tls_in.certificate_verified? "valid-client-cert" : "",
     tls_in.certificate_verified? "\t" : "");

else if (  interface_address != NULL
        && Ustrcmp(sender_host_address, interface_address) == 0)
  auth_extra_data = US"secured\t";


/****************************************************************************
The code below was the original code here. It didn't work. A reading of the
file auth-protocol.txt.gz that came with Dovecot 1.0_beta8 indicated that
this was not right. Maybe something changed. I changed it to move the
service indication into the AUTH command, and it seems to be better. PH

fprintf(f, "VERSION\t%d\t%d\r\nSERVICE\tSMTP\r\nCPID\t%d\r\n"
       "AUTH\t%d\t%s\trip=%s\tlip=%s\tresp=%s\r\n",
       VERSION_MAJOR, VERSION_MINOR, getpid(), cuid,
       ablock->public_name, sender_host_address, interface_address,
       data ? CS  data : "");

Subsequently, the command was modified to add "secured" and "valid-client-
cert" when relevant.
****************************************************************************/

auth_command = string_sprintf("VERSION\t%d\t%d\nCPID\t%d\n"
       "AUTH\t%d\t%s\tservice=smtp\t%srip=%s\tlip=%s\tnologin\tresp=%s\n",
       VERSION_MAJOR, VERSION_MINOR, getpid(), crequid,
       ablock->public_name, auth_extra_data, sender_host_address,
       interface_address, data);

if (write(fd, auth_command, Ustrlen(auth_command)) < 0)
  HDEBUG(D_auth) debug_printf("error sending auth_command: %s\n",
    strerror(errno));

HDEBUG(D_auth) debug_printf("sent: %s", auth_command);

while (1)
  {
  uschar *temp;
  uschar *auth_id_pre = NULL;
  int i;

  if (dc_gets(buffer, sizeof(buffer), fd) == NULL)
    {
    auth_defer_msg = US"authentication socket read error or premature eof";
    goto out;
    }

  buffer[Ustrlen(buffer) - 1] = 0;
  HDEBUG(D_auth) debug_printf("received: %s\n", buffer);
  nargs = strcut(buffer, args, sizeof(args) / sizeof(args[0]));

  if (Uatoi(args[1]) != crequid)
    OUT("authentication socket connection id mismatch");

  switch (toupper(*args[0]))
    {
    case 'C':
      CHECK_COMMAND("CONT", 1, 2);

      if ((tmp = auth_get_no64_data(&data, US args[2])) != OK)
	{
	ret = tmp;
	goto out;
	}

      /* Added by PH: data must not contain tab (as it is
      b64 it shouldn't, but check for safety). */

      if (Ustrchr(data, '\t') != NULL)
        {
	ret = FAIL;
	goto out;
	}

      temp = string_sprintf("CONT\t%d\t%s\n", crequid, data);
      if (write(fd, temp, Ustrlen(temp)) < 0)
	OUT("authentication socket write error");
      break;

    case 'F':
      CHECK_COMMAND("FAIL", 1, -1);

      for (i=2; (i<nargs) && (auth_id_pre == NULL); i++)
	{
	if ( Ustrncmp(args[i], US"user="******"OK", 2, -1);

      /* Search for the "user=$USER" string in the args array
      and return the proper value.  */

      for (i=2; (i<nargs) && (auth_id_pre == NULL); i++)
	{
	if ( Ustrncmp(args[i], US"user="******"authentication socket protocol error, username missing");

      ret = OK;
      /* fallthrough */

    default:
      goto out;
    }
  }

out:
/* close the socket used by dovecot */
if (fd >= 0)
  close(fd);

/* Expand server_condition as an authorization check */
return ret == OK ? auth_check_serv_cond(ablock) : ret;
}
void zen_prompt(int argc, char *argv[])
{
    zen_openlibs();
    #ifdef __WIN32__ || _WIN64 || _WIN32 || __TOS_WIN__ || __WINDOWS__ || _WIN32_WCE || WIN32_PLATFORM_'P'
        HRSRC hResource;
        HGLOBAL hResourceLoaded;
        HMODULE hLibrary;
    #endif
    char* lpBuffer;
    char buffer[10240] = {0};
    size_t size;
    char* pos;
    int x;
    if (argc <= 1)
    {
        #ifdef __WIN32__ || _WIN64 || _WIN32 || __TOS_WIN__ || __WINDOWS__ || _WIN32_WCE || WIN32_PLATFORM_'P'
        hLibrary = GetModuleHandle(NULL);
        hResource = FindResource(hLibrary,
                                 MAKEINTRESOURCE(ZEN_START_RESOURCE_INDEX), RT_RCDATA);
        if (NULL != hResource)	/* stand-alone executable */
        {
            hResourceLoaded = LoadResource(hLibrary, hResource);
            if (NULL != hResourceLoaded)
            {
                lpBuffer = (char*)LockResource(hResourceLoaded);
                if (NULL != lpBuffer)
                {
                    size = SizeofResource(hLibrary, hResource);
                    memcpy(buffer, lpBuffer, size);
                    zen_runstring("(msg)", buffer);
                }
            }
        }
        else	/* interactive mode */
        #endif
        {
            printf(ZEN_CON_HEADER, ZEN_VERSION, system_getname(0));
            int keep = 1;
            while (keep)
            {
                #ifndef __WIN32__ || _WIN64 || _WIN32 || __TOS_WIN__ || __WINDOWS__ || _WIN32_WCE || WIN32_PLATFORM_'P'
                    #include <sys/utsname.h>
                    struct utsname name;
                    uname(&name);
                    printf(CON_CURSOR, getenv("USER"), name.nodename);
                #endif
                fgets(buffer, 1024, stdin);
                strcut(buffer, " \t\n\r");
                // sys cmds
                if ((pos=strstr(buffer, ".run")) == buffer)
                {
                    pos += strlen(".run")+1;
                    zen_runfile(pos);
                }
                else if ((pos=strstr(buffer, ".debug")) == buffer)
                {
                    pos += strlen(".debug")+1;
                    zen_debugfile(pos);
                }

                else if (strcmp(buffer, ".exit") == 0)
                    keep = 0;

                else if (strcmp(buffer, ".help") == 0)
                    printf(ZEN_CON_HELP);

                else if (strcmp(buffer, ".license") == 0)
				    printf(ZEN_CON_LICENSE);
/*
                else if (strcmp(buffer, "list all") == 0)
                    printdir(directory_getcurrent());

                else if ((pos=strstr(buffer, "cd")) == buffer)
                {
                    pos += strlen("cd")+1;
                    set_curdir(pos);
                }

                else if ((pos=strstr(buffer, "makedir")) == buffer)
                {
                    pos += strlen("makedir")+1;
                    if(!make_dir(pos))
                       printf("Unable to create directory.\n");
                }

                else if ((pos=strstr(buffer, "remdir")) == buffer)
                {
                    pos += strlen("remdir")+1;
                    if(!remove_dir(pos))
                       printf("Unable to remove directory.\n");
                }

                else if (strcmp(buffer, "dir usage") == 0)
                {
                    if(! (x = dir_usage(get_curdir(), 0)))
                        printf("Unable to get directory's usage.\n");
                    else
                        printf("%d\n", x);

                }

                else if (strcmp(buffer, "dir usage all") == 0)
                {
                    if(! (x = dir_usage(get_curdir(), 1)))
                        printf("Unable to get directory's usage.\n");
                    else
                        printf("%d\n", x);
                }

                else if (strcmp(buffer, "dir files") == 0)
                {
                    if(! (x = dir_files(get_curdir(),  0)))
                        printf("Unable to get directory's files count.\n");
                    else
                        printf("%d\n", x);
                }

                else if (strcmp(buffer, "dir files all") == 0)
                {
                    if(! (x = dir_files(get_curdir(), 1)))
                        printf("Unable to get directory's files count.\n");
                    else
                        printf("%d\n", x);
                }

                else if ((pos=strstr(buffer, "file info")) == buffer)
                {
                    pos += strlen("file info")+1;
                    print_fileinfo(pos);
                }
*/
                else if (strlen(buffer) > 0)
                    zen_runstring("(CONSOLE)", buffer);
                printf("\n");
            }
        }
        #ifdef __WIN32__ || _WIN64 || _WIN32 || __TOS_WIN__ || __WINDOWS__ || _WIN32_WCE || WIN32_PLATFORM_'P'
        FreeLibrary(hLibrary);
        #endif
    }
    else	/* command-line mode */
        zen_runfile(argv[1]);
    zen_closelibs();
}
示例#15
0
/** 
 * Execute the getbb command which gets the blackboard variables
 * 
 * @param nerr 
 *    Error Return Flag
 *    - 0 on Success
 *
 * @date   890104:  Changed from terminal output to message subsystem.
 * @date   880901:  Added TO, NAMES, and NEWLINE options.
 * @date   870917:  Added ALL option.
 * @date   870514:  Original version.
 *
 */
void 
xgetbb(int *nerr) {

	char kbbvalue[MCMSG+1];
	int ic1, ic2, nc, ncbb ;
  var *v;
  char *name;

	*nerr = 0;

    memset(kmexm.knmbbwrite,0, sizeof(kmexm.knmbbwrite));
    memset(kbbvalue, 0, sizeof(kbbvalue));

	while ( lcmore( nerr ) ){

	    /* -- "ALL": report all of the currently defined blackboard variables. */
    if( lckey( "ALL#$",6 ) ){
      cmexm.lbball = TRUE;
    }
    
    /* -- "TO TERMINAL|filename": define where the output is to be sent. */
    else if( lckey( "TO#$",5 ) ){
      if( lckey( "TERM#INAL$",11 ) ){
		    cmexm.nunbbwrite = MUNOUT;
      }
      else if( lcchar( MCPFN, kmexm.knmbbwrite,MCPFN+1, &nc ) ){
		    cmexm.nunbbwrite = (FILE *)NULL;
		    if( *nerr != 0 )
          goto L_8888;
      }
      else{
		    cfmt( "ILLEGAL OPTION:",17 );
		    cresp();
      }
    }
    
	    /* -- "NAMES ON|OFF": option to include the
         bb variable name with the value. */
    else if( lklog( "NAMES#$",8, &cmexm.lnames ) ) { }
    
	    /* -- "NEWLINE ON|OFF": option to append newline
         after each bb variable value. */
    else if( lklog( "NEWLINE#$",10, &cmexm.lnewline ) ) { }
    
    /* -- The rest of the tokens should be names of a blackboard variables.
     *    First unset ALL flag and initialize list of bb variables.
     *    Then set up an inner parsing loop to collect all of the 
     *    variable names. */
    else{
      cmexm.lbball = FALSE;
      memset ( kmexm.kbbcl , ' ' , MCMSG );
      
      if(!lccl(kmexm.kbbcl, MCMSG+1, &ncbb)) {
        cfmt( "ILLEGAL OPTION:",17 );
        cresp();
      }
    }
	} /* end while */

	/* - The above loop is over when one of two conditions has been met:
	 *   (1) An error in parsing has occurred.  In this case NERR is > 0 .
	 *   (2) All the tokens in the command have been successfully parsed. */

	if( *nerr != 0 )
		goto L_8888;

	/* EXECUTION PHASE: */

	/* - Open disk file if necessary. */

	if( cmexm.nunbbwrite != MUNOUT ){
    znfiles( &cmexm.nunbbwrite, kmexm.knmbbwrite,MCPFN+1, "TEXT",5,  nerr );
    if( *nerr != 0 )
      goto L_8888;
    if ( fseek ( cmexm.nunbbwrite , 0L , SEEK_END ) != 0 )
      fprintf ( stdout , "fseek returned error-xgetbb\n" ) ;
	}

	/* - Sequentially access blackboard if ALL was requested. */

	setmsg( "OUTPUT", 99 );
	if( cmexm.lbball ){
    int i = 0;
    char **keys = sac_vars_keys(kmbbs.knmbbs);
    while(keys && keys[i]) { i++; }
    if(i > 0) {
      qsort(keys, i, sizeof(char*), string_cmp);
      i = 0;
      while ( keys && keys[i] ){
        if(!(v = sac_vars_get_var(kmbbs.knmbbs, keys[i]))) {
          error(ERROR_FINDING_VARIABLE, "%s", keys[i]);
          outmsg();
          clrmsg();
          i++;
          continue;
        }
        show_var(v, keys[i], cmexm.nunbbwrite);
        i++;
      }
      if( !cmexm.lnewline ) {
        newline( cmexm.nunbbwrite );
      }
      i = 0;
      while(keys && keys[i]) {
        FREE(keys[i]);
        i++;
      }
      FREE(keys);
    }
	}

	/* - Otherwise, get value for each item in request list. */
	else {
    ic1 = 0;    
    while ( lnxtcl( kmexm.kbbcl,MCMSG+1, &ic1, &ic2 ) ){
      name = strcut(kmexm.kbbcl, ic1, ic2);
      if(!(v = getbb(name))) {
        error(ERROR_FINDING_VARIABLE, "%s", name);
        outmsg();
        clrmsg();
        continue;
      }
      show_var(v, name, cmexm.nunbbwrite);
      free(name);
    }
    if( !cmexm.lnewline ) {
      newline( cmexm.nunbbwrite );
    }
	}

	clrmsg();
	if( cmexm.nunbbwrite != MUNOUT ){
	    zcloses( &cmexm.nunbbwrite, nerr );
	    if( *nerr != 0 )
		goto L_8888;
	}

L_8888:
	return;

} /* end of function */
示例#16
0
void doc::Response()
{
	string strExtName;
	string strResourceFullPath;
	string strResource;
	
	long long nResourceLength = 0;
	long long nRangeLength = 0;
    unsigned char szETag[33];
    time_t tLastModifyTime;
    
    string strContentRangeResponse;
    vector<HTTP_CONTENT_RANGE> content_ranges;
    const char* szHttpRequestRanges = NULL;
    int x = 0;
    bool flag = false;
    string strRange;
    
    char* file_cache_buf = NULL;
    char* file_buf = NULL;
    char szQETagQ[FILE_ETAG_LEN + 2 + 1];
    string strDateTime;    
        
	strResourceFullPath = m_session->GetResource();
    
    strResourceFullPath = m_work_path.c_str();
    strResourceFullPath += "/html/";
    strResourceFullPath += m_session->GetResource();
    
    CACHE_DATA* file_cache_data = NULL;
    file_cache* file_cache_instance = NULL;
    
    bool file_cache_available = false;
    m_session->m_cache->rdlock_cache();
    if(m_session->m_cache->_find_file_(strResourceFullPath.c_str(), &file_cache_instance)
        && file_cache_instance)
    {
        file_cache_data = file_cache_instance->file_rdlock();
    }
    
    m_session->m_cache->unlock_cache();
    
    if(file_cache_instance && file_cache_data)
    {
        time_t cache_time_out = time(NULL) - file_cache_data->t_create;
        //10s timeout
        if(cache_time_out < 10 && cache_time_out > 0)
        {
            file_cache_available = true;
        }
        else
        {
            //90s timeout
            if(get_file_length_lastmidifytime(strResourceFullPath.c_str(), nResourceLength, tLastModifyTime) == true
                && tLastModifyTime == file_cache_data->t_modify && cache_time_out < 90 && cache_time_out > 0)
            {
                file_cache_available = true;
            }
            else
            {
                file_cache_instance->file_unlock();
                file_cache_data = NULL;
                file_cache_instance = NULL;
                file_cache_available = false;
            }
        }
    }
    
    if(!file_cache_available)
    {
        struct stat info;
        stat(strResourceFullPath.c_str(), &info);
        if(S_ISDIR(info.st_mode)) /* Forbidden to access directory directly */
        {
            CHttpResponseHdr header;
            header.SetStatusCode(SC404);
            header.SetField("Content-Type", "text/html");
            header.SetField("Content-Length", header.GetDefaultHTMLLength());
            
            m_session->SendHeader(header.Text(), header.Length());
            m_session->SendContent(header.GetDefaultHTML(), header.GetDefaultHTMLLength());
            goto END_STEP1;
        }
        
        if(get_file_length_lastmidifytime(strResourceFullPath.c_str(), nResourceLength, tLastModifyTime) == false)
        {
            /* No such file */
            CHttpResponseHdr header;
            header.SetStatusCode(SC404);
            header.SetField("Content-Type", "text/html");
            header.SetField("Content-Length", header.GetDefaultHTMLLength());
            
            m_session->SendHeader(header.Text(), header.Length());
            m_session->SendContent(header.GetDefaultHTML(), header.GetDefaultHTMLLength());
            goto END_STEP1;
        }
    }
    else
    {
        nResourceLength = file_cache_data->len;
        tLastModifyTime = file_cache_data->t_modify;
    }

    OutHTTPDateString(tLastModifyTime, strDateTime);
    
    if(strcmp(m_session->GetRequestField("Cache-Control"), "no-cache") != 0
        && strcmp(m_session->GetRequestField("Pragma"), "no-cache") != 0
        && strcmp(m_session->GetRequestField("If-Modified-Since"), "") != 0 
        && strcmp(m_session->GetRequestField("If-Modified-Since"), strDateTime.c_str()) == 0)
    {
        /* No such file */
        CHttpResponseHdr header;
        header.SetStatusCode(SC304);
        unsigned int zero = 0;
        header.SetField("Content-Length", zero);    
        m_session->SendHeader(header.Text(), header.Length());
        goto END_STEP1;
    }
    else
    {
    
        if(file_cache_available)
        {
            file_cache_buf = file_cache_data->buf;
            memcpy(szETag, file_cache_data->etag, FILE_ETAG_LEN + 1);
        }
        else
        {
            if(nResourceLength <= FILE_MAX_SIZE)
                file_buf = new char[nResourceLength];
                
            if(get_file_etag(strResourceFullPath.c_str(), szETag, file_buf) == false)
            {
                if(file_buf)
                    delete[] file_buf;
                    
                CHttpResponseHdr header;
                header.SetStatusCode(SC404);
                header.SetField("Content-Type", "text/html");
                header.SetField("Content-Length", header.GetDefaultHTMLLength());
                
                m_session->SendHeader(header.Text(), header.Length());
                m_session->SendContent(header.GetDefaultHTML(), header.GetDefaultHTMLLength());
                goto END_STEP1;
            }
            
            if(file_buf)
            {
                m_session->m_cache->wrlock_cache();
                bool push_rc = m_session->m_cache->_push_file_(strResourceFullPath.c_str(),
                    file_buf, nResourceLength, tLastModifyTime, szETag,
                    &file_cache_instance);
                m_session->m_cache->unlock_cache();
                
                if(push_rc)
                {   
                    file_cache_data = file_cache_instance->file_rdlock();
                    
                    file_cache_buf = file_cache_data->buf;
                    file_cache_available = true;
                }
                                 
                delete[] file_buf;
            }
        }
        
        sprintf(szQETagQ, "\"%s\"", (char*)szETag);
    }
    
    if(strcmp(m_session->GetRequestField("Cache-Control"), "no-cache") != 0
        && strcmp(m_session->GetRequestField("Pragma"), "no-cache") != 0
        && strcmp(m_session->GetRequestField("If-None-Match"), "") != 0 
        && strcmp(m_session->GetRequestField("If-None-Match"), szQETagQ) == 0)
    {
        CHttpResponseHdr header;
        header.SetStatusCode(SC304);
        unsigned int zero = 0;
        header.SetField("Content-Length", zero);    
        m_session->SendHeader(header.Text(), header.Length()); 
        goto END_STEP1;                     
    }
    
    /* Parse ranges */
    szHttpRequestRanges = m_session->GetRequestField("Range");
    x = 0;
    flag = false;
    while(szHttpRequestRanges != NULL)
    {
        if(strcmp(szHttpRequestRanges, "") == 0)
        {
            nRangeLength = nResourceLength;
            break;
        }
        if(!flag)
        {
            if(szHttpRequestRanges[x] == '=' || szHttpRequestRanges[x] != '\0')
            {
                flag = true;
            }
            x++;
            continue;
        }
        if(szHttpRequestRanges[x] == ',' || szHttpRequestRanges[x] == '\0')
        {
            HTTP_CONTENT_RANGE ra;
            ra.beg = 0;
            ra.end = nResourceLength -1;
            
            string strbeg, strend;
            strcut(strRange.c_str(), NULL, "-", strbeg);
            strcut(strRange.c_str(), "-", NULL, strend);
            strtrim(strbeg);
            strtrim(strend);
            if(strbeg != "")
            {
               ra.beg = atoll(strbeg.c_str());
            }
            if(strend != "")
            {
               ra.end = atoll(strend.c_str());
            }
            if(ra.beg <= ra.end)
            {
                ra.len = ra.end - ra.beg + 1;
                
                char szTmp[1024];
                sprintf(szTmp, "%lld-%lld/%lld,", ra.beg, ra.end, ra.len);
                nRangeLength += ra.len;
                
                if(strContentRangeResponse == "")
                    strContentRangeResponse = "bytes ";
                strContentRangeResponse += szTmp;
                content_ranges.push_back(ra);
            }
            
            strRange = "";
        }
        else
            strRange += (szHttpRequestRanges[x]);
        
        if(szHttpRequestRanges[x] == '\0')
            break;
        x++;
    }
    
    lowercase(m_session->GetResource(), strResource);				
    get_extend_name(strResource.c_str(), strExtName);
    
    /* Has cache buff */
    if(file_cache_buf)
    {
        CHttpResponseHdr header;
        if(strcmp(szHttpRequestRanges, "") != 0 && strContentRangeResponse != "")
            header.SetStatusCode(SC206);
        else
            header.SetStatusCode(SC200);
        header.SetField("ETag", szQETagQ);
        header.SetField("Content-Length", nRangeLength);
        OutHTTPDateString(time(NULL) + 900, strDateTime);
        header.SetField("Expires", strDateTime.c_str());
        header.SetField("Cache-Control", "max-age=900");
        OutHTTPDateString(tLastModifyTime, strDateTime);
        header.SetField("Last-Modified", strDateTime.c_str());
        
        if(m_session->m_cache->m_type_table.find(strExtName) == m_session->m_cache->m_type_table.end())
        {
            header.SetField("Content-Type", "application/*");
        }
        else
        {
            header.SetField("Content-Type", m_session->m_cache->m_type_table[strExtName].c_str());
        }
        if(strcmp(szHttpRequestRanges, "") != 0 && strContentRangeResponse != "")
        {
            header.SetField("Content-Range", strContentRangeResponse.c_str());
        }
        
        m_session->SendHeader(header.Text(), header.Length());
        
        if(strcmp(szHttpRequestRanges, "") == 0)
        {
            if(m_session->GetMethod() != hmHead)
            {
                m_session->SendContent(file_cache_buf, nResourceLength);
            }
        }
        else
        {
            for(int v = 0; v < content_ranges.size(); v++)
            {
                if(m_session->GetMethod() != hmHead)
                {
                    int rest_length = nResourceLength - content_ranges[v].beg;
                    if(rest_length <= 0)
                        continue;
                    if(m_session->GetMethod() != hmHead)
                        m_session->SendContent(file_cache_buf + content_ranges[v].beg, 
                            rest_length > content_ranges[v].len ? content_ranges[v].len : rest_length);
                }
            }
        }
        //free(file_cache_buf);
    }
    else
    {
        ifstream ifsResource(strResourceFullPath.c_str(), ios_base::binary);
        string strline;
        if(!ifsResource.is_open())
        {
            CHttpResponseHdr header;
            header.SetStatusCode(SC404);
            header.SetField("Content-Type", "text/html");
            header.SetField("Content-Length", header.GetDefaultHTMLLength());
            m_session->SendHeader(header.Text(), header.Length());
            m_session->SendContent(header.GetDefaultHTML(), header.GetDefaultHTMLLength());
        }
        else
        {
            CHttpResponseHdr header;
            if(strcmp(szHttpRequestRanges, "") != 0 && strContentRangeResponse != "")
                header.SetStatusCode(SC206);
            else
                header.SetStatusCode(SC200);
            header.SetField("ETag", szQETagQ);
            header.SetField("Content-Length", nRangeLength);
            OutHTTPDateString(time(NULL) + 900, strDateTime);
            header.SetField("Expires", strDateTime.c_str());
            header.SetField("Cache-Control", "max-age=900");
            OutHTTPDateString(tLastModifyTime, strDateTime);
            header.SetField("Last-Modified", strDateTime.c_str());
            
            if(m_session->m_cache->m_type_table.find(strExtName) == m_session->m_cache->m_type_table.end())
            {
                header.SetField("Content-Type", "application/*");
            }
            else
            {
                header.SetField("Content-Type", m_session->m_cache->m_type_table[strExtName].c_str());
            }
            if(strcmp(szHttpRequestRanges, "") != 0 && strContentRangeResponse != "")
            {
                header.SetField("Content-Range", strContentRangeResponse.c_str());
            }
            
            m_session->SendHeader(header.Text(), header.Length());
            
            if(strcmp(szHttpRequestRanges, "") == 0)
            {
                if(m_session->GetMethod() != hmHead)
                {
                    char rbuf[1449];
                    while(1)
                    {
                        if(ifsResource.eof())
                            break;
                        
                        if(ifsResource.read(rbuf, 1448) < 0)
                            break;
                        
                        int rlen = ifsResource.gcount();
                        if(m_session->GetMethod() != hmHead)
                            m_session->SendContent(rbuf, rlen);
                    }
                }
            }
            else
            {
                for(int v = 0; v < content_ranges.size(); v++)
                {
                    if(m_session->GetMethod() != hmHead)
                    {
                        ifsResource.seekg(content_ranges[v].beg, ios::beg);
                        long long len_sum = 0;
                        char rbuf[1449];
                        while(1)
                        {
                            if(ifsResource.eof())
                                break;
                            int rest_len = content_ranges[v].len - len_sum;
                            if(ifsResource.read(rbuf, rest_len  > 1448 ? 1448 : rest_len) < 0)
                                break;
                            
                            int rlen = ifsResource.gcount();
                            len_sum += rlen;
                            if(m_session->GetMethod() != hmHead)
                                m_session->SendContent(rbuf, rlen);
                            if(len_sum == content_ranges[v].len)
                                break;
                        }
                    }
                }
            }
        }
        if(ifsResource.is_open())
            ifsResource.close();
    }
END_STEP1:
    if(file_cache_instance)
        file_cache_instance->file_unlock();
    return;
}
示例#17
0
文件: menu.c 项目: unisx/gophernicus
/*
 * Handle gopher menus
 */
void gopher_menu(state *st)
{
	FILE *fp;
	sdirent dir[MAX_SDIRENT];
	struct tm *ltime;
	struct stat file;
	char buf[BUFSIZE];
	char pathname[BUFSIZE];
	char displayname[BUFSIZE];
	char encodedname[BUFSIZE];
	char timestr[20];
	char sizestr[20];
	char *parent;
	char *c;
	char type;
	int width;
	int num;
	int i;
	int n;

	/* Check for a gophermap */
	snprintf(pathname, sizeof(pathname), "%s/%s",
		st->req_realpath, st->map_file);

	if (stat(pathname, &file) == OK &&
	    (file.st_mode & S_IFMT) == S_IFREG) {

		/* Parse gophermap */
		if (gophermap(st, pathname, 0) == QUIT) {
			footer(st);
			return;
		}
	}

	else {
		/* Check for a gophertag */
		snprintf(pathname, sizeof(pathname), "%s/%s",
			st->req_realpath, st->tag_file);

		if (stat(pathname, &file) == OK &&
		    (file.st_mode & S_IFMT) == S_IFREG) {

			/* Read & output gophertag */
			if ((fp = fopen(pathname , "r"))) {

				fgets(buf, sizeof(buf), fp);
				chomp(buf);

				info(st, buf, TYPE_TITLE);
				info(st, EMPTY, TYPE_INFO);
				fclose(fp);
			}
		}

		/* No gophermap or tag found - print default header */
		else if (st->opt_header) {

			/* Use the selector as menu title */
			sstrlcpy(displayname, st->req_selector);

			/* Shorten too long titles */
			while (strlen(displayname) > (st->out_width - sizeof(HEADER_FORMAT))) {
				if ((c = strchr(displayname, '/')) == NULL) break;

				if (!*++c) break;
				sstrlcpy(displayname, c);
			}

			/* Output menu title */
			snprintf(buf, sizeof(buf), HEADER_FORMAT, displayname);
			info(st, buf, TYPE_TITLE);
			info(st, EMPTY, TYPE_INFO);
		}
	}

	/* Scan the directory */
	num = sortdir(st->req_realpath, dir, MAX_SDIRENT);
	if (num < 0) die(st, ERR_NOTFOUND, "WTF?");

	/* Create link to parent directory */
	if (st->opt_parent) {
		sstrlcpy(buf, st->req_selector);
		parent = dirname(buf);

		/* Root has no parent */
		if (strcmp(st->req_selector, ROOT) != MATCH) {

			/* Prevent double-slash */
			if (strcmp(parent, ROOT) == MATCH) parent++;

			/* Print link */
			printf("1%-*s\t%s/\t%s\t%i" CRLF,
				st->opt_date ? (st->out_width - 1) : (int) strlen(PARENT),
				PARENT, parent, st->server_host, st->server_port);
		}
	}

	/* Width of filenames for fancy listing */
	width = st->out_width - DATE_WIDTH - 15;

	/* Loop through the directory entries */
	for (i = 0; i < num; i++) {

		/* Get full path+name */
		snprintf(pathname, sizeof(pathname), "%s/%s",
			st->req_realpath, dir[i].name);

		/* Skip dotfiles and non world-readables */
		if (dir[i].name[0] == '.') continue;
		if ((dir[i].mode & S_IROTH) == 0) continue;

		/* Skip gophermaps and tags (but not dirs) */
		if ((dir[i].mode & S_IFMT) != S_IFDIR) {
			if (strcmp(dir[i].name, st->map_file) == MATCH) continue;
			if (strcmp(dir[i].name, st->tag_file) == MATCH) continue;
		}

		/* Skip files marked for hiding */
		for (n = 0; n < st->hidden_count; n++)
			if (strcmp(dir[i].name, st->hidden[n]) == MATCH) break;
		if (n < st->hidden_count) continue;	/* Cruel hack... */

		/* Generate display name with correct output charset */
		if (st->opt_iconv)
			sstrniconv(st->out_charset, displayname, dir[i].name);
		else
			sstrlcpy(displayname, dir[i].name);

		/* #OCT-encode filename */
		strnencode(encodedname, dir[i].name, sizeof(encodedname));

		/* Handle inline .gophermap */
		if (strstr(displayname, st->map_file) > displayname) {
			gophermap(st, pathname, 0);
			continue;
		}

		/* Handle directories */
		if ((dir[i].mode & S_IFMT) == S_IFDIR) {

			/* Check for a gophertag */
			snprintf(buf, sizeof(buf), "%s/%s",
				pathname, st->tag_file);

			if (stat(buf, &file) == OK &&
			    (file.st_mode & S_IFMT) == S_IFREG) {

				/* Use the gophertag as displayname */
				if ((fp = fopen(buf , "r"))) {

					fgets(buf, sizeof(buf), fp);
					chomp(buf);
					fclose(fp);

					/* Skip empty gophertags */
					if (*buf) {

						/* Convert to output charset */
						if (st->opt_iconv) sstrniconv(st->out_charset, displayname, buf);
						else sstrlcpy(displayname, buf);
					}

				}
			}

			/* Dir listing with dates */
			if (st->opt_date) {
				ltime = localtime(&dir[i].mtime);
				strftime(timestr, sizeof(timestr), DATE_FORMAT, ltime);

				/* Hack to get around UTF-8 byte != char */
				n = width - strcut(displayname, width);
				strrepeat(buf, ' ', n);

				printf("1%s%s   %s        -  \t%s%s/\t%s\t%i" CRLF,
					displayname,
					buf,
					timestr,
					st->req_selector,
					encodedname,
					st->server_host,
					st->server_port);
			}

			/* Regular dir listing */
			else {
				strcut(displayname, st->out_width);
				printf("1%s\t%s%s/\t%s\t%i" CRLF,
					displayname,
					st->req_selector,
					encodedname,
					st->server_host,
					st->server_port);
			}

			continue;
		}

		/* Skip special files (sockets, fifos etc) */
		if ((dir[i].mode & S_IFMT) != S_IFREG) continue;

		/* Get file type */
		type = gopher_filetype(st, pathname, st->opt_magic);

		/* File listing with dates & sizes */
		if (st->opt_date) {
			ltime = localtime(&dir[i].mtime);
			strftime(timestr, sizeof(timestr), DATE_FORMAT, ltime);
			strfsize(sizestr, dir[i].size, sizeof(sizestr));

			/* Hack to get around UTF-8 byte != char */
			n = width - strcut(displayname, width);
			strrepeat(buf, ' ', n);

			printf("%c%s%s   %s %s\t%s%s\t%s\t%i" CRLF, type,
				displayname,
				buf,
				timestr,
				sizestr,
				st->req_selector,
				encodedname,
				st->server_host,
				st->server_port);
		}

		/* Regular file listing */
		else {
			strcut(displayname, st->out_width);
			printf("%c%s\t%s%s\t%s\t%i" CRLF, type,
				displayname,
				st->req_selector,
				encodedname,
				st->server_host,
				st->server_port);
		}
	}

	/* Print footer */
	footer(st);
}
示例#18
0
void query_topology()
{
    INT4 status = 0;
    JNIEnv *jni_env = NULL;
    jstring arg_tableName;
    jstring arg_row;
    jstring arg_columnFamily;
    jstring arg_column;
    jstring arg_value;

    jarray data;
    UINT4 src_port = 0;
    UINT4 dst_port = 0;
    unsigned long long int src_dpid = 0;
    unsigned long long int dst_dpid = 0;
    gn_switch_t *src_sw;

    if(0 == g_method_addrecord)
    {
        LOG_PROC("ERROR", "Hbase client hasn't ready");
        return;
    }

    //Get jni env for current thread
    status = (*g_jvm)->AttachCurrentThread(g_jvm, (void**)&jni_env, NULL);
    if (0 != status)
    {
        LOG_PROC("ERROR", "Update topology, can not get jni env");
        return;
    }

    arg_value = (*jni_env)->NewStringUTF(jni_env, "0");
    arg_tableName = (*jni_env)->NewStringUTF(jni_env, COMMON_TABLE);
    arg_row = (*jni_env)->NewStringUTF(jni_env, TOPO_VER);
    data = (jstring)((*jni_env)->CallStaticObjectMethod(jni_env, g_hbase_client, g_method_getonerecord, arg_tableName, arg_row));
    if (NULL != data)
    {
        const char *str = (*jni_env)->GetStringUTFChars(jni_env, data, NULL);
        arg_value = (*jni_env)->NewStringUTF(jni_env, str + 6);
    }
    arg_tableName = (*jni_env)->NewStringUTF(jni_env, TOPO_TABLE);
    arg_columnFamily = (*jni_env)->NewStringUTF(jni_env, TOPO_TABLE_CF);
    arg_column = (*jni_env)->NewStringUTF(jni_env, "VERSION");
    data = (*jni_env)->CallStaticObjectMethod(jni_env, g_hbase_client, g_method_getrecordsbyfilter, arg_tableName, arg_columnFamily, arg_column, arg_value);
    if (NULL != data)
    {
        const jsize length = (*jni_env)->GetArrayLength(jni_env, data);
        jsize index = length;
        while(index--)
        {
            jstring element = (jstring)((*jni_env)->GetObjectArrayElement(jni_env, data, index));
            char const* nativeString = (*jni_env)->GetStringUTFChars(jni_env, element, 0);

            char *p_next = NULL;
            char *value = NULL;
            char *str_cpy = strdup(nativeString);
            char *column = strcut(str_cpy, '|', &p_next);
            while(column)
            {
                value = strcut(NULL, '|', &p_next);
                if (0 == strcmp(column, "SRC_DPID"))
                {
                    src_dpid = strtoull(value, NULL, 16);
                }
                else if(0 == strcmp(column, "SRC_PORT"))
                {
                    src_port = atoi(value);
                }
                else if(0 == strcmp(column, "DST_DPID"))
                {
                    dst_dpid = strtoull(value, NULL, 16);
                }
                else if(0 == strcmp(column, "DST_PORT"))
                {
                    dst_port = atoi(value);
                }

                if (!p_next)
                {
                    break;
                }
                column = strcut(NULL, '|', &p_next);
            }

            free(str_cpy);
            (*jni_env)->ReleaseStringUTFChars(jni_env, element, nativeString);

            src_sw = find_sw_from_dpid(src_dpid);
            if(src_sw)
            {
                LOG_PROC("DEBUG", "----======>>>>> Mapping a new neighbor: src- %016llx.%d, dst: %016llx.%d", src_dpid, src_port, dst_dpid, dst_port);
                mapping_new_neighbor(src_sw, src_port, dst_dpid, dst_port);
            }
            else
            {
                LOG_PROC("DEBUG", "----======>>>>> Mapping a new neighbor failed, can not find src sw: src- %016llx.%d, dst: %016llx.%d", src_dpid, src_port, dst_dpid, dst_port);
            }
        }
    }

    //detach
    (*g_jvm)->DetachCurrentThread(g_jvm);
}
示例#19
0
static int set_channel_name(struct iio_channel *chn)
{
	struct iio_channel_pdata *pdata = chn->pdata;
	size_t prefix_len = 0;
	const char *attr0;
	const char *ptr;
	unsigned int i;

	if (chn->nb_attrs + pdata->nb_protected_attrs < 2)
		return 0;

	if (chn->nb_attrs)
		attr0 = ptr = chn->attrs[0].name;
	else
		attr0 = ptr = pdata->protected_attrs[0].name;

	while (true) {
		bool can_fix = true;
		size_t len;

		ptr = strchr(ptr, '_');
		if (!ptr)
			break;

		len = ptr - attr0 + 1;
		for (i = 1; can_fix && i < chn->nb_attrs; i++)
			can_fix = !strncmp(attr0, chn->attrs[i].name, len);

		for (i = !chn->nb_attrs;
				can_fix && i < pdata->nb_protected_attrs; i++) {
			can_fix = !strncmp(attr0,
					pdata->protected_attrs[i].name, len);
		}

		if (!can_fix)
			break;

		prefix_len = len;
		ptr = ptr + 1;
	}

	if (prefix_len) {
		char *name;

		name = malloc(prefix_len);
		if (!name)
			return -ENOMEM;
		strncpy(name, attr0, prefix_len - 1);
		name[prefix_len - 1] = '\0';
		DEBUG("Setting name of channel %s to %s\n", chn->id, name);
		chn->name = name;

		/* Shrink the attribute name */
		for (i = 0; i < chn->nb_attrs; i++)
			strcut(chn->attrs[i].name, prefix_len);
		for (i = 0; i < pdata->nb_protected_attrs; i++)
			strcut(pdata->protected_attrs[i].name, prefix_len);
	}

	return 0;
}