/**
 * \author Creighton, T. D.
 *
 * \brief Computes a continuous waveform with frequency drift and Doppler
 * modulation from an elliptical orbital trajectory.
 *
 * This function computes a quaiperiodic waveform using the spindown and
 * orbital parameters in <tt>*params</tt>, storing the result in
 * <tt>*output</tt>.
 *
 * In the <tt>*params</tt> structure, the routine uses all the "input"
 * fields specified in \ref GenerateSpinOrbitCW_h, and sets all of the
 * "output" fields.  If <tt>params-\>f</tt>=\c NULL, no spindown
 * modulation is performed.  If <tt>params-\>oneMinusEcc</tt>\f$\notin(0,1]\f$
 * (an open orbit), or if
 * <tt>params-\>rPeriNorm</tt>\f$\times\f$<tt>params-\>angularSpeed</tt>\f$\geq1\f$
 * (faster-than-light speed at periapsis), an error is returned.
 *
 * In the <tt>*output</tt> structure, the field <tt>output-\>h</tt> is
 * ignored, but all other pointer fields must be set to \c NULL.  The
 * function will create and allocate space for <tt>output-\>a</tt>,
 * <tt>output-\>f</tt>, and <tt>output-\>phi</tt> as necessary.  The
 * <tt>output-\>shift</tt> field will remain set to \c NULL.
 *
 * ### Algorithm ###
 *
 * For elliptical orbits, we combine \eqref{eq_spinorbit-tr},
 * \eqref{eq_spinorbit-t}, and \eqref{eq_spinorbit-upsilon} to get \f$t_r\f$
 * directly as a function of the eccentric anomaly \f$E\f$:
 * \f{eqnarray}{
 * \label{eq_tr-e1}
 * t_r = t_p & + & \left(\frac{r_p \sin i}{c}\right)\sin\omega\\
 * & + & \left(\frac{P}{2\pi}\right) \left( E +
 * \left[v_p(1-e)\cos\omega - e\right]\sin E
 * + \left[v_p\sqrt{\frac{1-e}{1+e}}\sin\omega\right]
 * [\cos E - 1]\right) \;,
 * \f}
 * where \f$v_p=r_p\dot{\upsilon}_p\sin i/c\f$ is a normalized velocity at
 * periapsis and \f$P=2\pi\sqrt{(1+e)/(1-e)^3}/\dot{\upsilon}_p\f$ is the
 * period of the orbit.  For simplicity we write this as:
 * \f{equation}{
 * \label{eq_tr-e2}
 * t_r = T_p + \frac{1}{n}\left( E + A\sin E + B[\cos E - 1] \right) \;,
 * \f}
 *
 * \figure{inject_eanomaly,eps,0.23,Function to be inverted to find eccentric anomaly}
 *
 * where \f$T_p\f$ is the \e observed time of periapsis passage and
 * \f$n=2\pi/P\f$ is the mean angular speed around the orbit.  Thus the key
 * numerical procedure in this routine is to invert the expression
 * \f$x=E+A\sin E+B(\cos E - 1)\f$ to get \f$E(x)\f$.  We note that
 * \f$E(x+2n\pi)=E(x)+2n\pi\f$, so we only need to solve this expression in
 * the interval \f$[0,2\pi)\f$, sketched to the right.
 *
 * We further note that \f$A^2+B^2<1\f$, although it approaches 1 when
 * \f$e\rightarrow1\f$, or when \f$v_p\rightarrow1\f$ and either \f$e=0\f$ or
 * \f$\omega=\pi\f$.  Except in this limit, Newton-Raphson methods will
 * converge rapidly for any initial guess.  In this limit, though, the
 * slope \f$dx/dE\f$ approaches zero at the point of inflection, and an
 * initial guess or iteration landing near this point will send the next
 * iteration off to unacceptably large or small values.  However, by
 * restricting all initial guesses and iterations to the domain
 * \f$E\in[0,2\pi)\f$, one will always end up on a trajectory branch that
 * will converge uniformly.  This should converge faster than the more
 * generically robust technique of bisection. (Note: the danger with Newton's method
 * has been found to be unstable for certain binary orbital parameters. So if
 * Newton's method fails to converge, a bisection algorithm is employed.)
 *
 * In this algorithm, we start the computation with an arbitrary initial
 * guess of \f$E=0\f$, and refine it until the we get agreement to within
 * 0.01 parts in part in \f$N_\mathrm{cyc}\f$ (where \f$N_\mathrm{cyc}\f$ is the
 * larger of the number of wave cycles in an orbital period, or the
 * number of wave cycles in the entire waveform being generated), or one
 * part in \f$10^{15}\f$ (an order of magnitude off the best precision
 * possible with \c REAL8 numbers).  The latter case indicates that
 * \c REAL8 precision may fail to give accurate phasing, and one
 * should consider modeling the orbit as a set of Taylor frequency
 * coefficients \'{a} la <tt>LALGenerateTaylorCW()</tt>.  On subsequent
 * timesteps, we use the previous timestep as an initial guess, which is
 * good so long as the timesteps are much smaller than an orbital period.
 * This sequence of guesses will have to readjust itself once every orbit
 * (as \f$E\f$ jumps from \f$2\pi\f$ down to 0), but this is relatively
 * infrequent; we don't bother trying to smooth this out because the
 * additional tests would probably slow down the algorithm overall.
 *
 * Once a value of \f$E\f$ is found for a given timestep in the output
 * series, we compute the system time \f$t\f$ via \eqref{eq_spinorbit-t},
 * and use it to determine the wave phase and (non-Doppler-shifted)
 * frequency via \eqref{eq_taylorcw-freq}
 * and \eqref{eq_taylorcw-phi}.  The Doppler shift on the frequency is
 * then computed using \eqref{eq_spinorbit-upsilon}
 * and \eqref{eq_orbit-rdot}.  We use \f$\upsilon\f$ as an intermediate in
 * the Doppler shift calculations, since expressing \f$\dot{R}\f$ directly in
 * terms of \f$E\f$ results in expression of the form \f$(1-e)/(1-e\cos E)\f$,
 * which are difficult to simplify and face precision losses when
 * \f$E\sim0\f$ and \f$e\rightarrow1\f$.  By contrast, solving for \f$\upsilon\f$ is
 * numerically stable provided that the system <tt>atan2()</tt> function is
 * well-designed.
 *
 * The routine does not account for variations in special relativistic or
 * gravitational time dilation due to the elliptical orbit, nor does it
 * deal with other gravitational effects such as Shapiro delay.  To a
 * very rough approximation, the amount of phase error induced by
 * gravitational redshift goes something like \f$\Delta\phi\sim
 * fT(v/c)^2\Delta(r_p/r)\f$, where \f$f\f$ is the typical wave frequency, \f$T\f$
 * is either the length of data or the orbital period (whichever is
 * \e smaller), \f$v\f$ is the \e true (unprojected) speed at
 * periapsis, and \f$\Delta(r_p/r)\f$ is the total range swept out by the
 * quantity \f$r_p/r\f$ over the course of the observation.  Other
 * relativistic effects such as special relativistic time dilation are
 * comparable in magnitude.  We make a crude estimate of when this is
 * significant by noting that \f$v/c\gtrsim v_p\f$ but
 * \f$\Delta(r_p/r)\lesssim 2e/(1+e)\f$; we take these approximations as
 * equalities and require that \f$\Delta\phi\lesssim\pi\f$, giving:
 * \f{equation}{
 * \label{eq_relativistic-orbit}
 * f_0Tv_p^2\frac{4e}{1+e}\lesssim1 \;.
 * \f}
 * When this critereon is violated, a warning is generated.  Furthermore,
 * as noted earlier, when \f$v_p\geq1\f$ the routine will return an error, as
 * faster-than-light speeds can cause the emission and reception times to
 * be non-monotonic functions of one another.
 */
void
LALGenerateEllipticSpinOrbitCW( LALStatus             *stat,
				PulsarCoherentGW            *output,
				SpinOrbitCWParamStruc *params )
{
  UINT4 n, i;              /* number of and index over samples */
  UINT4 nSpin = 0, j;      /* number of and index over spindown terms */
  REAL8 t, dt, tPow;       /* time, interval, and t raised to a power */
  REAL8 phi0, f0, twopif0; /* initial phase, frequency, and 2*pi*f0 */
  REAL8 f, fPrev;          /* current and previous values of frequency */
  REAL4 df = 0.0;          /* maximum difference between f and fPrev */
  REAL8 phi;               /* current value of phase */
  REAL8 p, vDotAvg;        /* orbital period, and 2*pi/(period) */
  REAL8 vp;                /* projected speed at periapsis */
  REAL8 upsilon, argument; /* true anomaly, and argument of periapsis */
  REAL8 eCosOmega;         /* eccentricity * cosine of argument */
  REAL8 tPeriObs;          /* time of observed periapsis */
  REAL8 spinOff;           /* spin epoch - orbit epoch */
  REAL8 x;                 /* observed mean anomaly */
  REAL8 dx, dxMax;         /* current and target errors in x */
  REAL8 a, b;              /* constants in equation for x */
  REAL8 ecc;               /* orbital eccentricity */
  REAL8 oneMinusEcc, onePlusEcc; /* 1 - ecc and 1 + ecc */
  REAL8 e = 0.0;                 /* eccentric anomaly */
  REAL8 de = 0.0;                /* eccentric anomaly step */
  REAL8 sine = 0.0, cose = 0.0;  /* sine of e, and cosine of e minus 1 */
  REAL8 *fSpin = NULL;           /* pointer to Taylor coefficients */
  REAL4 *fData;                  /* pointer to frequency data */
  REAL8 *phiData;                /* pointer to phase data */

  INITSTATUS(stat);
  ATTATCHSTATUSPTR( stat );

  /* Make sure parameter and output structures exist. */
  ASSERT( params, stat, GENERATESPINORBITCWH_ENUL,
	  GENERATESPINORBITCWH_MSGENUL );
  ASSERT( output, stat, GENERATESPINORBITCWH_ENUL,
	  GENERATESPINORBITCWH_MSGENUL );

  /* Make sure output fields don't exist. */
  ASSERT( !( output->a ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );
  ASSERT( !( output->f ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );
  ASSERT( !( output->phi ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );
  ASSERT( !( output->shift ), stat, GENERATESPINORBITCWH_EOUT,
	  GENERATESPINORBITCWH_MSGEOUT );

  /* If Taylor coeficients are specified, make sure they exist. */
  if ( params->f ) {
    ASSERT( params->f->data, stat, GENERATESPINORBITCWH_ENUL,
	    GENERATESPINORBITCWH_MSGENUL );
    nSpin = params->f->length;
    fSpin = params->f->data;
  }

  /* Set up some constants (to avoid repeated calculation or
     dereferencing), and make sure they have acceptable values. */
  oneMinusEcc = params->oneMinusEcc;
  ecc = 1.0 - oneMinusEcc;
  onePlusEcc = 1.0 + ecc;
  if ( ecc < 0.0 || oneMinusEcc <= 0.0 ) {
    ABORT( stat, GENERATESPINORBITCWH_EECC,
	   GENERATESPINORBITCWH_MSGEECC );
  }
  vp = params->rPeriNorm*params->angularSpeed;
  n = params->length;
  dt = params->deltaT;
  f0 = fPrev = params->f0;
  vDotAvg = params->angularSpeed
    *sqrt( oneMinusEcc*oneMinusEcc*oneMinusEcc/onePlusEcc );
  if ( vp >= 1.0 ) {
    ABORT( stat, GENERATESPINORBITCWH_EFTL,
	   GENERATESPINORBITCWH_MSGEFTL );
  }
  if ( vp <= 0.0 || dt <= 0.0 || f0 <= 0.0 || vDotAvg <= 0.0 ||
       n == 0 ) {
    ABORT( stat, GENERATESPINORBITCWH_ESGN,
	   GENERATESPINORBITCWH_MSGESGN );
  }

  /* Set up some other constants. */
  twopif0 = f0*LAL_TWOPI;
  phi0 = params->phi0;
  argument = params->omega;
  p = LAL_TWOPI/vDotAvg;
  a = vp*oneMinusEcc*cos( argument ) + oneMinusEcc - 1.0;
  b = vp*sqrt( oneMinusEcc/( onePlusEcc ) )*sin( argument );
  eCosOmega = ecc*cos( argument );
  if ( n*dt > p )
    dxMax = 0.01/( f0*n*dt );
  else
    dxMax = 0.01/( f0*p );
  if ( dxMax < 1.0e-15 ) {
    dxMax = 1.0e-15;
#ifndef NDEBUG
    LALWarning( stat, "REAL8 arithmetic may not have sufficient"
		" precision for this orbit" );
#endif
  }
#ifndef NDEBUG
  if ( lalDebugLevel & LALWARNING ) {
    REAL8 tau = n*dt;
    if ( tau > p )
      tau = p;
    if ( f0*tau*vp*vp*ecc/onePlusEcc > 0.25 )
      LALWarning( stat, "Orbit may have significant relativistic"
		  " effects that are not included" );
  }
#endif

  /* Compute offset between time series epoch and observed periapsis,
     and betweem true periapsis and spindown reference epoch. */
  tPeriObs = (REAL8)( params->orbitEpoch.gpsSeconds -
		      params->epoch.gpsSeconds );
  tPeriObs += 1.0e-9 * (REAL8)( params->orbitEpoch.gpsNanoSeconds -
				params->epoch.gpsNanoSeconds );
  tPeriObs += params->rPeriNorm*sin( params->omega );
  spinOff = (REAL8)( params->orbitEpoch.gpsSeconds -
		     params->spinEpoch.gpsSeconds );
  spinOff += 1.0e-9 * (REAL8)( params->orbitEpoch.gpsNanoSeconds -
			       params->spinEpoch.gpsNanoSeconds );

  /* Allocate output structures. */
  if ( ( output->a = (REAL4TimeVectorSeries *)
	 LALMalloc( sizeof(REAL4TimeVectorSeries) ) ) == NULL ) {
    ABORT( stat, GENERATESPINORBITCWH_EMEM,
	   GENERATESPINORBITCWH_MSGEMEM );
  }
  memset( output->a, 0, sizeof(REAL4TimeVectorSeries) );
  if ( ( output->f = (REAL4TimeSeries *)
	 LALMalloc( sizeof(REAL4TimeSeries) ) ) == NULL ) {
    LALFree( output->a ); output->a = NULL;
    ABORT( stat, GENERATESPINORBITCWH_EMEM,
	   GENERATESPINORBITCWH_MSGEMEM );
  }
  memset( output->f, 0, sizeof(REAL4TimeSeries) );
  if ( ( output->phi = (REAL8TimeSeries *)
	 LALMalloc( sizeof(REAL8TimeSeries) ) ) == NULL ) {
    LALFree( output->a ); output->a = NULL;
    LALFree( output->f ); output->f = NULL;
    ABORT( stat, GENERATESPINORBITCWH_EMEM,
	   GENERATESPINORBITCWH_MSGEMEM );
  }
  memset( output->phi, 0, sizeof(REAL8TimeSeries) );

  /* Set output structure metadata fields. */
  output->position = params->position;
  output->psi = params->psi;
  output->a->epoch = output->f->epoch = output->phi->epoch
    = params->epoch;
  output->a->deltaT = n*params->deltaT;
  output->f->deltaT = output->phi->deltaT = params->deltaT;
  output->a->sampleUnits = lalStrainUnit;
  output->f->sampleUnits = lalHertzUnit;
  output->phi->sampleUnits = lalDimensionlessUnit;
  snprintf( output->a->name, LALNameLength, "CW amplitudes" );
  snprintf( output->f->name, LALNameLength, "CW frequency" );
  snprintf( output->phi->name, LALNameLength, "CW phase" );

  /* Allocate phase and frequency arrays. */
  LALSCreateVector( stat->statusPtr, &( output->f->data ), n );
  BEGINFAIL( stat ) {
    LALFree( output->a );   output->a = NULL;
    LALFree( output->f );   output->f = NULL;
    LALFree( output->phi ); output->phi = NULL;
  } ENDFAIL( stat );
  LALDCreateVector( stat->statusPtr, &( output->phi->data ), n );
  BEGINFAIL( stat ) {
    TRY( LALSDestroyVector( stat->statusPtr, &( output->f->data ) ),
	 stat );
    LALFree( output->a );   output->a = NULL;
    LALFree( output->f );   output->f = NULL;
    LALFree( output->phi ); output->phi = NULL;
  } ENDFAIL( stat );

  /* Allocate and fill amplitude array. */
  {
    CreateVectorSequenceIn in; /* input to create output->a */
    in.length = 2;
    in.vectorLength = 2;
    LALSCreateVectorSequence( stat->statusPtr, &(output->a->data), &in );
    BEGINFAIL( stat ) {
      TRY( LALSDestroyVector( stat->statusPtr, &( output->f->data ) ),
	   stat );
      TRY( LALDDestroyVector( stat->statusPtr, &( output->phi->data ) ),
	   stat );
      LALFree( output->a );   output->a = NULL;
      LALFree( output->f );   output->f = NULL;
      LALFree( output->phi ); output->phi = NULL;
    } ENDFAIL( stat );
    output->a->data->data[0] = output->a->data->data[2] = params->aPlus;
    output->a->data->data[1] = output->a->data->data[3] = params->aCross;
  }

  /* Fill frequency and phase arrays. */
  fData = output->f->data->data;
  phiData = output->phi->data->data;
  for ( i = 0; i < n; i++ ) {
    INT4 nOrb; /* number of orbits since the specified orbit epoch */

    /* First, find x in the range [0,2*pi]. */
    x = vDotAvg*( i*dt - tPeriObs );
    nOrb = (INT4)( x/LAL_TWOPI );
    if ( x < 0.0 )
      nOrb -= 1;
    x -= LAL_TWOPI*nOrb;

    /* Newton-Raphson iteration to find E(x). Maximum of 100 iterations. */
    INT4 maxiter = 100, iter = 0;
    while ( iter<maxiter && fabs( dx = e + a*sine + b*cose - x ) > dxMax ) {
      iter++;
      //Make a check on the step-size so we don't step too far
      de = dx/( 1.0 + a*cose + a - b*sine );
      if ( de > LAL_PI )
        de = LAL_PI;
      else if ( de < -LAL_PI )
        de = -LAL_PI;
      e -= de;

      if ( e < 0.0 )
        e = 0.0;
      else if ( e > LAL_TWOPI )
        e = LAL_TWOPI;
      sine = sin( e );
      cose = cos( e ) - 1.0;
    }
    /* Bisection algorithm from GSL if Newton's method (above) fails to converge. */
    if (iter==maxiter && fabs( dx = e + a*sine + b*cose - x ) > dxMax ) {
       //Initialize solver
       const gsl_root_fsolver_type *T = gsl_root_fsolver_bisection;
       gsl_root_fsolver *s = gsl_root_fsolver_alloc(T);
       REAL8 e_lo = 0.0, e_hi = LAL_TWOPI;
       gsl_function F;
       struct E_solver_params pars = {a, b, x};
       F.function = &gsl_E_solver;
       F.params = &pars;

       if (gsl_root_fsolver_set(s, &F, e_lo, e_hi) != 0) {
          LALFree( output->a );   output->a = NULL;
          LALFree( output->f );   output->f = NULL;
          LALFree( output->phi ); output->phi = NULL;
          ABORT( stat, -1, "GSL failed to set initial points" );
       }

       INT4 keepgoing = 1;
       INT4 success = 0;
       INT4 root_status = keepgoing;
       e = 0.0;
       iter = 0;
       while (root_status==keepgoing && iter<maxiter) {
          iter++;
          root_status = gsl_root_fsolver_iterate(s);
          if (root_status!=keepgoing && root_status!=success) {
             LALFree( output->a );   output->a = NULL;
             LALFree( output->f );   output->f = NULL;
             LALFree( output->phi ); output->phi = NULL;
             ABORT( stat, -1, "gsl_root_fsolver_iterate() failed" );
          }
          e = gsl_root_fsolver_root(s);
          sine = sin(e);
          cose = cos(e) - 1.0;
          if (fabs( dx = e + a*sine + b*cose - x ) > dxMax) root_status = keepgoing;
          else root_status = success;
       }

       if (root_status!=success) {
          LALFree( output->a );   output->a = NULL;
          LALFree( output->f );   output->f = NULL;
          LALFree( output->phi ); output->phi = NULL;
          gsl_root_fsolver_free(s);
          ABORT( stat, -1, "Could not converge using bisection algorithm" );
       }

       gsl_root_fsolver_free(s);
    }

    /* Compute source emission time, phase, and frequency. */
    phi = t = tPow =
      ( e + LAL_TWOPI*nOrb - ecc*sine )/vDotAvg + spinOff;
    f = 1.0;
    for ( j = 0; j < nSpin; j++ ) {
      f += fSpin[j]*tPow;
      phi += fSpin[j]*( tPow*=t )/( j + 2.0 );
    }

    /* Appy frequency Doppler shift. */
    upsilon = 2.0 * atan2 ( sqrt(onePlusEcc/oneMinusEcc) * sin(0.5*e), cos(0.5*e) );
    f *= f0 / ( 1.0 + vp*( cos( argument + upsilon ) + eCosOmega ) /onePlusEcc );
    phi *= twopif0;
    if ( (i > 0) && (fabs( f - fPrev ) > df) )
      df = fabs( f - fPrev );
    *(fData++) = fPrev = f;
    *(phiData++) = phi + phi0;

  } /* for i < n */

  /* Set output field and return. */
  params->dfdt = df*dt;
  DETATCHSTATUSPTR( stat );
  RETURN( stat );
}
Esempio n. 2
0
File: vz.c Progetto: OpenVZ/libvzctl
char *get_running_state_fname(const char *ve_private, char *buf, int size)
{
	snprintf(buf, size, "%s/.running", ve_private);

	return buf;
}
Esempio n. 3
0
File: vz.c Progetto: OpenVZ/libvzctl
/** Register Container
 * @param path		Container private data root
 * @param param		struct vzctl_reg_param
 * @param flags		registration flags
 * @return		veid or -1 in case error
 */
int vzctl2_env_register(const char *path, struct vzctl_reg_param *param, int flags)
{
	char buf[PATH_MAX];
	char veconf[STR_SIZE];
	char path_r[PATH_MAX];
	struct stat st;
	int ret, err;
	struct vzctl_env_handle *h;
	FILE *fp;
	char ve_host[STR_SIZE];
	char host[STR_SIZE];
	int owner_check_res;
	int on_pcs, on_shared;
	int ha_resource_added = 0;
	int ha_enable = 0;
	const char *data, *name;
	ctid_t ctid = {};
	ctid_t uuid = {};

	/* preserve compatibility
	 * VZ_REG_SKIP_HA_CLUSTER is alias for VZ_REG_SKIP_CLUSTER
	 */
	if (flags & VZ_REG_SKIP_HA_CLUSTER)
		flags |= VZ_REG_SKIP_CLUSTER;

	if (stat(path, &st) != 0)
		return vzctl_err(-1, errno, "Unable to stat %s", path);

	if (realpath(path, path_r) == NULL)
		return vzctl_err(-1, errno, "Failed to get realpath %s", path);

	ret = vzctl2_env_layout_version(path_r);
	if (ret == -1) {
		return -1;
	} else if (ret < VZCTL_LAYOUT_4)
		return vzctl_err(-1, 0, "Warning: Container in old data format,"
				" registration skipped.");

	snprintf(veconf, sizeof(veconf), "%s/" VZCTL_VE_CONF, path_r);
	if (stat(veconf, &st)) {
		logger(-1, 0, "Error: Broken Container, no %s file found", veconf);
		return -1;
	}

	h = vzctl2_env_open_conf(param->ctid, veconf, 0, &err);
	if (h == NULL)
		return -1;

	data = param->uuid;
	/* get UUID from config if not specified */
	if (data == NULL)
		vzctl2_env_get_param(h, "UUID", &data);

	if (get_cid_uuid_pair(param->ctid, data, ctid, uuid))
		goto err;

	owner_check_res = vzctl_check_owner_quiet(
			path_r, host, sizeof(host), ve_host, sizeof(ve_host));
	on_pcs = (is_pcs(path_r) == 1);
	on_shared = (is_shared_fs(path_r) == 1);

        if (vzctl2_env_get_param(h, "HA_ENABLE", &data) == 0 && data != NULL)
                ha_enable = yesno2id(data);

	if (on_pcs && ha_enable != VZCTL_PARAM_OFF &&
			check_external_disk(path_r, h->env_param->disk) &&
			shaman_is_configured())
	{
		logger(-1, 0, "Containers with external disks cannot be"
				" registered in a High Availability cluster");
		goto err;
	}

	if (!(flags & VZ_REG_FORCE)) {
		/* ignore renew option for pstorage (https://jira.sw.ru/browse/PSBM-16819) */
		if (on_pcs)
			flags &= ~VZ_REG_RENEW;

		if (!(flags & VZ_REG_RENEW) && owner_check_res) {
			if (owner_check_res == VZCTL_E_ENV_MANAGE_DISABLED) {
				logger(-1, 0, "Owner check failed on the server %s;"
					" Container is registered for %s", host, ve_host);
				if (on_pcs)
					logger(0, 0,
					"Failed to register the Container/virtual machine. "
					"You can force the registration, but this will revoke "
					"all access to the Container from the original server.");
			}
			goto err;
		}

		if (validate_eid(h, &st, ctid))
			goto err;
	} else if ((owner_check_res == VZCTL_E_ENV_MANAGE_DISABLED) && on_shared) {
		if (on_pcs && !(flags & VZ_REG_SKIP_CLUSTER)) {
			/* [pstorage:] if CT already registered on other node, revoke leases */
			/* before files editing (https://jira.sw.ru/browse/PSBM-16819) */
			char *argv[] = { "/usr/bin/pstorage", "revoke", "-R", (char *)path_r, NULL };
			/* it is irreversible operation */
			if (vzctl2_wrap_exec_script(argv, NULL, 0))
				goto err;
		}
		if (!(flags & VZ_REG_SKIP_CLUSTER) && (ha_enable != VZCTL_PARAM_OFF)) {
			/* remove resource from HA cluster
			 * TODO : execute 'del-everywhere' and 'add' by one command
			 *	 (https://jira.sw.ru/browse/PSBM-17374
			 */
			shaman_del_everywhere(ctid);
		}
	}
	if (!(flags & VZ_REG_SKIP_CLUSTER) && on_shared && (ha_enable != VZCTL_PARAM_OFF)) {
		/* TODO : execute 'del-everywhere' and 'add' by one command
		 *		(https://jira.sw.ru/browse/PSBM-17374)
		 * Right now ask HA cluster to register CT as resource
		 * and will do it before filesystem operations
		 */
		if (shaman_add_resource(ctid, h->conf, path_r)) {
			logger(-1, 0, "Error: Failed to register the Container %s on HA cluster",
					ctid);
			goto err;
		}
		ha_resource_added = 1;
	}

	if (!(flags & VZ_REG_SKIP_OWNER)) {
		snprintf(buf, sizeof(buf), "%s/" VZCTL_VE_OWNER, path_r);
		if ((fp = fopen(buf, "w")) == NULL) {
			logger(-1, errno, "Unable to register the Container; failed to create"
					" the file %s", buf);
			goto err;
		}
		if (get_serverid(buf, sizeof(buf)) == 0)
			fprintf(fp, "%s", buf);
		fclose(fp);
	}

	ret = renew_VE_PRIVATE(h, path, ctid);
	if (ret)
		goto err;

	/* restore CT name */
	name = param->name ?: h->env_param->name->name;
	if (name != NULL && *name != '\0') {
		ctid_t t;
		char x[PATH_MAX];
		const char *new_name = name;
		const char *veid = NULL;

		vzctl2_env_get_param(h, "VEID", &veid);

		if (vzctl2_get_envid_by_name(name, t) == 0 &&
				veid != NULL && CMP_CTID(t, veid))
		{
			logger(-1, 0, "Name %s is in use by CT %s", name, t);
			new_name = gen_uniq_name(name, x, sizeof(x));
		}

		vzctl2_env_set_param(h, "NAME", new_name);
		if (h->env_param->name->name) {
			struct stat st_n;

			snprintf(buf, sizeof(buf), ENV_NAME_DIR "%s",
					h->env_param->name->name);
			if (stat(buf, &st_n) == 0 && st.st_dev == st_n.st_dev)
				unlink(buf);
		}

		logger(0, 0, "Assign the name: %s", new_name);
		snprintf(buf, sizeof(buf), ENV_NAME_DIR "%s", new_name);
		unlink(buf);
		if (symlink(veconf, buf)) {
			logger(-1, errno, "Unable to create the link %s", buf);
			goto err;
		}
	}

	vzctl2_env_set_param(h, "VEID", ctid);
	/* Update UUID */
	vzctl2_env_set_param(h, "UUID", uuid);
	if (flags & (VZ_REG_RENEW_NETIF_IFNAME|VZ_REG_RENEW_NETIF_MAC)) {
		if (h->env_param->veth &&
				!list_empty(&h->env_param->veth->dev_list)) {
			h->env_param->veth->delall = 1;
			data = veth2str(h->env_param, h->env_param->veth, flags);
			if (data != NULL)
				vzctl2_env_set_param(h, "NETIF", data);
		}
	}

	ret = vzctl2_env_save_conf(h, veconf);
	if (ret)
		goto err;

	/* create registration */
	vzctl2_get_env_conf_path(ctid, buf, sizeof(buf));
	unlink(buf);
	if (symlink(veconf, buf)) {
		logger(-1, errno, "Failed to create the symlink %s", buf);
		goto err;
	}

	vzctl2_env_close(h);
	vzctl2_send_state_evt(ctid, VZCTL_ENV_REGISTERED);

	logger(0, 0, "Container %s was successfully registered", ctid);
	return 0;

err:
	if (ha_resource_added)
		shaman_del_resource(ctid);
	vzctl2_env_close(h);
	logger(-1, 0, "Container registration failed: %s",
			vzctl2_get_last_error());

	return -1;
}
void CGPS9_23LogPosition (uint8_t vl_index, uint32_t Status_Code, s_GN_GPS_Nav_Data *pl_nav_data_to_use)
{
#if defined( CMCC_LOGGING_ENABLE ) && defined( AGPS_UP_FTR )
    int8_t Session_Start[20], Session_End[20];

    switch( Status_Code )
    {
        case CGPS_SUPL_CMCC_AGPS_SESSION_STARTED:
           sprintf( (char*)Session_Start , "%d" , 0 );
           GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_AGPS_SESSION_STARTED , Session_Start , "session starts");
        break;

        case CGPS_SUPL_CMCC_REPONSE_TIMEOUT_CODE:
            if (pl_nav_data_to_use != NULL)
            {
                if(pl_nav_data_to_use->Valid_SingleFix || pl_nav_data_to_use->Valid_SingleFix)
                {
                    /*we have a fix but don't reach the quality*/
                    sprintf( s_CmccLog, "%i, %04d%02d%02d%02d%02d%02d.%03d, %f, %f, %f, %f, # Position(Timestamp, lat, lon, orientation, height)  time to fix : %ld ms",
                        s_CgpsSupl[vl_index].v_GPSHandle, pl_nav_data_to_use->Year, pl_nav_data_to_use->Month,
                        pl_nav_data_to_use->Day, pl_nav_data_to_use->Hours, pl_nav_data_to_use->Minutes,
                        pl_nav_data_to_use->Seconds, pl_nav_data_to_use->Milliseconds,
                        pl_nav_data_to_use->Latitude, pl_nav_data_to_use->Longitude,
                        pl_nav_data_to_use->CourseOverGround, pl_nav_data_to_use->Altitude_MSL,
                        GN_GPS_Get_OS_Time_ms()-s_CgpsNaf[vl_index].v_RegisterTime);

                    GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_REPONSE_TIMEOUT_CODE, (char*)s_CmccLog, CGPS_SUPL_CMCC_POSITION_QUALITY_NOT_REACHED_STRING);
                }
                else
                {
                    /*no fix*/
                    snprintf( s_CmccLog,CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1, "%i",s_CgpsSupl[vl_index].v_GPSHandle);
                    GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_REPONSE_TIMEOUT_CODE, (char*)s_CmccLog, CGPS_SUPL_CMCC_CANNOT_PRODUCE_POSITION_WITHIN_RESP_TIME_STRING);
                }
            }
            else
            {
                sprintf( s_CmccLog, "%i, %04d%02d%02d%02d%02d%02d.%03d, %f, %f, %f, %f, # Position(Timestamp, lat, lon, orientation, height)  time to fix : %ld ms",
                    s_CgpsSupl[vl_index].v_GPSHandle, vg_Nav_Data.Year, vg_Nav_Data.Month,
                    vg_Nav_Data.Day, vg_Nav_Data.Hours, vg_Nav_Data.Minutes,
                    vg_Nav_Data.Seconds, vg_Nav_Data.Milliseconds,
                    vg_Nav_Data.Latitude, vg_Nav_Data.Longitude,
                    vg_Nav_Data.CourseOverGround, vg_Nav_Data.Altitude_MSL,
                    GN_GPS_Get_OS_Time_ms()-s_CgpsSupl[vl_index].v_RegisterTime);
                GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_REPONSE_TIMEOUT_CODE, (char*)s_CmccLog, NULL);
            }
        break;

        case CGPS_SUPL_CMCC_POSITION_RESULT_CODE:
            if (pl_nav_data_to_use != NULL)
            {
                sprintf( s_CmccLog, "%i, %04d%02d%02d%02d%02d%02d.%03d, %f, %f, %f, %f, # Position(Timestamp, lat, lon, orientation, height)  time to fix : %ld ms",
                    s_CgpsSupl[vl_index].v_GPSHandle, pl_nav_data_to_use->Year, pl_nav_data_to_use->Month,
                    pl_nav_data_to_use->Day, pl_nav_data_to_use->Hours, pl_nav_data_to_use->Minutes,
                    pl_nav_data_to_use->Seconds, pl_nav_data_to_use->Milliseconds,
                    pl_nav_data_to_use->Latitude, pl_nav_data_to_use->Longitude,
                    pl_nav_data_to_use->CourseOverGround, pl_nav_data_to_use->Altitude_MSL,
                    GN_GPS_Get_OS_Time_ms()-s_CgpsNaf[vl_index].v_RegisterTime);

                GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_POSITION_RESULT_CODE, (char*)s_CmccLog, NULL);
            }
        break;

        case CGPS_SUPL_CMCC_NETWORKCONNECTION_CODE:
            snprintf(s_CmccLog, CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1, "%i",s_CgpsSupl[vl_index].v_GPSHandle);
            GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_NETWORKCONNECTION_CODE,(char*)s_CmccLog,CGPS_SUPL_CMCC_NETWORKCONNECTION_STRING);
        break;

        case CGPS_SUPL_CMCC_NO_NETWORKCONNECTION_CODE:
            if (vl_index == 0xFF)
            {
                snprintf(s_CmccLog, CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1, "%x", 0xFFFFFFFF);
                GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_NO_NETWORKCONNECTION_CODE, (char*)s_CmccLog, CGPS_SUPL_CMCC_AUTONOMOUS_SET_STRING);
            }
            else
            {
                snprintf(s_CmccLog, CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1,"%i",s_CgpsSupl[vl_index].v_GPSHandle);
                GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_NO_NETWORKCONNECTION_CODE, (char*)s_CmccLog, CGPS_SUPL_CMCC_NO_NETWORKCONNECTION_STRING);
            }
        break;

        case CGPS_SUPL_CMCC_NETWORKCONNECTION_FAILURE_CODE:
            snprintf(s_CmccLog, CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1, "%i",s_CgpsSupl[vl_index].v_GPSHandle);
            GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_NETWORKCONNECTION_FAILURE_CODE, (char*)s_CmccLog, CGPS_SUPL_CMCC_NETWORKCONNECTION_FAILURE_STRING);
        break;

        case CGPS_SUPL_CMCC_SERVERCONNECTION_CODE:
            snprintf(s_CmccLog, CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1, "%i",s_CgpsSupl[vl_index].v_GPSHandle);
            GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_SERVERCONNECTION_CODE,(char*)s_CmccLog,CGPS_SUPL_CMCC_SERVERCONNECTION_STRING);
        break;

        case CGPS_SUPL_CMCC_SERVERCONNECTION_FAILURE_CODE:
            snprintf(s_CmccLog, CGPS_SUPL_CMCC_STRING_MAX_LENGHT-1, "%i",s_CgpsSupl[vl_index].v_GPSHandle);
            GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_SERVERCONNECTION_FAILURE_CODE,(char*)s_CmccLog,CGPS_SUPL_CMCC_SERVERCONNECTION_FAILURE_STRING);
        break;

        case CGPS_SUPL_CMCC_AGPS_SESSION_ENDED:
           sprintf( (char*)Session_End , "%d" , 0 );
           GN_SUPL_Write_Event_Log_CMCC(CGPS_SUPL_CMCC_AGPS_SESSION_STARTED , Session_End , "session ends");
        break;
        default:

        break;
    };
#else
    vl_index           = vl_index;
    Status_Code        = Status_Code;
    pl_nav_data_to_use = pl_nav_data_to_use;
#endif
}
Esempio n. 5
0
/*********************************************************************
CREATE TABLE T(
 	c1 VARCHAR(n),
       	c2 INT NOT NULL,
       	c3 FLOAT,
       	c4 DOUBLE,
       	c5 BLOB,
	c6 DECIMAL,
	PK(c1));  */
static
ib_err_t
create_table(
/*=========*/
	const char*	dbname,			/*!< in: database name */
	const char*	name)			/*!< in: table name */
{
	ib_trx_t	ib_trx;
	ib_id_t		table_id = 0;
	ib_err_t	err = DB_SUCCESS;
	ib_tbl_sch_t	ib_tbl_sch = NULL;
	ib_idx_sch_t	ib_idx_sch = NULL;
	char		table_name[IB_MAX_TABLE_NAME_LEN];

#ifdef __WIN__
	sprintf(table_name, "%s/%s", dbname, name);
#else
	snprintf(table_name, sizeof(table_name), "%s/%s", dbname, name);
#endif

	/* Pass a table page size of 0, ie., use default page size. */
	err = ib_table_schema_create(
		table_name, &ib_tbl_sch, IB_TBL_COMPACT, 0);

	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_col(
		ib_tbl_sch, "c1", IB_VARCHAR, IB_COL_NONE, 0, 10);

	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_col(
		ib_tbl_sch, "c2", IB_INT, IB_COL_NOT_NULL, 0, sizeof(ib_u32_t));
	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_col(
		ib_tbl_sch, "c3", IB_FLOAT, IB_COL_NONE, 0, sizeof(float));
	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_col(
		ib_tbl_sch, "c4", IB_DOUBLE, IB_COL_NONE, 0, sizeof(double));
	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_col(
		ib_tbl_sch, "c5", IB_BLOB, IB_COL_NONE, 0, 0);
	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_col(
		ib_tbl_sch, "c6", IB_DECIMAL, IB_COL_NONE, 0, 0);
	assert(err == DB_SUCCESS);

	err = ib_table_schema_add_index(ib_tbl_sch, "PRIMARY", &ib_idx_sch);
	assert(err == DB_SUCCESS);

	/* Set prefix length to 0. */
	err = ib_index_schema_add_col( ib_idx_sch, "c1", 0);
	assert(err == DB_SUCCESS);

	err = ib_index_schema_set_clustered(ib_idx_sch);
	assert(err == DB_SUCCESS);

	/* create table */
	ib_trx = ib_trx_begin(IB_TRX_REPEATABLE_READ);
	err = ib_schema_lock_exclusive(ib_trx);
	assert(err == DB_SUCCESS);

	err = ib_table_create(ib_trx, ib_tbl_sch, &table_id);
	assert(err == DB_SUCCESS);

	err = ib_trx_commit(ib_trx);
	assert(err == DB_SUCCESS);

	if (ib_tbl_sch != NULL) {
		ib_table_schema_delete(ib_tbl_sch);
	}

	return(err);
}
static ssize_t dbg_mask_show(struct device *d,
		struct device_attribute *attr, char *buf)
{
	return snprintf(buf, PAGE_SIZE, "%d\n", data_msg_dbg_mask);
}
Esempio n. 7
0
static int dm4_dive(void *param, int columns, char **data, char **column)
{
	UNUSED(columns);
	UNUSED(column);
	int i;
	int interval, retval = 0;
	struct parser_state *state = (struct parser_state *)param;
	sqlite3 *handle = state->sql_handle;
	float *profileBlob;
	unsigned char *tempBlob;
	int *pressureBlob;
	char *err = NULL;
	char get_events_template[] = "select * from Mark where DiveId = %d";
	char get_tags_template[] = "select Text from DiveTag where DiveId = %d";
	char get_events[64];

	dive_start(state);
	state->cur_dive->number = atoi(data[0]);

	state->cur_dive->when = (time_t)(atol(data[1]));
	if (data[2])
		utf8_string(data[2], &state->cur_dive->notes);

	/*
	 * DM4 stores Duration and DiveTime. It looks like DiveTime is
	 * 10 to 60 seconds shorter than Duration. However, I have no
	 * idea what is the difference and which one should be used.
	 * Duration = data[3]
	 * DiveTime = data[15]
	 */
	if (data[3])
		state->cur_dive->duration.seconds = atoi(data[3]);
	if (data[15])
		state->cur_dive->dc.duration.seconds = atoi(data[15]);

	/*
	 * TODO: the deviceid hash should be calculated here.
	 */
	settings_start(state);
	dc_settings_start(state);
	if (data[4])
		utf8_string(data[4], &state->cur_settings.dc.serial_nr);
	if (data[5])
		utf8_string(data[5], &state->cur_settings.dc.model);

	state->cur_settings.dc.deviceid = 0xffffffff;
	dc_settings_end(state);
	settings_end(state);

	if (data[6])
		state->cur_dive->dc.maxdepth.mm = lrint(strtod_flags(data[6], NULL, 0) * 1000);
	if (data[8])
		state->cur_dive->dc.airtemp.mkelvin = C_to_mkelvin(atoi(data[8]));
	if (data[9])
		state->cur_dive->dc.watertemp.mkelvin = C_to_mkelvin(atoi(data[9]));

	/*
	 * TODO: handle multiple cylinders
	 */
	cylinder_start(state);
	if (data[22] && atoi(data[22]) > 0)
		state->cur_dive->cylinder[state->cur_cylinder_index].start.mbar = atoi(data[22]);
	else if (data[10] && atoi(data[10]) > 0)
		state->cur_dive->cylinder[state->cur_cylinder_index].start.mbar = atoi(data[10]);
	if (data[23] && atoi(data[23]) > 0)
		state->cur_dive->cylinder[state->cur_cylinder_index].end.mbar = (atoi(data[23]));
	if (data[11] && atoi(data[11]) > 0)
		state->cur_dive->cylinder[state->cur_cylinder_index].end.mbar = (atoi(data[11]));
	if (data[12])
		state->cur_dive->cylinder[state->cur_cylinder_index].type.size.mliter = lrint((strtod_flags(data[12], NULL, 0)) * 1000);
	if (data[13])
		state->cur_dive->cylinder[state->cur_cylinder_index].type.workingpressure.mbar = (atoi(data[13]));
	if (data[20])
		state->cur_dive->cylinder[state->cur_cylinder_index].gasmix.o2.permille = atoi(data[20]) * 10;
	if (data[21])
		state->cur_dive->cylinder[state->cur_cylinder_index].gasmix.he.permille = atoi(data[21]) * 10;
	cylinder_end(state);

	if (data[14])
		state->cur_dive->dc.surface_pressure.mbar = (atoi(data[14]) * 1000);

	interval = data[16] ? atoi(data[16]) : 0;
	profileBlob = (float *)data[17];
	tempBlob = (unsigned char *)data[18];
	pressureBlob = (int *)data[19];
	for (i = 0; interval && i * interval < state->cur_dive->duration.seconds; i++) {
		sample_start(state);
		state->cur_sample->time.seconds = i * interval;
		if (profileBlob)
			state->cur_sample->depth.mm = lrintf(profileBlob[i] * 1000.0f);
		else
			state->cur_sample->depth.mm = state->cur_dive->dc.maxdepth.mm;

		if (data[18] && data[18][0])
			state->cur_sample->temperature.mkelvin = C_to_mkelvin(tempBlob[i]);
		if (data[19] && data[19][0])
			state->cur_sample->pressure[0].mbar = pressureBlob[i];
		sample_end(state);
	}

	snprintf(get_events, sizeof(get_events) - 1, get_events_template, state->cur_dive->number);
	retval = sqlite3_exec(handle, get_events, &dm4_events, state, &err);
	if (retval != SQLITE_OK) {
		fprintf(stderr, "%s", "Database query dm4_events failed.\n");
		return 1;
	}

	snprintf(get_events, sizeof(get_events) - 1, get_tags_template, state->cur_dive->number);
	retval = sqlite3_exec(handle, get_events, &dm4_tags, state, &err);
	if (retval != SQLITE_OK) {
		fprintf(stderr, "%s", "Database query dm4_tags failed.\n");
		return 1;
	}

	dive_end(state);

	/*
	for (i=0; i<columns;++i) {
		fprintf(stderr, "%s\t", column[i]);
	}
	fprintf(stderr, "\n");
	for (i=0; i<columns;++i) {
		fprintf(stderr, "%s\t", data[i]);
	}
	fprintf(stderr, "\n");
	//exit(0);
	*/
	return SQLITE_OK;
}
Esempio n. 8
0
// pretty print elapsed (or estimated) number of seconds
static void time_string(uint32_t time, int est, char *buf, size_t len)
{
  	int y = time / 31556736;
  	int d = (time % 31556736) / 86400;
	int h = (time % 86400) / 3600;
	int m = (time % 3600) / 60;
	int s = time % 60;

	if (est) {
		if (y > 0) {
			snprintf(buf, len, "%d years", y);
		} else if (d > 9) {
			snprintf(buf, len, "%dd", d);
		} else if (d > 0) {
			snprintf(buf, len, "%dd%02dh", d, h);
		} else if (h > 9) {
			snprintf(buf, len, "%dh", h);
		} else if (h > 0) {
			snprintf(buf, len, "%dh%02dm", h, m);
		} else if (m > 9) {
			snprintf(buf, len, "%dm", m);
		} else if (m > 0) {
			snprintf(buf, len, "%dm%02ds", m, s);
		} else {
			snprintf(buf, len, "%ds", s);
		}
	} else {
		if (d > 0) {
			snprintf(buf, len, "%dd%d:%02d:%02d", d, h, m, s);
		} else if (h > 0) {
			snprintf(buf, len, "%d:%02d:%02d", h, m, s);
		} else {
			snprintf(buf, len, "%d:%02d", m, s);
		}
	}
}
Esempio n. 9
0
File: op.c Progetto: deeso/radare2
// TODO: use esil here?
R_API char *r_anal_op_to_string(RAnal *anal, RAnalOp *op) {
	RAnalFunction *f;
	char ret[128];
	char *cstr;
	char *r0 = r_anal_value_to_string (op->dst);
	char *a0 = r_anal_value_to_string (op->src[0]);
	char *a1 = r_anal_value_to_string (op->src[1]);

	switch (op->type) {
	case R_ANAL_OP_TYPE_MOV:
		snprintf (ret, sizeof (ret), "%s = %s", r0, a0);
		break;
	case R_ANAL_OP_TYPE_CJMP:
		{
		RAnalBlock *bb = r_anal_bb_from_offset (anal, op->addr);
		if (bb) {
			cstr = r_anal_cond_to_string (bb->cond);
			snprintf (ret, sizeof (ret), "if (%s) goto 0x%"PFMT64x, cstr, op->jump);
			free (cstr);
		} else snprintf (ret, sizeof (ret), "if (%s) goto 0x%"PFMT64x, "unk", op->jump);
		}
		break;
	case R_ANAL_OP_TYPE_JMP:
		snprintf (ret, sizeof (ret), "goto 0x%"PFMT64x, op->jump);
		break;
	case R_ANAL_OP_TYPE_UJMP:
		snprintf (ret, sizeof (ret), "goto %s", r0);
		break;
	case R_ANAL_OP_TYPE_PUSH:
	case R_ANAL_OP_TYPE_UPUSH:
		snprintf (ret, sizeof (ret), "push %s", a0);
		break;
	case R_ANAL_OP_TYPE_POP:
		snprintf (ret, sizeof (ret), "pop %s", r0);
		break;
	case R_ANAL_OP_TYPE_UCALL:
		snprintf (ret, sizeof (ret), "%s()", r0);
		break;
	case R_ANAL_OP_TYPE_CALL:
		f = r_anal_get_fcn_in (anal, op->jump, R_ANAL_FCN_TYPE_NULL);
		if (f) snprintf (ret, sizeof (ret), "%s()", f->name);
		else  snprintf (ret, sizeof (ret), "0x%"PFMT64x"()", op->jump);
		break;
	case R_ANAL_OP_TYPE_CCALL:
		f = r_anal_get_fcn_in (anal, op->jump, R_ANAL_FCN_TYPE_NULL);
		{
		RAnalBlock *bb = r_anal_bb_from_offset (anal, op->addr);
		if (bb) {
			cstr = r_anal_cond_to_string (bb->cond);
			if (f) snprintf (ret, sizeof (ret), "if (%s) %s()", cstr, f->name);
			else snprintf (ret, sizeof (ret), "if (%s) 0x%"PFMT64x"()", cstr, op->jump);
			free (cstr);
		} else {
			if (f) snprintf (ret, sizeof (ret), "if (unk) %s()", f->name);
			else snprintf (ret, sizeof (ret), "if (unk) 0x%"PFMT64x"()", op->jump);
		}
		}
		break;
	case R_ANAL_OP_TYPE_ADD:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s += %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s + %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_SUB:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s -= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s - %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_MUL:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s *= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s * %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_DIV:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s /= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s / %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_AND:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s &= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s & %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_OR:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s |= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s | %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_XOR:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s ^= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s ^ %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_LEA:
		snprintf (ret, sizeof (ret), "%s -> %s", r0, a0);
		break;
	case R_ANAL_OP_TYPE_CMP:
		memcpy (ret, ";", 2);
		break;
	case R_ANAL_OP_TYPE_NOP:
		memcpy (ret, "nop", 4);
		break;
	case R_ANAL_OP_TYPE_RET:
		memcpy (ret, "ret", 4);
		break;
	case R_ANAL_OP_TYPE_CRET:
		{
		RAnalBlock *bb = r_anal_bb_from_offset (anal, op->addr);
		if (bb) {
			cstr = r_anal_cond_to_string (bb->cond);
			snprintf (ret, sizeof (ret), "if (%s) ret", cstr);
			free (cstr);
		} else memcpy (ret, "if (unk) ret", 13);
		}
		break;
	case R_ANAL_OP_TYPE_LEAVE:
		memcpy (ret, "leave", 6);
		break;
	case R_ANAL_OP_TYPE_MOD:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "%s %%= %s", r0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s %% %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_XCHG:
		if (a1 == NULL || !strcmp (a0, a1))
			snprintf (ret, sizeof (ret), "tmp = %s; %s = %s; %s = tmp", r0, r0, a0, a0);
		else snprintf (ret, sizeof (ret), "%s = %s ^ %s", r0, a0, a1);
		break;
	case R_ANAL_OP_TYPE_ROL:
	case R_ANAL_OP_TYPE_ROR:
	case R_ANAL_OP_TYPE_SWITCH:
	case R_ANAL_OP_TYPE_CASE:
		eprintf ("Command not implemented.\n");
		free (r0);
		free (a0);
		free (a1);
		return NULL;
	default:
		free (r0);
		free (a0);
		free (a1);
		return NULL;
	}
	free (r0);
	free (a0);
	free (a1);
	return strdup (ret);
}
Esempio n. 10
0
xml_element* XMLRPC_to_xml_element_worker(XMLRPC_VALUE current_vector, XMLRPC_VALUE node, 
                                          XMLRPC_REQUEST_TYPE request_type, int depth) {
#define BUF_SIZE 512
   xml_element* root = NULL;
   if (node) {
      char buf[BUF_SIZE];
      XMLRPC_VALUE_TYPE type = XMLRPC_GetValueType(node);
      XMLRPC_VECTOR_TYPE vtype = XMLRPC_GetVectorType(node);
      xml_element* elem_val = xml_elem_new();

      /* special case for when root element is not an array */
      if (depth == 0 && 
          !(type == xmlrpc_vector && 
            vtype == xmlrpc_vector_array && 
            request_type == xmlrpc_request_call) ) {
         int bIsFault = (vtype == xmlrpc_vector_struct && XMLRPC_VectorGetValueWithID(node, ELEM_FAULTCODE));

         xml_element* next_el = XMLRPC_to_xml_element_worker(NULL, node, request_type, depth + 1);
         if (next_el) {
            Q_PushTail(&elem_val->children, next_el);
         }
         elem_val->name = strdup(bIsFault ? ELEM_FAULT : ELEM_PARAMS);
        }
        else {
         switch (type) {
            case xmlrpc_empty: //  treat null value as empty string in xmlrpc.
         case xmlrpc_string:
            elem_val->name = strdup(ELEM_STRING);
            simplestring_addn(&elem_val->text, XMLRPC_GetValueString(node), XMLRPC_GetValueStringLen(node));
            break;
         case xmlrpc_int:
            elem_val->name = strdup(ELEM_INT);
            snprintf(buf, BUF_SIZE, "%i", XMLRPC_GetValueInt(node));
            simplestring_add(&elem_val->text, buf);
            break;
         case xmlrpc_boolean:
            elem_val->name = strdup(ELEM_BOOLEAN);
            snprintf(buf, BUF_SIZE, "%i", XMLRPC_GetValueBoolean(node));
            simplestring_add(&elem_val->text, buf);
            break;
         case xmlrpc_double:
            elem_val->name = strdup(ELEM_DOUBLE);
            snprintf(buf, BUF_SIZE, "%f", XMLRPC_GetValueDouble(node));
            simplestring_add(&elem_val->text, buf);
            break;
         case xmlrpc_datetime:
            elem_val->name = strdup(ELEM_DATETIME);
            simplestring_add(&elem_val->text, XMLRPC_GetValueDateTime_ISO8601(node));
            break;
         case xmlrpc_base64:
            {
               struct buffer_st buf;
               elem_val->name = strdup(ELEM_BASE64);
               base64_encode(&buf, XMLRPC_GetValueBase64(node), XMLRPC_GetValueStringLen(node));
               simplestring_addn(&elem_val->text, buf.data, buf.offset );
               buffer_delete(&buf);
            }
            break;
         case xmlrpc_vector:
            {
               XMLRPC_VECTOR_TYPE my_type = XMLRPC_GetVectorType(node);
               XMLRPC_VALUE xIter = XMLRPC_VectorRewind(node);
               xml_element* root_vector_elem = elem_val;

               switch (my_type) {
               case xmlrpc_vector_array:
                  {
                      if(depth == 0) {
                         elem_val->name = strdup(ELEM_PARAMS);
                      }
                      else {
                         /* Hi my name is Dave and I like to make things as confusing
                          * as possible, thus I will throw in this 'data' element
                          * where it absolutely does not belong just so that people
                          * cannot code arrays and structs in a similar and straight
                          * forward manner. Have a good day.
                          *
                          * GRRRRRRRRR!
                          */
                         xml_element* data = xml_elem_new();
                         data->name = strdup(ELEM_DATA);
    
                         elem_val->name = strdup(ELEM_ARRAY);
                         Q_PushTail(&elem_val->children, data);
                         root_vector_elem = data;
                      }
                  }
                  break;
               case xmlrpc_vector_mixed:       /* not officially supported */
               case xmlrpc_vector_struct:
                  elem_val->name = strdup(ELEM_STRUCT);
                  break;
               default:
                  break;
               }

               /* recurse through sub-elements */
               while ( xIter ) {
                  xml_element* next_el = XMLRPC_to_xml_element_worker(node, xIter, request_type, depth + 1);
                  if (next_el) {
                     Q_PushTail(&root_vector_elem->children, next_el);
                  }
                  xIter = XMLRPC_VectorNext(node);
               }
            }
            break;
         default:
            break;
         }
      }

      {
         XMLRPC_VECTOR_TYPE vtype = XMLRPC_GetVectorType(current_vector);

         if (depth == 1) {
            xml_element* value = xml_elem_new();
            value->name = strdup(ELEM_VALUE);

            /* yet another hack for the "fault" crap */
            if (XMLRPC_VectorGetValueWithID(node, ELEM_FAULTCODE)) {
               root = value;
                }
                else {
               xml_element* param = xml_elem_new();
               param->name = strdup(ELEM_PARAM);

               Q_PushTail(&param->children, value);

               root = param;
            }
            Q_PushTail(&value->children, elem_val);
            }
            else if (vtype == xmlrpc_vector_struct || vtype == xmlrpc_vector_mixed) {
            xml_element* member = xml_elem_new();
            xml_element* name = xml_elem_new();
            xml_element* value = xml_elem_new();

            member->name = strdup(ELEM_MEMBER);
            name->name = strdup(ELEM_NAME);
            value->name = strdup(ELEM_VALUE);

            simplestring_add(&name->text, XMLRPC_GetValueID(node));

            Q_PushTail(&member->children, name);
            Q_PushTail(&member->children, value);
            Q_PushTail(&value->children, elem_val);

            root = member;
            }
            else if (vtype == xmlrpc_vector_array) {
            xml_element* value = xml_elem_new();

            value->name = strdup(ELEM_VALUE);

            Q_PushTail(&value->children, elem_val);

            root = value;
            }
            else if (vtype == xmlrpc_vector_none) {
            /* no parent.  non-op */
            root = elem_val;
            }
            else {
            xml_element* value = xml_elem_new();

            value->name = strdup(ELEM_VALUE);

            Q_PushTail(&value->children, elem_val);

            root = value;
         }
      }
   }
   return root;
}
Esempio n. 11
0
static void monitor_update(iterator_t *it, pthread_mutex_t *recv_ready_mutex)
{
	uint32_t total_sent = iterator_get_sent(it);
	if (last_now > 0.0) {
		double age = now() - zsend.start;
		double delta = now() - last_now;
		double remaining_secs = compute_remaining_time(age, total_sent);
		double percent_complete = 100.*age/(age + remaining_secs);


		// ask pcap for fresh values
		pthread_mutex_lock(recv_ready_mutex);
		recv_update_pcap_stats();
		pthread_mutex_unlock(recv_ready_mutex);

		// format times for display
		char time_left[20];
		if (age < 5) {
			time_left[0] = '\0';
		} else {
			char buf[20];
			time_string((int)remaining_secs, 1, buf, sizeof(buf));
			snprintf(time_left, sizeof(time_left), " (%s left)", buf);
		}
		char time_past[20];
		time_string((int)age, 0, time_past, sizeof(time_past));

		char send_rate[20], send_avg[20],
			 recv_rate[20], recv_avg[20],
			 pcap_drop[20], pcap_drop_avg[20];
		// recv stats
		number_string((zrecv.success_unique - last_rcvd)/delta,
						recv_rate, sizeof(recv_rate));
		number_string((zrecv.success_unique/age), recv_avg, sizeof(recv_avg));
		// dropped stats
		number_string((zrecv.pcap_drop + zrecv.pcap_ifdrop - last_drop)/delta,
						pcap_drop, sizeof(pcap_drop));
		number_string(((zrecv.pcap_drop + zrecv.pcap_ifdrop)/age),
						pcap_drop_avg, sizeof(pcap_drop_avg));

		// Warn if we drop > 5% of our average receive rate
		uint32_t drop_rate = (uint32_t)((zrecv.pcap_drop + zrecv.pcap_ifdrop - last_drop) / delta);
		if (drop_rate > (uint32_t)((zrecv.success_unique - last_rcvd) / delta) / 20) {
			log_warn("monitor", "Dropped %d packets in the last second, (%d total dropped (pcap: %d + iface: %d))",
					 drop_rate, zrecv.pcap_drop + zrecv.pcap_ifdrop, zrecv.pcap_drop, zrecv.pcap_ifdrop);
		}

		// Warn if we fail to send > 1% of our average send rate
		uint32_t fail_rate = (uint32_t)((zsend.sendto_failures - last_failures) / delta); // failures/sec
		if (fail_rate > ((total_sent / age) / 100)) {
			log_warn("monitor", "Failed to send %d packets/sec (%d total failures)",
					 fail_rate, zsend.sendto_failures);
		}
		float hits;
		if (!total_sent) {
			hits = 0;
		} else {
			hits = zrecv.success_unique*100./total_sent;
		}
		if (!zsend.complete) {
			// main display (during sending)
			number_string((total_sent - last_sent)/delta,
							send_rate, sizeof(send_rate));
			number_string((total_sent/age), send_avg, sizeof(send_avg));
			fprintf(stderr,
					"%5s %0.0f%%%s; send: %u %sp/s (%sp/s avg); "
					"recv: %u %sp/s (%sp/s avg); "
					"drops: %sp/s (%sp/s avg); "
					"hits: %0.2f%%\n",
					time_past,
					percent_complete,
					time_left,
					total_sent,
					send_rate,
					send_avg,
					zrecv.success_unique,
					recv_rate,
					recv_avg,
					pcap_drop,
					pcap_drop_avg,
					hits);
		} else {
		  	// alternate display (during cooldown)
			number_string((total_sent/(zsend.finish - zsend.start)), send_avg, sizeof(send_avg));
			fprintf(stderr,
					"%5s %0.0f%%%s; send: %u done (%sp/s avg); "
					"recv: %u %sp/s (%sp/s avg); "
					"drops: %sp/s (%sp/s avg); "
					"hits: %0.2f%%\n",
					time_past,
					percent_complete,
					time_left,
					total_sent,
					send_avg,
					zrecv.success_unique,
					recv_rate,
					recv_avg,
					pcap_drop,
					pcap_drop_avg,
					hits);
		}
	}
	last_now  = now();
	last_sent = total_sent;
	last_rcvd = zrecv.success_unique;
	last_drop = zrecv.pcap_drop + zrecv.pcap_ifdrop;
	last_failures = zsend.sendto_failures;
}
Esempio n. 12
0
int Create_Semaphore (const char *name, int ival)
{
//    struct Semaphore *pSem = 0, *pSemNew = NULL, sem;
    struct Semaphore *pSem;
    int id = 0;

//Print("ARGS. name: %s, ival: %d\n", name, ival);
    /*
     * Obtiene el primer elemento de la lista y lo
     * recorre hasta el final para ver que ID le asigna
     * al semáforo solicitado (poco eficiente).
     */
    pSem = Get_Front_Of_Semaphore_List(&s_semList);
//    Print("LISTA ARRANCA EN %p\n", pSem);
    while (pSem != 0) {
        KASSERT(pSem != Get_Next_In_Semaphore_List(pSem));
        if (strcmp(pSem->name, name) == 0) {
            pSem->nref++;
#ifdef DEBUG
            Print("Semaforo %s ya existe con id %d.\n", name, pSem->id);
#endif
            Print("Semaforo %s ya existe con id %d.\n", name, pSem->id);
            return pSem->id;
        }
        pSem = Get_Next_In_Semaphore_List(pSem);
        id++;
    }

    /* La cantidad máxima de semáforos está siendo utilizada. */
    if (id >= MAX_SEM)
        return -1;

	pSem = Malloc(sizeof (struct Semaphore));
//    Print("ANTES: ");
//    Dump_All_Semaphore_List();
//    sem.id = id;
    pSem->id = id;

    /* Define nombre del semáforo */
//    snprintf(sem.name, sizeof(sem.name), "%s", name);
    snprintf(pSem->name, NAMESIZE, "%s", name);

    /* Define valor inicial del semáforo */
//    sem.value = ival;
    pSem->value = ival;

    /* Referencia a 1 */
//    sem.nref = 1;
    pSem->nref = 1;

/*
	pSemNew = Malloc(sizeof (struct Semaphore));
	pSemNew = &sem;
*/

    /* Agrega semáforo a la lista */
//    Add_To_Back_Of_Semaphore_List(&s_semList, &sem);
//    Add_To_Back_Of_Semaphore_List(&s_semList, pSemNew);
    Add_To_Back_Of_Semaphore_List(&s_semList, pSem);
/*
    sem = Get_Front_Of_Semaphore_List(&s_semList);
    while (sem != NULL) {
        KASSERT(sem != Get_Next_In_Semaphore_List(sem));
        Print("ESTE ID ya esta: %d\n", sem->id);
        sem = Get_Next_In_Semaphore_List(sem);
    }

*/
    Print("DESPUES: ");
    Dump_All_Semaphore_List();
#ifdef DEBUG
    Print("ID: %d\n", id);
#endif
    return id;
}
Esempio n. 13
0
END_TEST

START_TEST(importdb_can_parse_exported_database)
{
	int i;
	char buffer[512];
	DATA filleddb;
	FILE *exportfile;

	initdb();
	strcpy(data.interface, "something");
	strcpy(data.nick, "nothing");
	data.totalrx = 1;
	data.totaltx = 2;
	data.currx = 3;
	data.curtx = 4;
	data.totalrxk = 5;
	data.totaltxk = 6;
	data.btime = 7;

	for (i=0; i<30; i++) {
		data.day[i].date = i+1;
		data.day[i].rx = data.day[i].tx = i*100;
		data.day[i].rxk = data.day[i].txk = i;
		data.day[i].used = 1;
	}

	for (i=0; i<10; i++) {
		data.top10[i].date = i+1;
		data.top10[i].rx = data.top10[i].tx = i*100;
		data.top10[i].rxk = data.top10[i].txk = i;
		data.top10[i].used = 1;
	}

	for (i=0; i<12; i++) {
		data.month[i].month = i+1;
		data.month[i].rx = data.month[i].tx = i*100;
		data.month[i].rxk = data.month[i].txk = i;
		data.month[i].used = 1;
	}

	for (i=0; i<24; i++) {
		data.hour[i].date = i+1;
		data.hour[i].rx = data.hour[i].tx = i*100;
	}

	memcpy(&filleddb, &data, sizeof(DATA));
	ck_assert_int_eq(remove_directory(TESTDIR), 1);
	ck_assert_int_eq(clean_testdbdir(), 1);

	fflush(stdout);
	snprintf(buffer, 512, "%s/dbexport", TESTDBDIR);
	exportfile = fopen(buffer, "w");
	dup2(fileno(exportfile), STDOUT_FILENO);
	fclose(exportfile);
	exportdb();
	fflush(stdout);
	memset(&data, '\0', sizeof(DATA));

	ck_assert_int_gt(importdb(buffer), 0);

	ck_assert_str_eq(data.interface, filleddb.interface);
	ck_assert_str_eq(data.nick, filleddb.nick);
	ck_assert_int_eq(data.version, filleddb.version);
	ck_assert_int_eq(data.active, filleddb.active);
	ck_assert_int_eq(data.totalrx, filleddb.totalrx);
	ck_assert_int_eq(data.totaltx, filleddb.totaltx);
	ck_assert_int_eq(data.currx, filleddb.currx);
	ck_assert_int_eq(data.curtx, filleddb.curtx);
	ck_assert_int_eq(data.totalrxk, filleddb.totalrxk);
	ck_assert_int_eq(data.totaltxk, filleddb.totaltxk);
	ck_assert_int_eq(data.btime, filleddb.btime);
	ck_assert_int_eq(data.created, filleddb.created);
	ck_assert_int_eq(data.lastupdated, filleddb.lastupdated);

	for (i=0; i<30; i++) {
		ck_assert_int_eq(data.day[i].date, filleddb.day[i].date);
		ck_assert_int_eq(data.day[i].rx, filleddb.day[i].rx);
		ck_assert_int_eq(data.day[i].tx, filleddb.day[i].tx);
		ck_assert_int_eq(data.day[i].rxk, filleddb.day[i].rxk);
		ck_assert_int_eq(data.day[i].txk, filleddb.day[i].txk);
		ck_assert_int_eq(data.day[i].used, filleddb.day[i].used);
	}

	for (i=0; i<10; i++) {
		ck_assert_int_eq(data.top10[i].date, filleddb.top10[i].date);
		ck_assert_int_eq(data.top10[i].rx, filleddb.top10[i].rx);
		ck_assert_int_eq(data.top10[i].tx, filleddb.top10[i].tx);
		ck_assert_int_eq(data.top10[i].rxk, filleddb.top10[i].rxk);
		ck_assert_int_eq(data.top10[i].txk, filleddb.top10[i].txk);
		ck_assert_int_eq(data.top10[i].used, filleddb.top10[i].used);
	}

	for (i=0; i<12; i++) {
		ck_assert_int_eq(data.month[i].month, filleddb.month[i].month);
		ck_assert_int_eq(data.month[i].rx, filleddb.month[i].rx);
		ck_assert_int_eq(data.month[i].tx, filleddb.month[i].tx);
		ck_assert_int_eq(data.month[i].rxk, filleddb.month[i].rxk);
		ck_assert_int_eq(data.month[i].txk, filleddb.month[i].txk);
		ck_assert_int_eq(data.month[i].used, filleddb.month[i].used);
	}

	for (i=0; i<24; i++) {
		ck_assert_int_eq(data.hour[i].date, filleddb.hour[i].date);
		ck_assert_int_eq(data.hour[i].rx, filleddb.hour[i].rx);
		ck_assert_int_eq(data.hour[i].tx, filleddb.hour[i].tx);
	}
}
Esempio n. 14
0
File: rpc.c Progetto: dyustc/searaft
int rpc_call(struct rpc_context *context, 
    const struct rpc_target *dest, const struct method_t *method, 
    rpc_callback client_cb, void *data) {

    //TODO: check the protocol in dest->proto and do http
    // request only if dest->proto == HTTP
    int res = 1;
    struct evhttp_connection *evcon = NULL;
    struct evhttp_request *req = NULL;
    char *json_method = NULL;
    struct client_rpc_callback_with_data *ctx = NULL;

    //TODO: can be make http_connection as part of peer_t?
    evcon = evhttp_connection_base_new(
        context->base, NULL, dest->host, dest->port);
    if (!evcon) {
        goto cleanup;
    }
    ctx = (struct client_rpc_callback_with_data *)malloc(
        sizeof(struct client_rpc_callback_with_data));
    if(!ctx) {
        goto cleanup;
    }
    ctx->cb = client_cb;
    ctx->data = data;
    ctx->evcon = evcon;

    req = evhttp_request_new(http_request_done, ctx);
    if (!req) {
        goto cleanup;
    }

    char uri[256]; 
    snprintf(uri, sizeof(uri)-1, "http://%s:%d/rpc", dest->host, dest->port);
    
    json_method  = serialize_method_call(method);
    if(!json_method) {
        goto cleanup;
    }

    struct evbuffer *output_buffer = evhttp_request_get_output_buffer(req);
    evbuffer_add(output_buffer, json_method, strlen(json_method));

    char content_length[20];
    snprintf(content_length, sizeof(content_length)-1, "%d", (int)strlen(json_method));

    struct evkeyvalq *output_headers = evhttp_request_get_output_headers(req);
    evhttp_add_header(output_headers, "Host", dest->host);
    evhttp_add_header(output_headers, "Connection", "close");
    evhttp_add_header(output_headers, "Content-Length", content_length);

    printf("Sending req %p with ctx = %p\n", req, ctx);
    int r = evhttp_make_request(evcon, req, EVHTTP_REQ_POST, uri);
    if(!r) {
        res = 0;
    }

cleanup:
    if(json_method)
        free(json_method);
    if(res && ctx)
        free(ctx);
    if(res && evcon)
        evhttp_connection_free(evcon);
    if(res && req)
        evhttp_request_free(req);

    return res;
}
Esempio n. 15
0
static void
outvol(struct cfent **eptlist, int eptnum, int part, int nparts)
{
	FILE	*fp;
	char	*svpt, *path, temp[PATH_MAX];
	int	i;


	if (nparts > 1)
		(void) fprintf(stderr, gettext(" -- part %2d:\n"), part);
	if (part == 1) {
		/* re-write pkgmap, but exclude local pathnames */
		(void) snprintf(temp, sizeof (temp), "%s/pkgmap", pkgloc);
		if ((fp = fopen(temp, "w")) == NULL) {
			progerr(gettext(ERR_TEMP), errno);
			quit(99);
		}
		(void) fprintf(fp, ": %d %ld\n", nparts, limit);
		for (i = 0; eptlist[i]; i++) {
			svpt = eptlist[i]->ainfo.local;
			if (!strchr("sl", eptlist[i]->ftype))
				eptlist[i]->ainfo.local = NULL;
			if (ppkgmap(eptlist[i], fp)) {
				progerr(gettext(ERR_TEMP), errno);
				quit(99);
			}
			eptlist[i]->ainfo.local = svpt;
		}
		(void) fclose(fp);
		(void) fprintf(stderr, "%s\n", temp);
	}

	(void) snprintf(temp, sizeof (temp), "%s/pkginfo", pkgloc);
	if (copyf(svept->ainfo.local, temp, svept->cinfo.modtime))
		quit(1);
	(void) fprintf(stderr, "%s\n", temp);

	for (i = 0; i < eptnum; i++) {
		if (eptlist[i]->volno != part)
			continue;
		if (strchr("dxslcbp", eptlist[i]->ftype))
			continue;
		if (eptlist[i]->ftype == 'i') {
			if (eptlist[i] == svept)
				continue; /* don't copy pkginfo file */
			(void) snprintf(temp, sizeof (temp),
				"%s/install/%s", pkgloc,
				eptlist[i]->path);
			path = temp;
		} else
			path = srcpath(pkgloc, eptlist[i]->path, part, nparts);
		if (sflag) {
			if (slinkf(eptlist[i]->ainfo.local, path))
				quit(1);
		} else if (copyf(eptlist[i]->ainfo.local, path,
				eptlist[i]->cinfo.modtime)) {
			quit(1);
		}

		/*
		 * If the package file attributes can be sync'd up with
		 * the pkgmap, we fix the attributes here.
		 */
		if (*(eptlist[i]->ainfo.owner) != '$' &&
		    *(eptlist[i]->ainfo.group) != '$' && getuid() == 0) {
			/* Clear dangerous bits. */
			eptlist[i]->ainfo.mode=
			    (eptlist[i]->ainfo.mode & S_IAMB);
			/*
			 * Make sure it can be read by the world and written
			 * by root.
			 */
			eptlist[i]->ainfo.mode |= 0644;
			if (!strchr("in", eptlist[i]->ftype)) {
				/* Set the safe attributes. */
				averify(1, &(eptlist[i]->ftype),
				    path, &(eptlist[i]->ainfo));
			}
		}

		(void) fprintf(stderr, "%s\n", path);
	}
}
Esempio n. 16
0
static int
netfilter_inject_linux(pcap_t *handle, const void *buf, size_t size)
{
	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on netfilter devices");
	return (-1);
}                           
Esempio n. 17
0
File: file.c Progetto: Ansud/xxl2tpd
struct iprange *set_range (char *word, char *value, struct iprange *in)
{
    char *c, *d = NULL, *e = NULL;
    struct iprange *ipr, *p;
    struct hostent *hp;
	int count = 0;
    c = strchr (value, '-');
    if (c)
    {
        d = c + 1;
        *c = 0;
        while ((c >= value) && (*c < 33))
            *(c--) = 0;
        while (*d && (*d < 33))
            d++;
    }
    if (!strlen (value) || (c && !strlen (d)))
    {
        snprintf (filerr, sizeof (filerr),
                  "format is '%s <host or ip> - <host or ip>'\n", word);
        return NULL;
    }
    ipr = (struct iprange *) malloc (sizeof (struct iprange));
    ipr->next = NULL;
    hp = gethostbyname (value);
    if (!hp)
    {
        snprintf (filerr, sizeof (filerr), "Unknown host %s\n", value);
        free (ipr);
        return NULL;
    }
    bcopy (hp->h_addr, &ipr->start, sizeof (unsigned int));
    if (c)
    {
		char ip_hi[16];

		e = d;
		while(*e != '\0') {
			if (*e++ == '.')
				count++;
		}
		if (count < 3) {
			strcpy(ip_hi, value);
			for (e = ip_hi + sizeof(ip_hi); e >= ip_hi; e--) {
				if (*e == '.') count--;
				if (count < 0) {
					e++;
					break;
				}
			}
			/* Copy the last field + null terminator */
			if (ip_hi + sizeof(ip_hi)-e > strlen(d)) {
				strcpy(e, d);
				d = ip_hi;
			}
		}
        hp = gethostbyname (d);
        if (!hp)
        {
            snprintf (filerr, sizeof (filerr), "Unknown host %s\n", d);
            free (ipr);
            return NULL;
        }
        bcopy (hp->h_addr, &ipr->end, sizeof (unsigned int));
    }
    else
        ipr->end = ipr->start;
    if (ntohl (ipr->start) > ntohl (ipr->end))
    {
        snprintf (filerr, sizeof (filerr), "start is greater than end!\n");
        free (ipr);
        return NULL;
    }
    if (word[0] == 'n')
        ipr->sense = SENSE_DENY;
    else
        ipr->sense = SENSE_ALLOW;
    p = in;
    if (p)
    {
        while (p->next)
            p = p->next;
        p->next = ipr;
        return in;
    }
    else
        return ipr;
}
Esempio n. 18
0
static int
nflog_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
{
	const unsigned char *buf;
	int count = 0;
	int len;

	/* ignore interrupt system call error */
	do {
		len = recv(handle->fd, handle->buffer, handle->bufsize, 0);
		if (handle->break_loop) {
			handle->break_loop = 0;
			return -2;
		}
	} while ((len == -1) && (errno == EINTR));

	if (len < 0) {
		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't receive packet %d:%s", errno, pcap_strerror(errno));
		return -1;
	}

	buf = handle->buffer;
	while (len >= NLMSG_SPACE(0)) {
		const struct nlmsghdr *nlh = (const struct nlmsghdr *) buf;
		u_int32_t msg_len;

		if (nlh->nlmsg_len < sizeof(struct nlmsghdr) || len < nlh->nlmsg_len) {
			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Message truncated: (got: %d) (nlmsg_len: %u)", len, nlh->nlmsg_len);
			return -1;
		}

		if (NFNL_SUBSYS_ID(nlh->nlmsg_type) == NFNL_SUBSYS_ULOG && 
			NFNL_MSG_TYPE(nlh->nlmsg_type) == NFULNL_MSG_PACKET) 
		{
			const unsigned char *payload = NULL;
			struct pcap_pkthdr pkth;

			if (handle->linktype != DLT_NFLOG) {
				const struct nfattr *payload_attr = NULL;

				if (nlh->nlmsg_len < HDR_LENGTH) {
					snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Malformed message: (nlmsg_len: %u)", nlh->nlmsg_len);
					return -1;
				}

				if (nlh->nlmsg_len > HDR_LENGTH) {
					struct nfattr *attr = NFM_NFA(NLMSG_DATA(nlh));
					int attr_len = nlh->nlmsg_len - NLMSG_ALIGN(HDR_LENGTH);

					while (NFA_OK(attr, attr_len)) {
						switch (NFA_TYPE(attr)) {
							case NFULA_PAYLOAD:
								payload_attr = attr;
								break;
						}
						attr = NFA_NEXT(attr, attr_len);
					}
				}

				if (payload_attr) {
					payload = NFA_DATA(payload_attr);
					pkth.len = pkth.caplen = NFA_PAYLOAD(payload_attr);
				}

			} else {
				payload = NLMSG_DATA(nlh);
				pkth.caplen = pkth.len = nlh->nlmsg_len-NLMSG_ALIGN(sizeof(struct nlmsghdr));
			}

			if (payload) {
				/* pkth.caplen = min (payload_len, handle->snapshot); */

				gettimeofday(&pkth.ts, NULL);
				if (handle->fcode.bf_insns == NULL ||
						bpf_filter(handle->fcode.bf_insns, payload, pkth.len, pkth.caplen)) 
				{
					handle->md.packets_read++;
					callback(user, &pkth, payload);
					count++;
				}
			}
		}

		msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
		if (msg_len > len)
			msg_len = len;

		len -= msg_len;
		buf += msg_len;
	}
	return count;
}
void get_ext_md_post_fix(int md_id, char buf[], char buf_ex[])
{
	// name format: modem_X_YYY_Z_Ex.img
	int		X, Ex;
	char		YYY[8];
#if defined(DFO_FEATURE_EN)
	unsigned int	feature_val = 0;
#endif

  if (md_id < MD_SYS5) {
    printk("[EEMCS]wrong MD ID to get postfix %d\n", md_id);
    return;
  }

	// X
	X = md_id + 1;

#if defined(DFO_FEATURE_EN)
	// DFO start -------------------
	// YYY
	YYY[0] = '\0';
	switch(md_id) {
  	case MD_SYS5:
  		feature_val = ext_md_support[MD_SYS5-MD_EXT1];
  		break;
  	default:
      printk("[EEMCS]request MD ID %d not supported\n", md_id);
  		break;
	}
	switch(feature_val) {
  	case modem_lwg:
  		snprintf(YYY, 8, "_lwg_n");
  		break;
  	case modem_ltg:
  		snprintf(YYY, 8, "_ltg_n");
  		break;
  	default:
  		printk("[EEMCS]request MD type %d not supported\n", feature_val);
  		break;
	}
	// DFO end ---------------------
#else
	// Static start -------------------
	// YYY
	snprintf(YYY, 8, "_lwg_n");
	// Static end ---------------------
#endif

	// [_Ex] Get chip version
#if 0
	if(get_chip_version() == CHIP_SW_VER_01)
		Ex = 1;
	else if(get_chip_version() == CHIP_SW_VER_02)
		Ex = 2;
#else
	Ex = 1;
#endif

	// Gen post fix
	if(buf) {
		snprintf(buf, 12, "%d%s", X, YYY);
    printk("[EEMCS]MD%d image postfix=%s\n", md_id, buf);
	}

	if(buf_ex) {
		snprintf(buf_ex, 12, "%d%s_E%d", X, YYY, Ex);
    printk("[EEMCS]MD%d image postfix=%s\n", md_id, buf_ex);
	}
}
Esempio n. 20
0
int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct group *gptr;
	const char *arg, *cp, *printer;
	char *p;
	char buf[BUFSIZ];
	int c, i, f, errs;
	int	 ret, didlink;
	struct stat stb;
	struct stat statb1, statb2;
	struct printer myprinter, *pp = &myprinter;

	printer = NULL;
	euid = geteuid();
	uid = getuid();
	PRIV_END
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, cleanup);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, cleanup);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, cleanup);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, cleanup);

	progname = argv[0];
	gethostname(local_host, sizeof(local_host));
	openlog("lpd", 0, LOG_LPR);

	errs = 0;
	while ((c = getopt(argc, argv,
			   ":#:1:2:3:4:C:J:L:P:T:U:Z:cdfghi:lnmprstvw:"))
	       != -1)
		switch (c) {
		case '#':		/* n copies */
			i = strtol(optarg, &p, 10);
			if (*p)
				errx(1, "Bad argument to -#, number expected");
			if (i > 0)
				ncopies = i;
			break;

		case '1':		/* troff fonts */
		case '2':
		case '3':
		case '4':
			fonts[optopt - '1'] = optarg;
			break;

		case 'C':		/* classification spec */
			hdr++;
			class = optarg;
			break;

		case 'J':		/* job name */
			hdr++;
			jobname = optarg;
			break;

		case 'P':		/* specifiy printer name */
			printer = optarg;
			break;

		case 'L':               /* pr's locale */
			locale = optarg;
			break;

		case 'T':		/* pr's title line */
			title = optarg;
			break;

		case 'U':		/* user name */
			hdr++;
			Uflag = optarg;
			break;

		case 'Z':
			Zflag = optarg;
			break;

		case 'c':		/* print cifplot output */
		case 'd':		/* print tex output (dvi files) */
		case 'g':		/* print graph(1G) output */
		case 'l':		/* literal output */
		case 'n':		/* print ditroff output */
		case 't':		/* print troff output (cat files) */
		case 'p':		/* print using ``pr'' */
		case 'v':		/* print vplot output */
			format = optopt;
			break;

		case 'f':		/* print fortran output */
			format = 'r';
			break;

		case 'h':		/* nulifiy header page */
			hdr = 0;
			break;

		case 'i':		/* indent output */
			iflag++;
			indent = strtol(optarg, &p, 10);
			if (*p)
				errx(1, "Bad argument to -i, number expected");
			break;

		case 'm':		/* send mail when done */
			mailflg++;
			break;

		case 'q':		/* just queue job */
			qflag++;
			break;

		case 'r':		/* remove file when done */
			rflag++;
			break;

		case 's':		/* try to link files */
			sflag++;
			break;

		case 'w':		/* versatec page width */
			width = optarg;
			break;

		case ':':		/* catch "missing argument" error */
			if (optopt == 'i') {
				iflag++; /* -i without args is valid */
				indent = 8;
			} else
				errs++;
			break;

		default:
			errs++;
		}
	argc -= optind;
	argv += optind;
	if (errs)
		usage();
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	chkprinter(printer, pp);
	if (pp->no_copies && ncopies > 1)
		errx(1, "multiple copies are not allowed");
	if (pp->max_copies > 0 && ncopies > pp->max_copies)
		errx(1, "only %ld copies are allowed", pp->max_copies);
	/*
	 * Get the identity of the person doing the lpr using the same
	 * algorithm as lprm.  Actually, not quite -- lprm will override
	 * the login name with "root" if the user is running as root;
	 * the daemon actually checks for the string "root" in its
	 * permission checking.  Sigh.
	 */
	userid = getuid();
	if (Uflag) {
		if (userid != 0 && userid != pp->daemon_user)
			errx(1, "only privileged users may use the `-U' flag");
		lpr_username = Uflag;		/* -U person doing 'lpr' */
	} else {
		lpr_username = getlogin();	/* person doing 'lpr' */
		if (userid != pp->daemon_user || lpr_username == 0) {
			if ((pw = getpwuid(userid)) == NULL)
				errx(1, "Who are you?");
			lpr_username = pw->pw_name;
		}
	}

	/*
	 * Check for restricted group access.
	 */
	if (pp->restrict_grp != NULL && userid != pp->daemon_user) {
		if ((gptr = getgrnam(pp->restrict_grp)) == NULL)
			errx(1, "Restricted group specified incorrectly");
		if (gptr->gr_gid != getgid()) {
			while (*gptr->gr_mem != NULL) {
				if ((strcmp(lpr_username, *gptr->gr_mem)) == 0)
					break;
				gptr->gr_mem++;
			}
			if (*gptr->gr_mem == NULL)
				errx(1, "Not a member of the restricted group");
		}
	}
	/*
	 * Check to make sure queuing is enabled if userid is not root.
	 */
	lock_file_name(pp, buf, sizeof buf);
	if (userid && stat(buf, &stb) == 0 && (stb.st_mode & LFM_QUEUE_DIS))
		errx(1, "Printer queue is disabled");
	/*
	 * Initialize the control file.
	 */
	mktemps(pp);
	tfd = nfile(tfname);
	PRIV_START
	(void) fchown(tfd, pp->daemon_user, -1);
	/* owned by daemon for protection */
	PRIV_END
	card('H', local_host);
	card('P', lpr_username);
	card('C', class);
	if (hdr && !pp->no_header) {
		if (jobname == NULL) {
			if (argc == 0)
				jobname = "stdin";
			else
				jobname = ((arg = strrchr(argv[0], '/'))
					   ? arg + 1 : argv[0]);
		}
		card('J', jobname);
		card('L', lpr_username);
	}
	if (format != 'p' && Zflag != 0)
		card('Z', Zflag);
	if (iflag)
		card('I', itoa(indent));
	if (mailflg)
		card('M', lpr_username);
	if (format == 't' || format == 'n' || format == 'd')
		for (i = 0; i < 4; i++)
			if (fonts[i] != NULL)
				card('1'+i, fonts[i]);
	if (width != NULL)
		card('W', width);
	/*
	 * XXX
	 * Our use of `Z' here is incompatible with LPRng's
	 * use.  We assume that the only use of our existing
	 * `Z' card is as shown for `p' format (pr) files.
	 */
	if (format == 'p') {
		char *s;

		if (locale)
			card('Z', locale);
		else if ((s = setlocale(LC_TIME, "")) != NULL)
			card('Z', s);
	}

	/*
	 * Read the files and spool them.
	 */
	if (argc == 0)
		copy(pp, 0, " ");
	else while (argc--) {
		if (argv[0][0] == '-' && argv[0][1] == '\0') {
			/* use stdin */
			copy(pp, 0, " ");
			argv++;
			continue;
		}
		if ((f = test(arg = *argv++)) < 0)
			continue;	/* file unreasonable */

		if (sflag && (cp = linked(arg)) != NULL) {
			(void)snprintf(buf, sizeof(buf), "%ju %ju",
			    (uintmax_t)statb.st_dev, (uintmax_t)statb.st_ino);
			card('S', buf);
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			if (f)
				card('U', cp);
			card('N', arg);
			dfname[inchar]++;
			nact++;
			continue;
		}
		if (sflag)
			printf("%s: %s: not linked, copying instead\n",
			    progname, arg);

		if (f) {
			/*
			 * The user wants the file removed after it is copied
			 * to the spool area, so see if the file can be moved
			 * instead of copy/unlink'ed.  This is much faster and
			 * uses less spool space than copying the file.  This
			 * can be very significant when running services like
			 * samba, pcnfs, CAP, et al.
			 */
			PRIV_START
			didlink = 0;
			/*
			 * There are several things to check to avoid any
			 * security issues.  Some of these are redundant
			 * under BSD's, but are necessary when lpr is built
			 * under some other OS's (which I do do...)
			 */
			if (lstat(arg, &statb1) < 0)
				goto nohardlink;
			if (S_ISLNK(statb1.st_mode))
				goto nohardlink;
			if (link(arg, dfname) != 0)
				goto nohardlink;
			didlink = 1;
			/*
			 * Make sure the user hasn't tried to trick us via
			 * any race conditions
			 */
			if (lstat(dfname, &statb2) < 0)
				goto nohardlink;
			if (statb1.st_dev != statb2.st_dev)
				goto nohardlink;
			if (statb1.st_ino != statb2.st_ino)
				goto nohardlink;
			/*
			 * Skip if the file already had multiple hard links,
			 * because changing the owner and access-bits would
			 * change ALL versions of the file
			 */
			if (statb2.st_nlink > 2)
				goto nohardlink;
			/*
			 * If we can access and remove the original file
			 * without special setuid-ness then this method is
			 * safe.  Otherwise, abandon the move and fall back
			 * to the (usual) copy method.
			 */
			PRIV_END
			ret = access(dfname, R_OK);
			if (ret == 0)
				ret = unlink(arg);
			PRIV_START
			if (ret != 0)
				goto nohardlink;
			/*
			 * Unlink of user file was successful.  Change the
			 * owner and permissions, add entries to the control
			 * file, and skip the file copying step.
			 */
			chown(dfname, pp->daemon_user, getegid());
			chmod(dfname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
			PRIV_END
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			card('N', arg);
			nact++;
			continue;
		nohardlink:
			if (didlink)
				unlink(dfname);
			PRIV_END           /* restore old uid */
		} /* end: if (f) */

		if ((i = open(arg, O_RDONLY)) < 0) {
			printf("%s: cannot open %s\n", progname, arg);
		} else {
			copy(pp, i, arg);
			(void) close(i);
			if (f && unlink(arg) < 0)
				printf("%s: %s: not removed\n", progname, arg);
		}
	}

	if (nact) {
		(void) close(tfd);
		tfname[inchar]--;
		/*
		 * Touch the control file to fix position in the queue.
		 */
		PRIV_START
		if ((tfd = open(tfname, O_RDWR)) >= 0) {
			char touch_c;

			if (read(tfd, &touch_c, 1) == 1 &&
			    lseek(tfd, (off_t)0, 0) == 0 &&
			    write(tfd, &touch_c, 1) != 1) {
				printf("%s: cannot touch %s\n", progname,
				    tfname);
				tfname[inchar]++;
				cleanup(0);
			}
			(void) close(tfd);
		}
		if (link(tfname, cfname) < 0) {
			printf("%s: cannot rename %s\n", progname, cfname);
			tfname[inchar]++;
			cleanup(0);
		}
		unlink(tfname);
		PRIV_END
		if (qflag)		/* just q things up */
			exit(0);
		if (!startdaemon(pp))
			printf("jobs queued, but cannot start daemon.\n");
		exit(0);
	}
	cleanup(0);
	return (1);
	/* NOTREACHED */
}
Esempio n. 21
0
static int dm5_dive(void *param, int columns, char **data, char **column)
{
	UNUSED(columns);
	UNUSED(column);
	int i;
	int tempformat = 0;
	int interval, retval = 0, block_size;
	struct parser_state *state = (struct parser_state *)param;
	sqlite3 *handle = state->sql_handle;
	unsigned const char *sampleBlob;
	char *err = NULL;
	char get_events_template[] = "select * from Mark where DiveId = %d";
	char get_tags_template[] = "select Text from DiveTag where DiveId = %d";
	char get_cylinders_template[] = "select * from DiveMixture where DiveId = %d";
	char get_gaschange_template[] = "select GasChangeTime,Oxygen,Helium from DiveGasChange join DiveMixture on DiveGasChange.DiveMixtureId=DiveMixture.DiveMixtureId where DiveId = %d";
	char get_events[512];

	dive_start(state);
	state->cur_dive->number = atoi(data[0]);

	state->cur_dive->when = (time_t)(atol(data[1]));
	if (data[2])
		utf8_string(data[2], &state->cur_dive->notes);

	if (data[3])
		state->cur_dive->duration.seconds = atoi(data[3]);
	if (data[15])
		state->cur_dive->dc.duration.seconds = atoi(data[15]);

	/*
	 * TODO: the deviceid hash should be calculated here.
	 */
	settings_start(state);
	dc_settings_start(state);
	if (data[4]) {
		utf8_string(data[4], &state->cur_settings.dc.serial_nr);
		state->cur_settings.dc.deviceid = atoi(data[4]);
	}
	if (data[5])
		utf8_string(data[5], &state->cur_settings.dc.model);

	dc_settings_end(state);
	settings_end(state);

	if (data[6])
		state->cur_dive->dc.maxdepth.mm = lrint(strtod_flags(data[6], NULL, 0) * 1000);
	if (data[8])
		state->cur_dive->dc.airtemp.mkelvin = C_to_mkelvin(atoi(data[8]));
	if (data[9])
		state->cur_dive->dc.watertemp.mkelvin = C_to_mkelvin(atoi(data[9]));

	if (data[4]) {
		state->cur_dive->dc.deviceid = atoi(data[4]);
	}
	if (data[5])
		utf8_string(data[5], &state->cur_dive->dc.model);

	snprintf(get_events, sizeof(get_events) - 1, get_cylinders_template, state->cur_dive->number);
	retval = sqlite3_exec(handle, get_events, &dm5_cylinders, state, &err);
	if (retval != SQLITE_OK) {
		fprintf(stderr, "%s", "Database query dm5_cylinders failed.\n");
		return 1;
	}

	if (data[14])
		state->cur_dive->dc.surface_pressure.mbar = (atoi(data[14]) / 100);

	interval = data[16] ? atoi(data[16]) : 0;

	/*
	 * sampleBlob[0]	version number, indicates the size of one sample
	 *
	 * Following ones describe single sample, bugs in interpretation of the binary blob are likely:
	 *
	 * sampleBlob[3]	depth
	 * sampleBlob[7-9]	pressure
	 * sampleBlob[11]	temperature - either full Celsius or float, might be different field for some version of DM
	 */

	sampleBlob = (unsigned const char *)data[24];

	if (sampleBlob) {
		switch (sampleBlob[0]) {
			case 1:
				// Log is converted from DM4 to DM5
				block_size = 16;
				break;
			case 2:
				block_size = 19;
				break;
			case 3:
				block_size = 23;
				break;
			case 4:
				// Temperature is stored in float
				tempformat = 1;
				block_size = 26;
				break;
			case 5:
				// Temperature is stored in float
				tempformat = 1;
				block_size = 30;
				break;
			default:
				block_size = 16;
				break;
		}
	}

	for (i = 0; interval && sampleBlob && i * interval < state->cur_dive->duration.seconds; i++) {
		float *depth = (float *)&sampleBlob[i * block_size + 3];
		int32_t pressure = (sampleBlob[i * block_size + 9] << 16) + (sampleBlob[i * block_size + 8] << 8) + sampleBlob[i * block_size + 7];

		sample_start(state);
		state->cur_sample->time.seconds = i * interval;
		state->cur_sample->depth.mm = lrintf(depth[0] * 1000.0f);

		if (tempformat == 1) {
			float *temp = (float *)&(sampleBlob[i * block_size + 11]);
			state->cur_sample->temperature.mkelvin = C_to_mkelvin(*temp);
		} else {
			if ((sampleBlob[i * block_size + 11]) != 0x7F) {
				state->cur_sample->temperature.mkelvin = C_to_mkelvin(sampleBlob[i * block_size + 11]);
			}
		}

		/*
		 * Limit cylinder pressures to somewhat sensible values
		 */
		if (pressure >= 0 && pressure < 350000)
			state->cur_sample->pressure[0].mbar = pressure;
		sample_end(state);
	}

	/*
	 * Log was converted from DM4, thus we need to parse the profile
	 * from DM4 format
	 */

	if (i == 0) {
		float *profileBlob;
		unsigned char *tempBlob;
		int *pressureBlob;

		profileBlob = (float *)data[17];
		tempBlob = (unsigned char *)data[18];
		pressureBlob = (int *)data[19];
		for (i = 0; interval && i * interval < state->cur_dive->duration.seconds; i++) {
			sample_start(state);
			state->cur_sample->time.seconds = i * interval;
			if (profileBlob)
				state->cur_sample->depth.mm = lrintf(profileBlob[i] * 1000.0f);
			else
				state->cur_sample->depth.mm = state->cur_dive->dc.maxdepth.mm;

			if (data[18] && data[18][0])
				state->cur_sample->temperature.mkelvin = C_to_mkelvin(tempBlob[i]);
			if (data[19] && data[19][0])
				state->cur_sample->pressure[0].mbar = pressureBlob[i];
			sample_end(state);
		}
	}

	snprintf(get_events, sizeof(get_events) - 1, get_gaschange_template, state->cur_dive->number);
	retval = sqlite3_exec(handle, get_events, &dm5_gaschange, state, &err);
	if (retval != SQLITE_OK) {
		fprintf(stderr, "%s", "Database query dm5_gaschange failed.\n");
		return 1;
	}

	snprintf(get_events, sizeof(get_events) - 1, get_events_template, state->cur_dive->number);
	retval = sqlite3_exec(handle, get_events, &dm4_events, state, &err);
	if (retval != SQLITE_OK) {
		fprintf(stderr, "%s", "Database query dm4_events failed.\n");
		return 1;
	}

	snprintf(get_events, sizeof(get_events) - 1, get_tags_template, state->cur_dive->number);
	retval = sqlite3_exec(handle, get_events, &dm4_tags, state, &err);
	if (retval != SQLITE_OK) {
		fprintf(stderr, "%s", "Database query dm4_tags failed.\n");
		return 1;
	}

	dive_end(state);

	return SQLITE_OK;
}
Esempio n. 22
0
static int recv_fd(int c)
{
    int fd;
    uint8_t msgbuf[CMSG_SPACE(sizeof(fd))];
    struct msghdr msg = {
        .msg_control = msgbuf,
        .msg_controllen = sizeof(msgbuf),
    };
    struct cmsghdr *cmsg;
    struct iovec iov;
    uint8_t req[1];
    ssize_t len;

    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
    msg.msg_controllen = cmsg->cmsg_len;

    iov.iov_base = req;
    iov.iov_len = sizeof(req);

    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    len = recvmsg(c, &msg, 0);
    if (len > 0) {
        memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
        return fd;
    }

    return len;
}

static int net_bridge_run_helper(const char *helper, const char *bridge,
                                 Error **errp)
{
    sigset_t oldmask, mask;
    int pid, status;
    char *args[5];
    char **parg;
    int sv[2];

    sigemptyset(&mask);
    sigaddset(&mask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &mask, &oldmask);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        error_setg_errno(errp, errno, "socketpair() failed");
        return -1;
    }

    /* try to launch bridge helper */
    pid = fork();
    if (pid < 0) {
        error_setg_errno(errp, errno, "Can't fork bridge helper");
        return -1;
    }
    if (pid == 0) {
        int open_max = sysconf(_SC_OPEN_MAX), i;
        char fd_buf[6+10];
        char br_buf[6+IFNAMSIZ] = {0};
        char helper_cmd[PATH_MAX + sizeof(fd_buf) + sizeof(br_buf) + 15];

        for (i = 3; i < open_max; i++) {
            if (i != sv[1]) {
                close(i);
            }
        }

        snprintf(fd_buf, sizeof(fd_buf), "%s%d", "--fd=", sv[1]);

        if (strrchr(helper, ' ') || strrchr(helper, '\t')) {
            /* assume helper is a command */

            if (strstr(helper, "--br=") == NULL) {
                snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);
            }

            snprintf(helper_cmd, sizeof(helper_cmd), "%s %s %s %s",
                     helper, "--use-vnet", fd_buf, br_buf);

            parg = args;
            *parg++ = (char *)"sh";
            *parg++ = (char *)"-c";
            *parg++ = helper_cmd;
            *parg++ = NULL;

            execv("/bin/sh", args);
        } else {
            /* assume helper is just the executable path name */

            snprintf(br_buf, sizeof(br_buf), "%s%s", "--br=", bridge);

            parg = args;
            *parg++ = (char *)helper;
            *parg++ = (char *)"--use-vnet";
            *parg++ = fd_buf;
            *parg++ = br_buf;
            *parg++ = NULL;

            execv(helper, args);
        }
        _exit(1);

    } else {
        int fd;
        int saved_errno;

        close(sv[1]);

        do {
            fd = recv_fd(sv[0]);
        } while (fd == -1 && errno == EINTR);
        saved_errno = errno;

        close(sv[0]);

        while (waitpid(pid, &status, 0) != pid) {
            /* loop */
        }
        sigprocmask(SIG_SETMASK, &oldmask, NULL);
        if (fd < 0) {
            error_setg_errno(errp, saved_errno,
                             "failed to recv file descriptor");
            return -1;
        }
        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
            error_setg(errp, "bridge helper failed");
            return -1;
        }
        return fd;
    }
}
void CGPS9_00HandleEvents(t_CgpsEventInformation* pp_EventInfo)
{
    uint8_t   vl_CharactersWritten = 0;
    uint8_t   vl_CheckSum          = 0;
    char vl_NmeaBuffer[K_CGPS_MAX_NMEA_SIZE];
    /*++  For adding newline at the end of PSTE messages */
    char vl_PsteBuffer[K_CGPS_MAX_NMEA_SIZE];
    /*--  For adding newline at the end of PSTE messages */

/* + LMSQC19754 */
    /*The transview tool expects the PSTE messages to have a timestamp that is in resolution of 4ms*/
    uint32_t  vl_timer             = (uint32_t)GN_GPS_Get_OS_Time_ms() / 4;
/*    uint32_t  vl_timer             = GN_GPS_Get_OS_Time_ms(); */
/* - LMSQC19754 */

    vl_CharactersWritten = snprintf(vl_NmeaBuffer, K_CGPS_MAX_NMEA_SIZE, "$PSTE,");

    switch( pp_EventInfo->v_EventType )
    {
        case K_CGPS_RESPONSE_RETURNED:
            vl_CharactersWritten += MC_CGPS_ADD_PSTE_TYPE(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten, 4);  /* Pste type */
            vl_CharactersWritten += MC_CGPS_ADD_OS_TIME  (vl_NmeaBuffer+vl_CharactersWritten, vl_timer, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);                /*OS time*/
            vl_CharactersWritten += MC_CGPS_ADD_SEPERATOR(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);                          /* , */
            vl_CharactersWritten += MC_CGPS_ADD_LATLON(vl_NmeaBuffer+vl_CharactersWritten, pp_EventInfo->v_Latitude, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);/*Latitude*/
            vl_CharactersWritten += MC_CGPS_ADD_SEPERATOR(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);                          /* , */
            vl_CharactersWritten += MC_CGPS_ADD_LATLON  (vl_NmeaBuffer+vl_CharactersWritten, pp_EventInfo->v_Longitude, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);/*Longitude*/
            vl_CharactersWritten += MC_CGPS_ADD_SEPERATOR(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);                          /* , */
            vl_CharactersWritten += MC_CGPS_ADD_ALT  (vl_NmeaBuffer+vl_CharactersWritten, pp_EventInfo->v_Altitude, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);/*Altitude*/
            vl_CharactersWritten += MC_CGPS_ADD_EOM      (vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);                          /* * */
        break;

        case K_CGPS_POSITIONING_SESSION_START:
            vl_CharactersWritten += MC_CGPS_ADD_PSTE_TYPE(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten, 1);
            vl_CharactersWritten += MC_CGPS_ADD_OS_TIME  (vl_NmeaBuffer+vl_CharactersWritten, vl_timer, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);
            vl_CharactersWritten += MC_CGPS_ADD_EOM      (vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);
        break;

        case K_CGPS_POSITIONING_SESSION_END:
            vl_CharactersWritten += MC_CGPS_ADD_PSTE_TYPE(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten, 2);
            vl_CharactersWritten += MC_CGPS_ADD_OS_TIME  (vl_NmeaBuffer+vl_CharactersWritten, vl_timer, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);
            vl_CharactersWritten += MC_CGPS_ADD_EOM      (vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);
        break;

/* + LMSQC19754 */
        case K_CGPS_ABORT_SESSION:
            vl_CharactersWritten += MC_CGPS_ADD_PSTE_TYPE(vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten, 3);
            vl_CharactersWritten += MC_CGPS_ADD_OS_TIME  (vl_NmeaBuffer+vl_CharactersWritten, vl_timer, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);
            vl_CharactersWritten += MC_CGPS_ADD_EOM      (vl_NmeaBuffer+vl_CharactersWritten, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);
        break;
/* - LMSQC19754 */

        default:
        break;
    }

    vl_CheckSum = CGPS9_01GenerateCheckSum(vl_NmeaBuffer, strlen((const char*)vl_NmeaBuffer));

    vl_CharactersWritten += MC_CGPS_ADD_CS (vl_NmeaBuffer+vl_CharactersWritten, vl_CheckSum, K_CGPS_MAX_NMEA_SIZE-vl_CharactersWritten);

    MC_CGPS_TRACE(("%s", vl_NmeaBuffer));

    sprintf(vl_PsteBuffer,"%s\r\n",vl_NmeaBuffer);
/*--  For adding newline at the end of PSTE messages */
    if( vg_CgpsTestall.p_Callback != NULL  )
    {
        t_cgps_NavData vl_NavDataToSend;

        vl_NavDataToSend.v_Type    = K_CGPS_NMEA;
        vl_NavDataToSend.v_Length  = vl_CharactersWritten;
        vl_NavDataToSend.p_NavData = vl_NmeaBuffer;
        /*++  For adding newline at the end of PSTE messages */
        sprintf(vl_PsteBuffer,"%s\r\n",vl_NavDataToSend.p_NavData);
        vl_NavDataToSend.v_Length  += 2;
        vl_NavDataToSend.p_NavData = vl_PsteBuffer;
        MC_CGPS_TRACE(("In CGPS9_00HandleEvents calling p_Callback"));

        (vg_CgpsTestall.p_Callback)( vl_NavDataToSend );
    /*--  For adding newline at the end of PSTE messages */
    }
    /* + DUR 19 Jan 2011 NMEA Logging */
       CGPS4_11SendAcknowledge(vl_PsteBuffer);
    /* - DUR 19 Jan 2011 NMEA Logging */
}
Esempio n. 24
0
static void net_init_tap_one(const NetdevTapOptions *tap, NetClientState *peer,
                             const char *model, const char *name,
                             const char *ifname, const char *script,
                             const char *downscript, const char *vhostfdname,
                             int vnet_hdr, int fd, Error **errp)
{
    Error *err = NULL;
    TAPState *s = net_tap_fd_init(peer, model, name, fd, vnet_hdr);
    int vhostfd;

    tap_set_sndbuf(s->fd, tap, &err);
    if (err) {
        error_propagate(errp, err);
        return;
    }

    if (tap->has_fd || tap->has_fds) {
        snprintf(s->nc.info_str, sizeof(s->nc.info_str), "fd=%d", fd);
    } else if (tap->has_helper) {
        snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s",
                 tap->helper);
    } else {
        snprintf(s->nc.info_str, sizeof(s->nc.info_str),
                 "ifname=%s,script=%s,downscript=%s", ifname, script,
                 downscript);

        if (strcmp(downscript, "no") != 0) {
            snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);
            snprintf(s->down_script_arg, sizeof(s->down_script_arg),
                     "%s", ifname);
        }
    }

    if (tap->has_vhost ? tap->vhost :
        vhostfdname || (tap->has_vhostforce && tap->vhostforce)) {
        VhostNetOptions options;

        options.backend_type = VHOST_BACKEND_TYPE_KERNEL;
        options.net_backend = &s->nc;
        if (tap->has_poll_us) {
            options.busyloop_timeout = tap->poll_us;
        } else {
            options.busyloop_timeout = 0;
        }

        if (vhostfdname) {
            vhostfd = monitor_fd_param(cur_mon, vhostfdname, &err);
            if (vhostfd == -1) {
                error_propagate(errp, err);
                return;
            }
        } else {
            vhostfd = open("/dev/vhost-net", O_RDWR);
            if (vhostfd < 0) {
                error_setg_errno(errp, errno,
                                 "tap: open vhost char device failed");
                return;
            }
        }
        options.opaque = (void *)(uintptr_t)vhostfd;

        s->vhost_net = vhost_net_init(&options);
        if (!s->vhost_net) {
            error_setg(errp,
                       "vhost-net requested but could not be initialized");
            return;
        }
    } else if (vhostfdname) {
        error_setg(errp, "vhostfd(s)= is not valid without vhost");
    }
}
Esempio n. 25
0
File: vz.c Progetto: OpenVZ/libvzctl
int vzctl2_env_unreg(struct vzctl_env_handle *h, int flags)
{
	char buf[STR_SIZE];
	char host[STR_SIZE];
	int ret;
	const char *ve_root;
	const char *ve_private = h->env_param->fs->ve_private;

	/* preserve compatibility
	 * VZ_REG_SKIP_HA_CLUSTER is alias for VZ_REG_SKIP_CLUSTER
	 */
	if (flags & VZ_REG_SKIP_HA_CLUSTER)
		flags |= VZ_REG_SKIP_CLUSTER;

	if (is_env_run(h))
		return vzctl_err(VZCTL_E_ENV_RUN, 0,
			"Container is running, Stop Container before proceeding.");

	if (access(ve_private, F_OK) && errno == ENOENT) {
		ret = unregister_env_conf(h);
		if (ret)
			return ret;
		goto out;
	}

	if (vzctl2_env_layout_version(ve_private) < VZCTL_LAYOUT_4)
		return 0;

	ret = vzctl_check_owner_quiet(ve_private, buf, sizeof(buf), host, sizeof(host));
	if (ret == VZCTL_E_ENV_MANAGE_DISABLED) {
		logger(0, 0, "Owner check failed on the server '%s':"
				" Container (%s) is registered for '%s'",
				buf, ve_private, host);
		ret = unregister_env_conf(h);
		if (ret)
			return ret;
		goto out;
	} else if (ret)
		return ret;

	ve_root = h->env_param->fs->ve_root;
	if (ve_root != NULL && vzctl2_env_is_mounted(h) == 1) {
		if (vzctl2_env_umount(h, 0))
			return vzctl_err(VZCTL_E_FS_MOUNTED, 0,
				"Container is mounted, Unmount Container "
				"before proceeding.");
	}

	if (!(flags & VZ_UNREG_PRESERVE)) {
		/* Remove VEID from /ve_private/ve.conf */
		vzctl2_env_set_param(h, "VEID", NULL);
		if (vzctl2_env_save(h))
			return VZCTL_E_UNREGISTER;

		/* Remove VE_PRIVATE/.owner */
		snprintf(buf, sizeof(buf), "%s/" VZCTL_VE_OWNER, ve_private);
		unlink(buf);
	}

	/* cleanup name */
	if (h->env_param->name->name != NULL) {
		char name_path[PATH_MAX];
		char veconf[PATH_MAX];

		snprintf(veconf, sizeof(veconf), "%s/" VZCTL_VE_CONF, ve_private);
		snprintf(name_path, sizeof(name_path), ENV_NAME_DIR "%s",
				h->env_param->name->name);
		if (is_same_file(name_path, veconf))
			unlink(name_path);
	}

	/* Remove /etc/vz/conf/VEID.conf */
	unregister_env_conf(h);

	if (!(flags & VZ_REG_SKIP_CLUSTER) &&
			is_shared_fs(ve_private) &&
			shaman_del_resource(EID(h)))
		logger(0, 0,"Warning: Failed to unregister the Container on HA cluster");

out:
	vzctl2_destroy_net_stat(h, 0);
	vzctl2_send_state_evt(EID(h), VZCTL_ENV_UNREGISTERED);
	logger(0, 0, "Container unregistered succesfully");

	return 0;
}
socket_t
htsp_tcp_connect_addr(struct addrinfo* addr, char *errbuf, size_t errbufsize,
	    int timeout)
{
  socket_t fd;
  int r, err, val;
  socklen_t errlen = sizeof(int);

  fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
  if(fd == -1) {
    snprintf(errbuf, errbufsize, "Unable to create socket: %s",
	     strerror(WSAGetLastError()));
    return -1;
  }

  /**
   * Switch to nonblocking
   */
  val = 1;
  ioctlsocket(fd, FIONBIO, &val);

  r = connect(fd, addr->ai_addr, addr->ai_addrlen);

  if(r == -1) {
    if(WSAGetLastError() == EINPROGRESS ||
       WSAGetLastError() == EAGAIN) {
      fd_set fd_write, fd_except;
      struct timeval tv;

      tv.tv_sec  =         timeout / 1000;
      tv.tv_usec = 1000 * (timeout % 1000);

      FD_ZERO(&fd_write);
      FD_ZERO(&fd_except);

      FD_SET(fd, &fd_write);
      FD_SET(fd, &fd_except);

      r = select((int)fd+1, NULL, &fd_write, &fd_except, &tv);

      if(r == 0) {
        /* Timeout */
        snprintf(errbuf, errbufsize, "Connection attempt timed out");
        closesocket(fd);
        return -1;
      }

      if(r == -1) {
        snprintf(errbuf, errbufsize, "select() error: %s", strerror(WSAGetLastError()));
        closesocket(fd);
        return -1;
      }

      getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen);
    } else {
      err = WSAGetLastError();
    }
  } else {
    err = 0;
  }

  if(err != 0) {
    snprintf(errbuf, errbufsize, "%s", strerror(err));
    closesocket(fd);
    return -1;
  }

  val = 0;
  ioctlsocket(fd, FIONBIO, &val);

  val = 1;
  setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&val, sizeof(val));

  return fd;
}
Esempio n. 27
0
File: vz.c Progetto: OpenVZ/libvzctl
int vzctl2_get_free_envid(unsigned *neweid, const char *dst,
		const char *unused)
{
	int i;
	struct vzctl_conf_simple conf;
	char file[STR_SIZE];
	char lckfile[STR_SIZE];
	char dstlck[PATH_MAX];
	struct stat st;
	int check_ve_private = 0;
	int check_ve_root = 0;
	int check_dst = 0;
	int fail_cnt = 0;
	int fd;
	ctid_t ctid = {};

	vzctl_parse_conf_simple(ctid, GLOBAL_CFG, &conf);

	if (conf.ve_private_orig != NULL && strstr(conf.ve_private_orig, "$VEID"))
		check_ve_private = 1;
	if (conf.ve_root_orig != NULL && strstr(conf.ve_root_orig, "$VEID"))
		check_ve_root = 1;
	if (dst != NULL && strstr(dst, "$VEID")) {
		snprintf(dstlck, sizeof(dstlck), "%s.lck", dst);
		check_dst = 1;
	}

	*neweid = 0;
	for (i = START_ID; i < INT_MAX/2 && fail_cnt < GET_FREE_ENVID_FAIL_MAX; i++) {
		ctid_t ctid = {i, };
		/* Check for VEID.conf */
		vzctl2_get_env_conf_path(ctid, file, sizeof(file));
		if (lstat(file, &st)) {
			if (errno != ENOENT) {
				logger(-1, errno, "Failed to stat %s", file);
				fail_cnt++;
				continue;
			}
		} else
			continue;
		/* lock envid */
		snprintf(lckfile, sizeof(lckfile), "%s.lck", file);
		fd = open(lckfile, O_CREAT|O_EXCL, 0644);
		if (fd == -1) {
			if (errno != EEXIST) {
				fail_cnt++;
				logger(-1, errno, "Failed to create %s", lckfile);
			}
			continue;
		}
		close(fd);

		/* check if PATH(s) exist */
		if ((check_ve_private && !is_dst_free(conf.ve_private_orig, ctid, &fail_cnt)) ||
		    (check_ve_root && !is_dst_free(conf.ve_root_orig, ctid, &fail_cnt)) ||
		    (check_dst &&
			(!is_dst_free(dst, ctid, &fail_cnt) || !is_dst_free(dstlck, ctid, &fail_cnt))))
		{
			/* unlock envid */
			unlink(lckfile);
			continue;
		}
		*neweid = i;
		break;
	}
	vzctl_free_conf_simple(&conf);

	if (*neweid == 0)
		return vzctl_err(-1, 0,  "Failed to get unused Countainer id");

	return 0;
}
Esempio n. 28
0
int
main(int argc, char *argv[])
{
	struct utsname utsbuf;
	struct statvfs64 svfsb;
	struct cfent	**eptlist;
	FILE	*fp;
	VFP_T	*vfp;
	int	i, c, n, eptnum, found,
		part, nparts, npkgs, objects;
	char	buf[MAX_PKG_PARAM_LENGTH];
	char	temp[MAX_PKG_PARAM_LENGTH];
	char	param[MAX_PKG_PARAM_LENGTH];
	char	*pt, *value, *pkginst, *tmpdir, *abi_sym_ptr,
		**cmdparam;
	char	*pkgname;
	char	*pkgvers;
	char	*pkgarch;
	char	*pkgcat;
	void	(*func)();
	time_t	clock;
	fsblkcnt_t	bsize = 0;
	fsblkcnt_t	frsize = 0;
	struct cl_attr	**allclass = NULL;
	struct cl_attr	**order;

	/* initialize locale environment */

	(void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);

	/* initialize program name */

	(void) set_prog_name(argv[0]);

	/* tell spmi zones interface how to access package output functions */

	z_set_output_functions(echo, echoDebug, progerr);

	func = sigset(SIGINT, trap);
	if (func != SIG_DFL)
		func = sigset(SIGINT, func);
	func = sigset(SIGHUP, trap);
	setmapmode(MAPBUILD);	/* variable binding */
	if (func != SIG_DFL)
		func = sigset(SIGHUP, func);

	environ = NULL;
	while ((c = getopt(argc, argv, "osnp:l:r:b:d:f:a:v:?")) != EOF) {
		switch (c) {
		    case 'n':
			nflag++;
			break;

		    case 's':
			sflag++;
			break;

		    case 'o':
			overwrite++;
			break;

		    case 'p':
			putparam("PSTAMP", optarg);
			break;

		    case 'l':
			llimit = atol(optarg);
			break;

		    case 'r':
			pt = strtok(optarg, " \t\n, ");
			n = 0;
			do {
				rootlist[n++] = flex_device(pt, 0);
				if (n >= NROOT) {
					progerr(gettext(ERR_NROOT), NROOT);
					quit(1);
				}
			} while (pt = strtok(NULL, " \t\n, "));
			rootlist[n] = NULL;
			break;

		    case 'b':
			basedir = optarg;
			break;

		    case 'f':
			protofile = optarg;
			break;

		    case 'd':
			device = flex_device(optarg, 1);
			break;

		    case 'a':
			putparam("ARCH", optarg);
			break;

		    case 'v':
			putparam("VERSION", optarg);
			break;

		    default:
			usage();
		}
	}

	/*
	 * Store command line variable assignments for later
	 * incorporation into the environment.
	 */
	cmdparam = &argv[optind];

	/* Skip past equates. */
	while (argv[optind] && strchr(argv[optind], '='))
		optind++;

	/* Confirm that the instance name is valid */
	if ((pkginst = argv[optind]) != NULL) {
		if (pkgnmchk(pkginst, "all", 0)) {
			progerr(gettext(ERR_PKGINST), pkginst);
			quit(1);
		}
		argv[optind++] = NULL;
	}
	if (optind != argc)
		usage();

	tmpdir = getenv("TMPDIR");
	if (tmpdir == NULL)
		tmpdir = P_tmpdir;

	/* bug id 4244631, not ABI compliant */
	abi_sym_ptr = getenv("PKG_NONABI_SYMLINKS");
	if (abi_sym_ptr && (strncasecmp(abi_sym_ptr, "TRUE", 4) == 0)) {
		set_nonABI_symlinks();
	}

	if (device == NULL) {
		device = devattr(SPOOLDEV, "pathname");
		if (device == NULL) {
			progerr(gettext(ERR_DEVICE), SPOOLDEV);
			exit(99);
		}
	}

	if (protofile == NULL) {
		if (access("prototype", 0) == 0)
			protofile = "prototype";
		else if (access("Prototype", 0) == 0)
			protofile = "Prototype";
		else {
			progerr(gettext(ERR_PROTOTYPE));
			quit(1);
		}
	}

	if (devtype(device, &pkgdev)) {
		progerr(gettext(ERR_BADDEV), device);
		quit(1);
	}
	if (pkgdev.norewind) {
		/* initialize datastream */
		progerr(gettext(ERR_DSTREAM), device);
		quit(1);
	}
	if (pkgdev.mount) {
		if (n = pkgmount(&pkgdev, NULL, 0, 0, 1))
			quit(n);
	}

	/*
	 * convert prototype file to a pkgmap, while locating
	 * package objects in the current environment
	 */
	t_pkgmap = tempnam(tmpdir, "tmpmap");
	if (t_pkgmap == NULL) {
		progerr(gettext(ERR_TEMP), errno);
		exit(99);
	}

	(void) fprintf(stderr, gettext(MSG_PROTOTYPE));
	if (n = mkpkgmap(t_pkgmap, protofile, cmdparam)) {
		progerr(gettext(ERR_BUILD));
		quit(1);
	}

	setmapmode(MAPNONE);	/* All appropriate variables are now bound */

	if (vfpOpen(&vfp, t_pkgmap, "r", VFP_NEEDNOW) != 0) {
		progerr(gettext(ERR_TEMP), errno);
		quit(99);
	}

	eptlist = procmap(vfp, 0, NULL);

	if (eptlist == NULL) {
		quit(1);
	}

	(void) vfpClose(&vfp);

	/* Validate the zone attributes in pkginfo, before creation */
	if (!valid_zone_attr(eptlist)) {
		progerr(ERR_PKGINFO_INVALID_OPTION_COMB);
		quit(1);
	}

	(void) fprintf(stderr, gettext(MSG_PKGINFO));
	pt = NULL;
	for (i = 0; eptlist[i]; i++) {
		ckmissing(eptlist[i]->path, eptlist[i]->ftype);
		if (eptlist[i]->ftype != 'i')
			continue;
		if (strcmp(eptlist[i]->path, "pkginfo") == 0)
			svept = eptlist[i];
	}
	if (svept == NULL) {
		progerr(gettext(ERR_NOPKGINFO));
		quit(99);
	}
	eptnum = i;

	/*
	 * process all parameters from the pkginfo file
	 * and place them in the execution environment
	 */

	if ((fp = fopen(svept->ainfo.local, "r")) == NULL) {
		progerr(gettext(ERR_RDPKGINFO), svept->ainfo.local);
		quit(99);
	}
	param[0] = '\0';
	while (value = fpkgparam(fp, param)) {
		if (getenv(param) == NULL)
			putparam(param, value);
		free((void *)value);
		param[0] = '\0';
	}
	(void) fclose(fp);

	/* add command line variables */
	while (*cmdparam && (value = strchr(*cmdparam, '=')) != NULL) {
		*value = NULL;	/* terminate the parameter */
		value++;	/* value is now the value (not '=') */
		putparam(*cmdparam++, value);  /* store it in environ */
	}

	/* make sure parameters are valid */
	(void) time(&clock);
	if (pt = getenv("PKG")) {
		if (pkgnmchk(pt, NULL, 0) || strchr(pt, '.')) {
			progerr(gettext(ERR_PKGABRV), pt);
			quit(1);
		}
		if (pkginst == NULL)
			pkginst = pt;
	} else {
		progerr(gettext(ERR_NOPARAM), "PKG", svept->path);
		quit(1);
	}
	/*
	 * verify consistency between PKG parameter and pkginst
	 */
	(void) snprintf(param, sizeof (param), "%s.*", pt);
	if (pkgnmchk(pkginst, param, 0)) {
		progerr(gettext(ERR_PKGMTCH), pt, pkginst);
		quit(1);
	}

	/*
	 * *********************************************************************
	 * this feature is removed starting with Solaris 10 - there is no built
	 * in list of packages that should be run "the old way"
	 * *********************************************************************
	 */

#ifdef	ALLOW_EXCEPTION_PKG_LIST
	/* Until 2.9, set it from the execption list */
	if (exception_pkg(pkginst, LINK))
		set_nonABI_symlinks();
#endif

	if ((pkgname = getenv("NAME")) == NULL) {
		progerr(gettext(ERR_NOPARAM), "NAME", svept->path);
		quit(1);
	}
	if (ckparam("NAME", pkgname))
		quit(1);
	if ((pkgvers = getenv("VERSION")) == NULL) {
		/* XXX - I18n */
		/* LINTED do not use cftime(); use strftime instead */
		(void) cftime(buf, "\045m/\045d/\045Y", &clock);
		(void) snprintf(temp, sizeof (temp),
			gettext("Dev Release %s"), buf);
		putparam("VERSION", temp);
		pkgvers = getenv("VERSION");
		logerr(gettext(WRN_SETPARAM), "VERSION", temp);
	}
	if (ckparam("VERSION", pkgvers))
		quit(1);
	if ((pkgarch = getenv("ARCH")) == NULL) {
		(void) uname(&utsbuf);
		putparam("ARCH", utsbuf.machine);
		pkgarch = getenv("ARCH");
		logerr(gettext(WRN_SETPARAM), "ARCH", utsbuf.machine);
	}
	if (ckparam("ARCH", pkgarch))
		quit(1);
	if (getenv("PSTAMP") == NULL) {
		/* use octal value of '%' to fight sccs expansion */
		/* XXX - I18n */
		/* LINTED do not use cftime(); use strftime instead */
		(void) cftime(buf, "\045Y\045m\045d\045H\045M\045S", &clock);
		(void) uname(&utsbuf);
		(void) snprintf(temp, sizeof (temp), "%s%s",
			utsbuf.nodename, buf);
		putparam("PSTAMP", temp);
		logerr(gettext(WRN_SETPARAM), "PSTAMP", temp);
	}
	if ((pkgcat = getenv("CATEGORY")) == NULL) {
		progerr(gettext(ERR_NOPARAM), "CATEGORY", svept->path);
		quit(1);
	}
	if (ckparam("CATEGORY", pkgcat))
		quit(1);

	/*
	 * warn user of classes listed in package which do
	 * not appear in CLASSES variable in pkginfo file
	 */
	objects = 0;
	for (i = 0; eptlist[i]; i++) {
		if (eptlist[i]->ftype != 'i') {
			objects++;
			addlist(&allclass, eptlist[i]->pkg_class);
		}
	}

	if ((pt = getenv("CLASSES")) == NULL) {
		if (allclass && *allclass) {
			cl_setl(allclass);
			cl_putl("CLASSES", allclass);
			logerr(gettext(WRN_SETPARAM), "CLASSES",
			    getenv("CLASSES"));
		}
	} else {
		cl_sets(qstrdup(pt));
		if (allclass && *allclass) {
			for (i = 0; allclass[i]; i++) {
				found = 0;
				if (cl_idx(allclass[i]->name) != -1) {
					found++;
					break;
				}
				if (!found) {
					logerr(gettext(WRN_CLASSES),
					    (char *)allclass[i]);
				}
			}
		}
	}

	(void) fprintf(stderr, gettext(MSG_VOLUMIZE), objects);
	order = (struct cl_attr **)0;
	if (pt = getenv("ORDER")) {
		pt = qstrdup(pt);
		(void) setlist(&order, pt);
		cl_putl("ORDER", order);
	}

	/* stat the intended output filesystem to get blocking information */
	if (pkgdev.dirname == NULL) {
		progerr(gettext(ERR_WHATVFS), device);
		quit(99);
	}
	if (statvfs64(pkgdev.dirname, &svfsb)) {
		progerr(gettext(ERR_STATVFS), pkgdev.dirname);
		quit(99);
	}

	if (bsize == 0) {
		bsize = svfsb.f_bsize;
	}
	if (frsize == 0) {
		frsize = svfsb.f_frsize;
	}
	if (limit == 0)
		/*
		 * bavail is in terms of fragment size blocks - change
		 * to 512 byte blocks
		 */
		limit = (((long)frsize > 0) ?
			howmany(frsize, DEV_BSIZE) :
			howmany(bsize, DEV_BSIZE)) * svfsb.f_bavail;
	if (ilimit == 0) {
		ilimit = (svfsb.f_favail > 0) ?
		    svfsb.f_favail : svfsb.f_ffree;
	}

	nparts = splpkgmap(eptlist, eptnum, (char **)order, bsize, frsize,
	    &limit, &ilimit, &llimit);

	if (nparts <= 0) {
		progerr(gettext(ERR_SPLIT));
		quit(1);
	}

	if (nflag) {
		for (i = 0; eptlist[i]; i++)
			(void) ppkgmap(eptlist[i], stdout);
		exit(0);
		/*NOTREACHED*/
	}

	(void) snprintf(pkgloc, sizeof (pkgloc), "%s/%s",
			pkgdev.dirname, pkginst);
	if (!isdir(pkgloc) && !overwrite) {
		progerr(gettext(ERR_OVERWRITE), pkgloc);
		quit(1);
	}

	/* output all environment install parameters */
	t_pkginfo = tempnam(tmpdir, "pkginfo");
	if ((fp = fopen(t_pkginfo, "w")) == NULL) {
		progerr(gettext(ERR_TEMP), errno);
		exit(99);
	}
	for (i = 0; environ[i]; i++) {
		if (isupper(*environ[i])) {
			(void) fputs(environ[i], fp);
			(void) fputc('\n', fp);
		}
	}
	(void) fclose(fp);

	started++;
	(void) rrmdir(pkgloc);
	if (mkdir(pkgloc, 0755)) {
		progerr(gettext(ERR_MKDIR), pkgloc);
		quit(1);
	}

	/* determine how many packages already reside on the medium */
	pkgdir = pkgdev.dirname;
	npkgs = 0;
	while (pt = fpkginst("all", NULL, NULL))
		npkgs++;
	(void) fpkginst(NULL); /* free resource usage */

	if (nparts > 1) {
		if (pkgdev.mount && npkgs) {
			progerr(gettext(ERR_ONEVOL));
			quit(1);
		}
	}

	/*
	 *  update pkgmap entry for pkginfo file, since it may
	 *  have changed due to command line or failure to
	 *  specify all neccessary parameters
	 */
	for (i = 0; eptlist[i]; i++) {
		if (eptlist[i]->ftype != 'i')
			continue;
		if (strcmp(eptlist[i]->path, "pkginfo") == 0) {
			svept = eptlist[i];
			svept->ftype = '?';
			svept->ainfo.local = t_pkginfo;
			(void) cverify(0, &svept->ftype, t_pkginfo,
				&svept->cinfo, 1);
			svept->ftype = 'i';
			break;
		}
	}

	if (nparts > 1)
		(void) fprintf(stderr, gettext(MSG_PACKAGEM), nparts);
	else
		(void) fprintf(stderr, gettext(MSG_PACKAGE1));

	for (part = 1; part <= nparts; part++) {
		if ((part > 1) && pkgdev.mount) {
			if (pkgumount(&pkgdev)) {
				progerr(gettext(ERR_UMOUNT), pkgdev.mount);
				quit(99);
			}
			if (n = pkgmount(&pkgdev, NULL, part, nparts, 1))
				quit(n);
			(void) rrmdir(pkgloc);
			if (mkdir(pkgloc, 0555)) {
				progerr(gettext(ERR_MKDIR), pkgloc);
				quit(99);
			}
		}
		outvol(eptlist, eptnum, part, nparts);

		/* Validate (as much as possible) the control scripts. */
		if (part == 1) {
			char inst_path[PATH_MAX];

			(void) fprintf(stderr, gettext(MSG_VALSCRIPTS));
			(void) snprintf(inst_path, sizeof (inst_path),
					"%s/install", pkgloc);
			checkscripts(inst_path, 0);
		}
	}

	quit(0);
	/*NOTREACHED*/
}
/*
    ========================================================================

    Routine Description:
        In kernel mode read parameters from file

    Arguments:
        src                     the location of the file.
        dest                        put the parameters to the destination.
        Length                  size to read.

    Return Value:
        None

    Note:

    ========================================================================
*/
void rtmp_read_wapi_parms_from_file(
		IN  PRTMP_ADAPTER pAd, 
		PSTRING tmpbuf, 
		PSTRING buffer)
{	
	UINT32					ip_addr;
#ifdef CONFIG_AP_SUPPORT	
	INT						apidx = 0;
#endif // CONFIG_AP_SUPPORT //

	PCOMMON_WAPI_INFO pInfo = &pAd->CommonCfg.comm_wapi_info;
	
	// wapi interface name
	if (RTMPGetKeyParameter("Wapiifname", tmpbuf, 32, buffer, TRUE))
	{
		if (strlen(tmpbuf) > 0)
		{
			NdisMoveMemory(pInfo->wapi_ifname, tmpbuf, strlen(tmpbuf));
			pInfo->wapi_ifname_len = strlen(tmpbuf); 
			
			DBGPRINT(RT_DEBUG_TRACE, ("Wapiifname=%s, len=%d\n", 
														pInfo->wapi_ifname, 
														pInfo->wapi_ifname_len));
		}
	}
	

	// WapiAsCertPath
	if (RTMPGetKeyParameter("WapiAsCertPath", tmpbuf, 128, buffer, TRUE))
	{
		if (strlen(tmpbuf) > 0)
		{
			NdisMoveMemory(pInfo->as_cert_path, tmpbuf, strlen(tmpbuf));
			pInfo->as_cert_path_len = strlen(tmpbuf); 
			
			DBGPRINT(RT_DEBUG_TRACE, ("WapiAsCertPath=%s, len=%d\n", 
														pInfo->as_cert_path, 
														pInfo->as_cert_path_len));
		}
	}

	// WapiUserCertPath
	if (RTMPGetKeyParameter("WapiUserCertPath", tmpbuf, 128, buffer, TRUE))
	{
		if (strlen(tmpbuf) > 0)
		{
			NdisMoveMemory(pInfo->user_cert_path, tmpbuf, strlen(tmpbuf));
			pInfo->user_cert_path_len = strlen(tmpbuf); 
			
			DBGPRINT(RT_DEBUG_TRACE, ("WapiUserCertPath=%s, len=%d\n", 
														pInfo->user_cert_path, 
														pInfo->user_cert_path_len));
		}
	}

	// WapiAsIpAddr
	if (RTMPGetKeyParameter("WapiAsIpAddr", tmpbuf, 32, buffer, TRUE))
	{
		if (rtinet_aton(tmpbuf, &ip_addr))
     	{
            pInfo->wapi_as_ip = ip_addr;  
			DBGPRINT(RT_DEBUG_TRACE, ("WapiAsIpAddr=%s(%x)\n", tmpbuf, pInfo->wapi_as_ip));
		}	    
	}

	// WapiAsPort
	if (RTMPGetKeyParameter("WapiAsPort", tmpbuf, 32, buffer, TRUE))
	{
		pInfo->wapi_as_port = simple_strtol(tmpbuf, 0, 10); 
		DBGPRINT(RT_DEBUG_TRACE, ("WapiAsPort=%d\n", pInfo->wapi_as_port));			   
	}

	// WapiUskRekeyMethod
	if (RTMPGetKeyParameter("WapiUskRekeyMethod", tmpbuf, 32, buffer, TRUE))
	{		
		if ((strcmp(tmpbuf, "TIME") == 0) || (strcmp(tmpbuf, "time") == 0))
			pAd->CommonCfg.wapi_usk_rekey_method = REKEY_METHOD_TIME;
		else if ((strcmp(tmpbuf, "PKT") == 0) || (strcmp(tmpbuf, "pkt") == 0))
			pAd->CommonCfg.wapi_usk_rekey_method = REKEY_METHOD_PKT;
		else
			pAd->CommonCfg.wapi_usk_rekey_method = REKEY_METHOD_DISABLE;

		DBGPRINT(RT_DEBUG_TRACE, ("WapiUskRekeyMethod=%d\n", pAd->CommonCfg.wapi_usk_rekey_method));			   
	}

	// WapiUskRekeyThreshold
	if (RTMPGetKeyParameter("WapiUskRekeyThreshold", tmpbuf, 32, buffer, TRUE))
	{			
		pAd->CommonCfg.wapi_usk_rekey_threshold = simple_strtol(tmpbuf, 0, 10); 
		DBGPRINT(RT_DEBUG_TRACE, ("WapiUskRekeyThreshold=%d\n", pAd->CommonCfg.wapi_usk_rekey_threshold));			   
	}

	// WapiMskRekeyMethod
	if (RTMPGetKeyParameter("WapiMskRekeyMethod", tmpbuf, 32, buffer, TRUE))
	{		
		if ((strcmp(tmpbuf, "TIME") == 0) || (strcmp(tmpbuf, "time") == 0))
			pAd->CommonCfg.wapi_msk_rekey_method = REKEY_METHOD_TIME;
		else if ((strcmp(tmpbuf, "PKT") == 0) || (strcmp(tmpbuf, "pkt") == 0))
			pAd->CommonCfg.wapi_msk_rekey_method = REKEY_METHOD_PKT;
		else
			pAd->CommonCfg.wapi_msk_rekey_method = REKEY_METHOD_DISABLE;

		DBGPRINT(RT_DEBUG_TRACE, ("WapiMskRekeyMethod=%d\n", pAd->CommonCfg.wapi_msk_rekey_method));			   
	}

	// WapiMskRekeyThreshold
	if (RTMPGetKeyParameter("WapiMskRekeyThreshold", tmpbuf, 32, buffer, TRUE))
	{
		pAd->CommonCfg.wapi_msk_rekey_threshold = simple_strtol(tmpbuf, 0, 10); 
		DBGPRINT(RT_DEBUG_TRACE, ("WapiMskRekeyThreshold=%d\n", pAd->CommonCfg.wapi_msk_rekey_threshold));			   
	}
	
#ifdef CONFIG_AP_SUPPORT
	IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
	{						
		STRING tok_str[16];

		// WapiPskX		
		for (apidx = 0; apidx < pAd->ApCfg.BssidNum; apidx++)
		{
			snprintf(tok_str, sizeof(tok_str), "WapiPsk%d", apidx + 1);
			
			NdisZeroMemory(pAd->ApCfg.MBSSID[apidx].WAPIPassPhrase, 64);
			pAd->ApCfg.MBSSID[apidx].WAPIPassPhraseLen = 0;
			if(RTMPGetKeyParameter(tok_str, tmpbuf, 65, buffer, FALSE))
			{								    
			    if (strlen(tmpbuf) >= 8 && strlen(tmpbuf) <= 64)
			    {                                    
			        NdisMoveMemory(pAd->ApCfg.MBSSID[apidx].WAPIPassPhrase, tmpbuf, strlen(tmpbuf));
			        pAd->ApCfg.MBSSID[apidx].WAPIPassPhraseLen = strlen(tmpbuf);
   					DBGPRINT(RT_DEBUG_TRACE, ("IF(ra%d) WapiPsk=(%s), len=%d\n", apidx, tmpbuf, strlen(tmpbuf)));						
			    }
				else
				{
					if (pAd->ApCfg.MBSSID[apidx].AuthMode == Ndis802_11AuthModeWAIPSK)
					{
						pAd->ApCfg.MBSSID[apidx].AuthMode = Ndis802_11AuthModeOpen;
						pAd->ApCfg.MBSSID[apidx].WepStatus = Ndis802_11EncryptionDisabled;
					}
					DBGPRINT(RT_DEBUG_ERROR, ("IF(ra%d) The length of WAPI PSKPassPhrase is invalid(len=%d). \n", apidx, strlen(tmpbuf)));
				}																			
			}
		}					
	}
#endif // CONFIG_AP_SUPPORT //

	
#ifdef CONFIG_STA_SUPPORT
	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
	{
		// WapiPsk
		if (RTMPGetKeyParameter("WapiPsk", tmpbuf, 512, buffer, FALSE))
		{											                 										
		    NdisZeroMemory(pAd->StaCfg.WAPIPassPhrase, 64);
		    pAd->StaCfg.WAPIPassPhraseLen = 0;
		    if (strlen(tmpbuf) >= 8 && strlen(tmpbuf) <= 64)
		    {                                    
		        NdisMoveMemory(pAd->StaCfg.WAPIPassPhrase, tmpbuf, strlen(tmpbuf));
		        pAd->StaCfg.WAPIPassPhraseLen = strlen(tmpbuf);

				DBGPRINT(RT_DEBUG_TRACE, ("WapiPsk=(%s), len=%d\n", tmpbuf, strlen(tmpbuf)));						
		    }
			else
			{
				if (pAd->StaCfg.AuthMode == Ndis802_11AuthModeWAIPSK)
				{
					pAd->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
					pAd->StaCfg.WepStatus = Ndis802_11EncryptionDisabled;
				}
				DBGPRINT(RT_DEBUG_ERROR, ("The length of WAPI PSKPassPhrase is invalid(len=%d). \n", strlen(tmpbuf)));
			}			      						 
		}
	}
#endif // CONFIG_STA_SUPPORT //													

	// WapiPskType
	if (RTMPGetKeyParameter("WapiPskType", tmpbuf, 32, buffer, TRUE))
	{		
		INT	err;

#ifdef CONFIG_AP_SUPPORT
		IF_DEV_CONFIG_OPMODE_ON_AP(pAd)
		{
			PSTRING macptr;
			
			for (apidx = 0, macptr = rstrtok(tmpbuf,";"); macptr; macptr = rstrtok(NULL,";"), apidx++)
		    {
				err = 0;
			
				if (apidx >= pAd->ApCfg.BssidNum)
					break;

				// HEX
				if(simple_strtol(macptr, 0, 10) == 0)
				{
					pAd->ApCfg.MBSSID[apidx].WapiPskType = HEX_MODE;
		
					if (pAd->ApCfg.MBSSID[apidx].WAPIPassPhraseLen % 2 != 0)
					{
						err = 1;
						DBGPRINT(RT_DEBUG_ERROR, ("I/F(ra%d) The WAPI-PSK key length MUST be even in Hex mode\n", apidx));						
					}						
				}
				// ASCII
				else	
				{
					pAd->ApCfg.MBSSID[apidx].WapiPskType = ASCII_MODE;
				}
				
				if (err)
				{
					pAd->ApCfg.MBSSID[apidx].AuthMode = Ndis802_11AuthModeOpen;
					pAd->ApCfg.MBSSID[apidx].WepStatus = Ndis802_11EncryptionDisabled;
				}
				else
					DBGPRINT(RT_DEBUG_TRACE, ("I/F(ra%d) WapiPskType=%s\n", apidx, (pAd->ApCfg.MBSSID[apidx].WapiPskType == HEX_MODE) ? "HEX" : "ASCII"));
		    }
		}
#endif // CONFIG_AP_SUPPORT //

#ifdef CONFIG_STA_SUPPORT
		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
		{
			err = 0;
		
			// HEX
			if(simple_strtol(tmpbuf, 0, 10) == 0)  
			{
				pAd->StaCfg.WapiPskType = HEX_MODE;
	
				if (pAd->StaCfg.WAPIPassPhraseLen % 2 != 0)
				{
					err = 1;
					DBGPRINT(RT_DEBUG_ERROR, ("The WAPI-PSK key length MUST be even in Hex mode\n"));						
				}
			}
			// ASCII
			else 
			{
				pAd->StaCfg.WapiPskType = ASCII_MODE;
			}

			if (err)
			{
				pAd->StaCfg.AuthMode = Ndis802_11AuthModeOpen;
				pAd->StaCfg.WepStatus = Ndis802_11EncryptionDisabled;
			}
			else
				DBGPRINT(RT_DEBUG_TRACE, ("WapiPskType=%s\n", (pAd->StaCfg.WapiPskType == HEX_MODE) ? "HEX" : "ASCII"));
		}
#endif // CONFIG_STA_SUPPORT //
				
	}
Esempio n. 30
0
/*
 * call from within ldap_back_db_open()
 */
int
ldap_back_monitor_db_open( BackendDB *be )
{
	ldapinfo_t		*li = (ldapinfo_t *) be->be_private;
	char			buf[ BACKMONITOR_BUFSIZE ];
	Entry			*e = NULL;
	monitor_callback_t	*cb = NULL;
	struct berval		suffix, *filter, *base;
	char			*ptr;
	time_t			now;
	char			timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
	struct berval 		timestamp;
	int			rc = 0;
	BackendInfo		*mi;
	monitor_extra_t		*mbe;

	if ( !SLAP_DBMONITORING( be ) ) {
		return 0;
	}

	/* check if monitor is configured and usable */
	mi = backend_info( "monitor" );
	if ( !mi || !mi->bi_extra ) {
		SLAP_DBFLAGS( be ) ^= SLAP_DBFLAG_MONITORING;
		return 0;
 	}
 	mbe = mi->bi_extra;

	/* don't bother if monitor is not configured */
	if ( !mbe->is_configured() ) {
		static int warning = 0;

		if ( warning++ == 0 ) {
			Debug( LDAP_DEBUG_ANY, "ldap_back_monitor_db_open: "
				"monitoring disabled; "
				"configure monitor database to enable\n",
				0, 0, 0 );
		}

		return 0;
	}

	/* set up the fake subsystem that is used to create
	 * the volatile connection entries */
	li->li_monitor_info.lmi_mss.mss_name = "back-ldap";
	li->li_monitor_info.lmi_mss.mss_flags = MONITOR_F_VOLATILE_CH;
	li->li_monitor_info.lmi_mss.mss_create = ldap_back_monitor_conn_create;

	li->li_monitor_info.lmi_li = li;
	li->li_monitor_info.lmi_scope = LDAP_SCOPE_SUBORDINATE;
	base = &li->li_monitor_info.lmi_base;
	BER_BVSTR( base, "cn=databases,cn=monitor" );
	filter = &li->li_monitor_info.lmi_filter;
	BER_BVZERO( filter );

	suffix.bv_len = ldap_bv2escaped_filter_value_len( &be->be_nsuffix[ 0 ] );
	if ( suffix.bv_len == be->be_nsuffix[ 0 ].bv_len ) {
		suffix = be->be_nsuffix[ 0 ];

	} else {
		ldap_bv2escaped_filter_value( &be->be_nsuffix[ 0 ], &suffix );
	}
	
	filter->bv_len = STRLENOF( "(&" )
		+ li->li_monitor_info.lmi_more_filter.bv_len
		+ STRLENOF( "(monitoredInfo=" )
		+ strlen( be->bd_info->bi_type )
		+ STRLENOF( ")(!(monitorOverlay=" )
		+ strlen( be->bd_info->bi_type )
		+ STRLENOF( "))(namingContexts:distinguishedNameMatch:=" )
		+ suffix.bv_len + STRLENOF( "))" );
	ptr = filter->bv_val = ch_malloc( filter->bv_len + 1 );
	ptr = lutil_strcopy( ptr, "(&" );
	ptr = lutil_strncopy( ptr, li->li_monitor_info.lmi_more_filter.bv_val,
		li->li_monitor_info.lmi_more_filter.bv_len );
	ptr = lutil_strcopy( ptr, "(monitoredInfo=" );
	ptr = lutil_strcopy( ptr, be->bd_info->bi_type );
	ptr = lutil_strcopy( ptr, ")(!(monitorOverlay=" );
	ptr = lutil_strcopy( ptr, be->bd_info->bi_type );
	ptr = lutil_strcopy( ptr, "))(namingContexts:distinguishedNameMatch:=" );
	ptr = lutil_strncopy( ptr, suffix.bv_val, suffix.bv_len );
	ptr = lutil_strcopy( ptr, "))" );
	ptr[ 0 ] = '\0';
	assert( ptr == &filter->bv_val[ filter->bv_len ] );

	if ( suffix.bv_val != be->be_nsuffix[ 0 ].bv_val ) {
		ch_free( suffix.bv_val );
	}

	now = slap_get_time();
	timestamp.bv_val = timebuf;
	timestamp.bv_len = sizeof( timebuf );
	slap_timestamp( &now, &timestamp );

	/* caller (e.g. an overlay based on back-ldap) may want to use
	 * a different RDN... */
	if ( BER_BVISNULL( &li->li_monitor_info.lmi_rdn ) ) {
		ber_str2bv( "cn=Connections", 0, 1, &li->li_monitor_info.lmi_rdn );
	}

	ptr = ber_bvchr( &li->li_monitor_info.lmi_rdn, '=' );
	assert( ptr != NULL );
	ptr[ 0 ] = '\0';
	ptr++;

	snprintf( buf, sizeof( buf ),
		"dn: %s=%s\n"
		"objectClass: monitorContainer\n"
		"%s: %s\n"
		"creatorsName: %s\n"
		"createTimestamp: %s\n"
		"modifiersName: %s\n"
		"modifyTimestamp: %s\n",
		li->li_monitor_info.lmi_rdn.bv_val,
			ptr,
		li->li_monitor_info.lmi_rdn.bv_val,
			ptr,
		BER_BVISNULL( &be->be_rootdn ) ? SLAPD_ANONYMOUS : be->be_rootdn.bv_val,
		timestamp.bv_val,
		BER_BVISNULL( &be->be_rootdn ) ? SLAPD_ANONYMOUS : be->be_rootdn.bv_val,
		timestamp.bv_val );
	e = str2entry( buf );
	if ( e == NULL ) {
		rc = -1;
		goto cleanup;
	}

	ptr[ -1 ] = '=';

	/* add labeledURI and special, modifiable URI value */
	if ( li->li_uri != NULL ) {
		struct berval	bv;
		LDAPURLDesc	*ludlist = NULL;
		int		rc;

		rc = ldap_url_parselist_ext( &ludlist,
			li->li_uri, NULL,
			LDAP_PVT_URL_PARSE_NOEMPTY_HOST
				| LDAP_PVT_URL_PARSE_DEF_PORT );
		if ( rc != LDAP_URL_SUCCESS ) {
			Debug( LDAP_DEBUG_ANY,
				"ldap_back_monitor_db_open: "
				"unable to parse URI list (ignored)\n",
				0, 0, 0 );
		} else {
			for ( ; ludlist != NULL; ) {
				LDAPURLDesc	*next = ludlist->lud_next;

				bv.bv_val = ldap_url_desc2str( ludlist );
				assert( bv.bv_val != NULL );
				ldap_free_urldesc( ludlist );
				bv.bv_len = strlen( bv.bv_val );
				attr_merge_normalize_one( e, slap_schema.si_ad_labeledURI,
					&bv, NULL );
				ch_free( bv.bv_val );

				ludlist = next;
			}
		}
		
		ber_str2bv( li->li_uri, 0, 0, &bv );
		attr_merge_normalize_one( e, ad_olmDbURIList,
			&bv, NULL );
	}

	ber_dupbv( &li->li_monitor_info.lmi_nrdn, &e->e_nname );

	cb = ch_calloc( sizeof( monitor_callback_t ), 1 );
	cb->mc_update = ldap_back_monitor_update;
	cb->mc_modify = ldap_back_monitor_modify;
	cb->mc_free = ldap_back_monitor_free;
	cb->mc_private = (void *)li;

	rc = mbe->register_entry_parent( e, cb,
		(monitor_subsys_t *)&li->li_monitor_info,
		MONITOR_F_VOLATILE_CH,
		base, LDAP_SCOPE_SUBORDINATE, filter );

cleanup:;
	if ( rc != 0 ) {
		if ( cb != NULL ) {
			ch_free( cb );
			cb = NULL;
		}

		if ( e != NULL ) {
			entry_free( e );
			e = NULL;
		}

		if ( !BER_BVISNULL( filter ) ) {
			ch_free( filter->bv_val );
			BER_BVZERO( filter );
		}
	}

	/* store for cleanup */
	li->li_monitor_info.lmi_cb = (void *)cb;

	if ( e != NULL ) {
		entry_free( e );
	}

	return rc;
}