Beispiel #1
0
void playback(char* path, int interval)
{
	FILE* fd = fopen(path, "r");
	if (!fd)
	{
		displayMsg("Unable to open output file.");
		return;
	}
	displayMsg("Starting Playback...");

	XPCSocket sock = openUDP("127.0.0.1");
	float posi[7];
	while (!feof(fd) && !ferror(fd))
	{
		int result = fscanf(fd, "%f, %f, %f, %f, %f, %f, %f\n",
			&posi[0], &posi[1], &posi[2], &posi[3], &posi[4], &posi[5], &posi[6]);
		playbackSleep(interval);
		if (result != 7)
		{
			continue;
		}		
		sendPOSI(sock, posi, 7, 0);
	}
	closeUDP(sock);
	displayMsg("Playback Complete");
}
Beispiel #2
0
void record(char* path, int interval, int duration)
{
	FILE* fd = fopen(path, "w");
	int count = duration * 1000 / interval;
	if (!fd)
	{
		displayMsg("Unable to open output file.");
		return;
	}
	if (count < 1)
	{
		displayMsg("Duration is less than one iteration.");
		return;
	}
	displayMsg("Recording...");

	XPCSocket sock = openUDP("127.0.0.1");
	for (int i = 0; i < count; ++i)
	{
		float posi[7];
		int result = getPOSI(sock, posi, 0);
		playbackSleep(interval);
		if (result < 0)
		{
			continue;
		}
		fprintf(fd, "%f, %f, %f, %f, %f, %f, %f\n", posi[0], posi[1], posi[2], posi[3], posi[4], posi[5], posi[6]);
	}
	closeUDP(sock);
	displayMsg("Recording Complete");
}
double
TabulatedFunction_getValue(TabulatedFunction *func,
				      double x)
{
  TabulatedFunctionSample *samp = (TabulatedFunctionSample *)func->samples.data;
  size_t isamp;

  /* check for out of bounds conditions */
  if (samp[0].x  > x)
  {
    char msg[1000],msg2[1000];
    sprintf(msg,"requested value before available data! (%s @",
	    func->fileName);
    sprintf(msg2,"%.1f)",x);
    displayMsg(1,"TAB1",msg,msg2,1);
    return samp[0].y;
  }
  if (samp[func->samples.nelem-1].x  < x)
  {
    char msg[1000],msg2[1000];
    sprintf(msg,"requested value after available data! (%s @",
	    func->fileName);
    sprintf(msg2,"%.1f)",x);
    displayMsg(1,"TAB2",msg,msg2,1);
    return samp[func->samples.nelem-1].y;
  }

  /* find first sample to fall before requested time */
#if 0
  for (isamp = 0; 
       isamp < func->samples.nelem  && samp[isamp].x <= x; 
       isamp++)
    ;  
#else  /* binary search code, aka the "The Price Is Right" method */
  int imin=0, imax=func->samples.nelem-1;
  int imid;
  do
  {
    imid = (imin+imax)/2;
    if (samp[imid].x > x)
      imax = imid;
    else
      imin = imid;
  } while (imax > imin+1);
  isamp = imax;
#endif

  /* interpolate */
  return (x - samp[isamp-1].x) / (samp[isamp].x - samp[isamp-1].x)
    * (samp[isamp].y - samp[isamp-1].y) + samp[isamp-1].y;
}
Beispiel #4
0
void CtcpHandler::parse(Message::Type messageType, const QString &prefix, const QString &target, const QByteArray &message) {
  QByteArray ctcp;

  //lowlevel message dequote
  QByteArray dequotedMessage = lowLevelDequote(message);

  CtcpType ctcptype = messageType == Message::Notice
    ? CtcpReply
    : CtcpQuery;

  Message::Flags flags = (messageType == Message::Notice && !network()->isChannelName(target))
    ? Message::Redirected
    : Message::None;

  // extract tagged / extended data
  int xdelimPos = -1;
  int xdelimEndPos = -1;
  int spacePos = -1;
  while((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) {
    if(xdelimPos > 0)
      displayMsg(messageType, target, userDecode(target, dequotedMessage.left(xdelimPos)), prefix, flags);

    xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1);
    if(xdelimEndPos == -1) {
      // no matching end delimiter found... treat rest of the message as ctcp
      xdelimEndPos = dequotedMessage.count();
    }
    ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
    dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);

    //dispatch the ctcp command
    QString ctcpcmd = userDecode(target, ctcp.left(spacePos));
    QString ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));

    spacePos = ctcp.indexOf(' ');
    if(spacePos != -1) {
      ctcpcmd = userDecode(target, ctcp.left(spacePos));
      ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
    } else {
      ctcpcmd = userDecode(target, ctcp);
      ctcpparam = QString();
    }

    handle(ctcpcmd, Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam));
  }

  if(!dequotedMessage.isEmpty())
    displayMsg(messageType, target, userDecode(target, dequotedMessage), prefix, flags);
}
Beispiel #5
0
void getPostKeplerian(pulsar *psr,int com,double an,double *si,double *m2,
        double *mtot,double *omdot, double *gamma,double *xdot,
        double *xpbdot,double *pbdot, double *edot,double *pmra,
        double *pmdec,double *dpara, double *dr,double *dth,
        double *a0,double *b0,double *xomdot,double *afac,
        double *eps1dot,double *eps2dot, double *daop){
    double SUNMASS = 4.925490947e-6;
    double rad2deg = 180.0/M_PI;
    //double pxConv = 1.74532925199432958E-2/3600.0e3;//converts mas to rad
    double pxConv = M_PI/180.0/3600*1e-3; // converts mas to rad
    double daopConv = 3.08568025e16;//pc in m

    //  logdbg("Going to get parameters");
    *si      = getParameter(psr,param_sini,com);
    if (*si > 1.0)
    {
        displayMsg(1,"BIN1","SIN I > 1.0, setting to 1: should probably use DDS model","",psr[0].noWarnings);
        *si = 1.0;
        psr[0].param[param_sini].val[0] = 1.0;
    }
    if (*si < -1.0)
    {
        displayMsg(1,"BIN1","SIN I < -1.0, setting to -1: should probably use DDS model","",psr[0].noWarnings);
        *si = -1.0;
        psr[0].param[param_sini].val[0] = -1.0;
    }
    *m2      = getParameter(psr,param_m2,com)*SUNMASS;
    *mtot    = getParameter(psr,param_mtot,com)*SUNMASS;
    *omdot   = getParameter(psr,param_omdot,com)/(rad2deg*365.25*SECDAY*an);
    *gamma   = getParameter(psr,param_gamma,com);
    *xdot    = getParameter(psr,param_a1dot,com);
    *xpbdot  = getParameter(psr,param_xpbdot,com);
    *pbdot   = getParameter(psr,param_pbdot,com);
    *edot    = getParameter(psr,param_edot,com);
    *pmra    = getParameter(psr,param_pmra,com)
        * M_PI/(180.0*3600.0e3)/(365.25*86400.0);
    *pmdec   = getParameter(psr,param_pmdec,com)
        * M_PI/(180.0*3600.0e3)/(365.25*86400.0);
    *dpara   = getParameter(psr,param_px,com)*pxConv;
    *dr      = getParameter(psr,param_dr,com);
    *dth     = getParameter(psr,param_dth,com);
    *a0      = getParameter(psr,param_a0,com);
    *b0      = getParameter(psr,param_b0,com);
    *xomdot  = getParameter(psr,param_xomdot,com)/(an*rad2deg*365.25*86400.0);
    *afac    = getParameter(psr,param_afac,com);
    *eps1dot = getParameter(psr,param_eps1dot,com);
    *eps2dot = getParameter(psr,param_eps2dot,com);
    *daop    = getParameter(psr,param_daop,com)*1e-3/pxConv;
}
Beispiel #6
0
// only accept CTCPs in their simplest form, i.e. one ctcp, from start to
// end, no text around it; not as per the 'specs', but makes people happier
void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
{
    if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() -1] != '\001') {
        displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags);
    } else {
        int spacePos = -1;
        QString ctcpcmd, ctcpparam;

        QByteArray ctcp = xdelimDequote(dequotedMessage.mid(1, dequotedMessage.count() - 2));
        spacePos = ctcp.indexOf(' ');
        if (spacePos != -1) {
            ctcpcmd = targetDecode(e, ctcp.left(spacePos));
            ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1));
        } else {
            ctcpcmd = targetDecode(e, ctcp);
            ctcpparam = QString();
        }
        ctcpcmd = ctcpcmd.toUpper();

        // we don't want to block /me messages by the CTCP ignore list
        if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
            QUuid uuid = QUuid::createUuid();
            _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix())));
            CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(),
                ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid);
            emit newEvent(event);
            CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(),
                ctcptype, "INVALID", QString(), e->timestamp(), uuid);
            emit newEvent(flushEvent);
        }
    }
}
Beispiel #7
0
menix::menix(QWidget *parent) :
        QMainWindow(parent),
        m_ui(new Ui::menix) {
    m_ui->setupUi(this);


    QToolBar *toolbarIconos = addToolBar(tr("Iconos"));
    toolbarIconos->addAction(QIcon(":/preferences-system.png"),"Opciones",this,SLOT( abrirOpciones() ) );
    toolbarIconos->addAction(QIcon(":/terminal.png"),"Debug",this,SLOT(abrirDebug()));

    opciones = new opcionesGlobales();
    numero = opciones->NumeroDestino();
    puerto = opciones->Puerto();
    pin = opciones->Pin();
    centro = opciones->CentroMensajes();
    fixok = opciones->Fixok();
    
    ips = new QStringList( opciones->Ips() );

    file = new QFile( opciones->fileLog() );
    file->open( QIODevice::WriteOnly | QIODevice::Text );
    flog = new QTextStream( file );
    
    mensaje = new smsat(centro,puerto,flog,pin,fixok);
    crearAcciones();
    crearBandeja();
//    testPuerto( mensaje );
    Server *tcp = new Server(ips,this);
    connect(tcp,SIGNAL(sendMessage(QString)),this,SLOT(sendMessage(QString)));
    connect(mensaje,SIGNAL(sendAt(QString)),this,SLOT(sendedMessage(QString)));
    connect(mensaje,SIGNAL(displayMsg(QString)),this,SLOT(showPopup(QString)));
}
Beispiel #8
0
void showSplashScreen()
{
   	//Clear the screen
   	LCDClear();
	displayMsg(m1_splash, m2_splash, 0);
   	_delay_ms(2000);
}
Beispiel #9
0
int qSslChat::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QWidget::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: peerRejectedFileSend(); break;
        case 1: fsCompleted(); break;
        case 2: hostConnection(); break;
        case 3: connectToHost(); break;
        case 4: activateMsgSending(); break;
        case 5: sendMsg((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 6: receiveMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 7: displayMsg(); break;
        case 8: endConnection(); break;
        case 9: sendAnticipation(); break;
        case 10: sendFile((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
        case 11: notifyServer(); break;
        case 12: completeFileSend(); break;
        case 13: selectSmiley(); break;
        case 14: insertSmiley((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
        case 15: displayCertificateInfo(); break;
        }
        _id -= 16;
    }
    return _id;
}
Beispiel #10
0
int main() {
    hideCursor();
    char title[] = "Simple Game Demo";
    setTitle(title);

    int opt = displayMainMenu();
    while (opt != 3) {
        clrscr();
        if (opt == 0) {
            char msg[] = "Let's play a game\nEat the # to win the game";
            displayMsg(0, 0, msg);
            Sleep(1000);
            clrscr();
            playGame();
        } else if (opt == 1) {
            printf("This is load");
        } else if (opt == 2) {
            printf("This is setting");
        }
        clrscr();
        opt = displayMainMenu();
    }

    return 0;
}
Beispiel #11
0
void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
{
    QByteArray ctcp;

    QList<CtcpEvent *> ctcpEvents;
    QUuid uuid; // needed to group all replies together

    // extract tagged / extended data
    int xdelimPos = -1;
    int xdelimEndPos = -1;
    int spacePos = -1;
    while ((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) {
        if (xdelimPos > 0)
            displayMsg(e, messagetype, targetDecode(e, dequotedMessage.left(xdelimPos)), e->prefix(), e->target(), flags);

        xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1);
        if (xdelimEndPos == -1) {
            // no matching end delimiter found... treat rest of the message as ctcp
            xdelimEndPos = dequotedMessage.count();
        }
        ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
        dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);

        //dispatch the ctcp command
        QString ctcpcmd = targetDecode(e, ctcp.left(spacePos));
        QString ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1));

        spacePos = ctcp.indexOf(' ');
        if (spacePos != -1) {
            ctcpcmd = targetDecode(e, ctcp.left(spacePos));
            ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1));
        }
        else {
            ctcpcmd = targetDecode(e, ctcp);
            ctcpparam = QString();
        }

        ctcpcmd = ctcpcmd.toUpper();

        // we don't want to block /me messages by the CTCP ignore list
        if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
            if (uuid.isNull())
                uuid = QUuid::createUuid();

            CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(),
                ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid);
            ctcpEvents << event;
        }
    }
    if (!ctcpEvents.isEmpty()) {
        _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix())));
        CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(),
            ctcptype, "INVALID", QString(), e->timestamp(), uuid);
        ctcpEvents << flushEvent;
        foreach(CtcpEvent *event, ctcpEvents) {
            emit newEvent(event);
        }
Beispiel #12
0
void BasicHandler::displayMsg(Message::Type msgType, QString target, const QString &text, const QString &sender, Message::Flags flags) {
  if(!target.isEmpty() && network()->prefixes().contains(target[0]))
    target = target.mid(1);

  IrcChannel *channel = network()->ircChannel(target);
  if(!channel && (target.startsWith('$') || target.startsWith('#')))
    target = nickFromMask(sender);

  emit displayMsg(msgType, typeByTarget(target), target, text, sender, flags);
}
Beispiel #13
0
static void MAMACALLTYPE
msgCb (mamaSubscription  subscription, 
       mamaMsg           msg, 
       void*             closure,
       void*             itemClosure)
{
    if (gQuietLevel < 2)
    {
        printf ("mamasubscriberc: Recieved msg.\n");
    }
    displayMsg (msg);
}
Beispiel #14
0
double getZenithWetDelay(char *siteName, double mjd, int warnings)
{
  double zwd = getMeteorologicalValue(&zenithWetDelayTables, siteName, mjd,
				      warnings);
  if (zwd==0.0)
  {
    char msg[1000],msg2[1000];
    sprintf(msg,"Assume zero zenith wet delay (no data) for site %s  at MJD",
	    siteName);
    sprintf(msg2,"%.1f",mjd);
    displayMsg(1,"TROP1",msg,msg2,warnings);
  }

  return zwd;
}
Beispiel #15
0
double getSurfaceAtmosphericPressure(char *siteName, double mjd, int warnings)
{
  double sap = getMeteorologicalValue(&surfaceAtmosphericPressureTables, 
				      siteName, mjd,
				      warnings);
  if (sap==0.0)
  {
    char msg[1000],msg2[1000];
    sprintf(msg,"Assume standard atmospheric pressure (no data) for site %s at MJD",
	    siteName);
    sprintf(msg2,"%.1f",mjd);
    displayMsg(1,"TROP2",msg,msg2,warnings);
    sap = 101.325;
  }

  return sap;
}
Beispiel #16
0
chatServer::chatServer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::chatServer)
{
    ui->setupUi(this);
    numOfClients = 0;

    // connect gui to app
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(exitApp()));

    // create a mailbox for the server
    thread = new QThread();
    const char *mid = "/mailbox0";
    QString id = "Server";
    server = new msgSendRecv(id, mid);
    connect(this, SIGNAL(started()), server, SLOT(startRecv()));
    connect(server, SIGNAL(messageRecv(QString)), this, SLOT(displayMsg(QString)));
    server->moveToThread(thread);
    thread->start();
    // start reading the mailbox
    emit started();
}
Beispiel #17
0
double ELL1Hmodel(pulsar *psr,int p,int ipos,int param) {
    double an; // orbital angular velocity
    double x0,m2,tt0,orbits,phase,e1,e2,dre,drep,drepp,brace,dlogbr,ds,da,pb;
    double eps1,eps2,eps1dot,eps2dot,si,a0,b0,d2bar;
    double torb,Csigma,Cx,Ceps1,Ceps2,Cm2,Csi,ct,t0asc,pbdot,xpbdot,x,xdot,am2;
    int norbits;
    double SUNMASS = 4.925490947e-6;
    double ecc; // eccentricity
    double TrueAnom; // true anomaly
    double omega; // omega
    // fw10 parameters:
    double h3, h4, stig;
    double lgf; // intermediate derivative calculation
    int nharm=4;
    int mode = -1; // How to implement the fw10 model. There are four modes:
    // mode 0: Only h3 is fitted. This is an incomplete parameterisation of the
    //         Shapiro delay.
    // mode 1: h3 and stigma are fitted. This is a complete and exact parameterisation
    //         of the Shapiro delay and should only be used if the SD is well
    //         constrained.
    // mode 2: h3 and h4 fitted. This is an approximate parameterisation of the SD
    //         and can be translated in m2 and sini.
    // mode 3: h3, h4, nharm (>=5). This determines h3 and h4 and in doing so,
    //         takes nharm harmonics into account. In the lower limit (nharm = 4),
    //         this mode is identical to mode 2. In the higher limit (nharm->infty),
    //         this mode approaches mode 1. NHARM is a constant, integer input.
    //         Be aware that nharm>=5 can only be used in case h3 is clearly
    //         inconsistent with zero.

    a0 = 0.0; // WHAT SHOULD THESE BE? -- They should be zero because
    b0 = 0.0; // the Aberration delay is not yet implemented. (See below;
    // JPWV; 15 Jan 2010.)

    pb    = psr[p].param[param_pb].val[0]*SECDAY;

    if( psr[p].param[param_pbdot].paramSet[0] == 1 )
        pbdot = psr[p].param[param_pbdot].val[0];
    else
        pbdot=0.0;

    an    = 2.0*M_PI/pb;

    // Sanity check
    if( psr[p].param[param_h3].paramSet[0] != 1 ) {
        printf( "ERROR! Cannot use the ELL1H model without H3.\n" );
    } else
        h3 = psr[p].param[param_h3].val[0];
    //h3 = getParameterValue( &psr[p], param_h3, 0 );

    // Determine fw10 mode
    if( psr[p].param[param_h4].paramSet[0] == 1 ) {
        h4 = psr[p].param[param_h4].val[0];
        //    h4 = getParameterValue( &psr[p], param_h4, 0 );
        // mode 2 or 3 take preference over mode 1 as they are more stable
        if( psr[p].param[param_nharm].paramSet[0] == 1 ) {
            nharm = (int)psr[p].param[param_nharm].val[0];
            //nharm = (int)getParameterValue( &psr[p], param_nharm, 0 );
            if( nharm > 4 )
                mode = 3;
            else
                mode = 2;
        }
        if( psr[p].param[param_stig].paramSet[0] == 1 ) {
            // Conflict. Unsure whether to select mode 1 or modes 2/3, so will default
            // to the most stable one.
            logerr("You specified both H4 and STIG - Ignoring STIG");
            logmsg( "WARNING! You specified both H4 and STIG." );
            logmsg( "We will ignore STIG and perform the approx. H4 fit instead." );
            logmsg( "If you want to perform the exact fit for H3 and STIG, then " );
            logmsg( "please remove H4 from your parameter file.");
        }
        // Have H3, H4, but no NHARM
        mode = 2;
    } else {
        // Have H3, but no H4
        if( psr[p].param[param_stig].paramSet[0] == 1 ) {
            stig = psr[p].param[param_stig].val[0];
            //stig = getParameterValue( &psr[p], param_stig, 0 );
            mode = 1;
        } else {
            mode = 0;
            h4 = 0;
            nharm = 3;
        }
    }// fw10 mode determined.

    // Define sin(i) and m2 for calculation of the orbital phases etc.
    if( mode == 1 ) {
        // fw10, Eq. 22:
        si = 2.0 * stig / ( 1.0 + pow( stig, 2.0 ) );
        // fw10, Eq. 20:
        m2 = h3 / pow( stig, 3.0 ); // Shapiro r, not just M2.

        if( si > 1.0 ) {
            displayMsg(1,"BIN1",
                       "SIN I > 1.0, setting to 1: should probably use DDS model",
                       "",psr[p].noWarnings);
            si = 1.0;
            psr[p].param[param_sini].val[0] = longdouble(1.0);
        }
    } else if( mode == 2 || mode == 3 ) {
        // fw10, Eq. 25:
        si = 2.0 * h3 * h4 / ( h3 * h3 + h4 * h4 );
        // fw10, Eq. 26:
        m2 = pow( h3, 4.0 ) / pow( h4, 3.0 );
        if( si > 1.0 ) {
            displayMsg(1,"BIN1",
                       "SIN I > 1.0, setting to 1: should probably use DDS model",
                       "",psr[p].noWarnings);
            si = 1.0;
            psr[p].param[param_sini].val[0] = longdouble(1.0);
        }
    } else if( mode == 0 ) {
        // Cannot determine m2 and/or sini. Will have to determine the
        // Shapiro delay based on h3 alone.
    } else {
        printf( "This should not be possible. Go Away.\n" );
        printf( "And tell someone about it: [email protected], e.g.\n" );
    }


    x0    = psr[p].param[param_a1].val[0];
    if( psr[p].param[param_a1dot].paramSet[0] == 1 )
        xdot  = psr[p].param[param_a1dot].val[0];
    else
        xdot = 0.0;

    t0asc = psr[p].param[param_tasc].val[0];

    xpbdot = 0.0;
    eps1  = psr[p].param[param_eps1].val[0];
    eps2  = psr[p].param[param_eps2].val[0];
    if( psr[p].param[param_eps1dot].paramSet[0] == 1 )
        eps1dot = psr[p].param[param_eps1dot].val[0];
    else
        eps1dot=0;

    if( psr[p].param[param_eps2dot].paramSet[0] == 1 )
        eps2dot = psr[p].param[param_eps2dot].val[0];
    else
        eps2dot=0;

    ct = psr[p].obsn[ipos].bbat;
    tt0 = (ct-t0asc)*SECDAY;
    orbits = tt0/pb-0.5*(pbdot+xpbdot)*pow(tt0/pb,2);
    norbits = (int)orbits;
    if( orbits < 0.0 )
        norbits = norbits-1;

    phase = 2.0*M_PI*(orbits-norbits);

    x = x0+xdot*tt0;

    e1 = eps1+eps1dot*tt0;
    e2 = eps2+eps2dot*tt0;
    dre  = x*(sin(phase)-0.5*(e1*cos(2.0*phase)-e2*sin(2.0*phase)));
    drep = x*cos(phase);
    drepp=-x*sin(phase);

    brace = 1.0 - si * sin( phase );
    dlogbr = log( brace );

    ecc = sqrt( e1 * e1 + e2 * e2 );
    TrueAnom = phase;
    //TrueAnom = 2.0 * atan2( sqrt( 1.0 + ecc ) * sin( phase / 2.0 ),
    //                       sqrt( 1.0 - ecc ) * cos( phase / 2.0 ) );
    omega = atan2( e1, e2 );
    //lgf = log( 1.0 + stig * stig - 2.0 * stig * sin( TrueAnom + omega ) );
    double lsc, fs;
    fs = 1.0 + stig * stig - 2.0 * stig * sin( TrueAnom );
    lgf = log( fs );
    lsc = lgf + 2.0 * stig * sin( TrueAnom ) - stig * stig * cos( 2.0 * TrueAnom );

    if( mode == 0 ) {
        // mode 0: only h3 is known.
        ds = -4.0 / 3.0 * h3 * sin( 3.0 * TrueAnom );
    } else if( mode == 1 ) {
        ds = -2.0 *m2* lsc;
        //ds = -2.0 * m2 * dlogbr;
    } else { // modes 2 and 3
        ds = calcDH( TrueAnom, h3, h4, nharm, 0 );
    }

    /* ================
       ABERRATION DELAY
       ================ */
    /* NOTE: a0 and b0 are always zero -- they are not set in the
       original TEMPO!!!!! */
    da=a0*sin(phase)+b0*cos(phase);

    /*  Now compute d2bar (cf. DD 52) */

    // I suspect this following equation gives the expansion of the
    // R\"omer delay, then the Shapiro delay (ds) and finally the
    // aberration delay (da). The Aberration dealy is, however,
    // unmeasurably small in all presently known systems - this is why
    // da == 0, implied by a0 == 0 and b0 == 0. (JPWV; 15 Jan 2010)
    d2bar=dre*(1-an*drep+pow(an*drep,2)+0.5*pow(an,2)*dre*drepp)+ds+da;
    torb=-d2bar;
    if( param == -1 )
        return torb;

    /* Now we need the partial derivatives. */
    Csigma   = x*cos(phase);
    Cx       = sin(phase);
    Ceps1    = -0.5*x*cos(2*phase);
    Ceps2    =  0.5*x*sin(2*phase);
    Cm2      = -2*dlogbr;
    Csi      = 2*m2*sin(phase)/brace;
    if( param == param_pb ) {
        return -Csigma*an*SECDAY*tt0/(pb*SECDAY); /* Pb    */

    } else if( param == param_a1 ) {
        return Cx;

    } else if( param == param_eps1 ) {
        return Ceps1;

    } else if( param == param_tasc ) {
        return -Csigma*an*SECDAY;

    } else if( param == param_eps2 ) {
        return Ceps2;

    } else if( param == param_eps1dot ) {
        return Ceps1*tt0;

    } else if( param == param_eps2dot ) {
        return Ceps2*tt0;

    } else if( param == param_pbdot ) {
        return 0.5*tt0*(-Csigma*an*SECDAY*tt0/(pb*SECDAY));

    } else if( param == param_a1dot ) {
        return Cx*tt0;

    } else if( param == param_sini ) {
        return Csi;

    } else if( param == param_m2 ) {
        return Cm2*SUNMASS;

    } else if( param == param_stig ) {
        return( -2.0 * m2 / stig * ( 1.0 - 3.0 * lgf - ( 1.0 - stig * stig ) / fs )
                + 2.0 * m2 * ( 4.0 * sin( TrueAnom ) - stig * cos( 2.0 * TrueAnom ) ) );
        //return( -2.0 * m2 / stig *
        //        ( 1.0 + 3.0 * lgf - ( 1.0 - stig * stig ) /
        //          ( 1.0 + stig * stig - 2.0 * stig * sin( TrueAnom + omega ) ) ) );
        //       //+ 2.0 * m2 * ( 4.0 * sin( TrueAnom ) - stig * cos( 2.0 * TrueAnom ) ) );
    } else if( param == param_h3 ) {
        if( mode == 0 || mode == 2)
            return( -4.0 / 3.0 * sin( 3.0 * TrueAnom ) );
        else if( mode == 1 ) {
            return( -2.0 * lsc / pow( stig, 3.0 ) );
            //return( 2.0 / pow( stig, 3.0 ) *
            //        ( lgf + 2.0 * stig * sin( TrueAnom ) - stig * stig * cos( TrueAnom ) ) );
        } else if( mode == 3 )
            return( calcDH( TrueAnom, h3, h4, nharm, 3 ) );
        else {
            printf( "ERROR in ELL1H. This really shouldn't happen.\n" );
        }
    } else if( param == param_h4 ) {
        if( mode == 2 )
            return( cos( 4.0 * TrueAnom ) );
        else
            return( calcDH( TrueAnom, h3, h4, nharm, 4 ) );
    }

    return 0.0;
}
Beispiel #18
0
double T2model(pulsar *psr,int p,int ipos,int param,int arr)
{
    double an;
    double pb,omdot;
    double rad2deg = 180.0/M_PI;
    double SUNMASS = 4.925490947e-6;
    longdouble tt0,t0,ct,t0asc;
    double m2,x,ecc,er,xdot,edot,dr,dth,eth;
    double pbdot,xpbdot,phase,u,gamma;
    double orbits;
    int    norbits;
    double cu,onemecu=0,cae,sae,ae,omega,omz,sw,cw,alpha,beta,bg,dre,drep,drepp,
           anhat,su=0;
    double sqr1me2,cume,brace,si,dlogbr,ds,da,a0,b0,d2bar,torb;
    double csigma,ce,cx,comega,cgamma,cdth,cm2,csi, ckom, ckin;
    double eps1,eps2,eps1dot,eps2dot;
    double ceps1,ceps2;
    double shapmax,cshapmax,sdds;
    int    com,com1,com2;
    int    allTerms=1;            /* = 0 to emulate BT model */
    double dpara;
    double pmra,pmdec;
    double sin_omega,cos_omega,ki;
    double mtot,m1,xk,xomdot,afac,kom;
    longdouble DK011,DK012, DK021, DK022, DK031,DK032, DK041,DK042,C,S;
    longdouble DK013, DK014, DK023, DK024, DK033, DK034, DK043, DK044;
    longdouble DAOP=longdouble(0.0), DSR=longdouble(0.0);
    longdouble DOP=longdouble(0.0); // Orbital parallax time delay
    double daop;// DAOP is the time delay due to annual orbital
    // parallax. daop is the aop distance.

    longdouble h3,h4,stig;
    longdouble lgf,TrueAnom;
    longdouble lsc, fs;
    int nharm=4;
    int mode = -1; // See ELL1Hmodel.C

    torb = 0.0;
    const char *CVS_verNum = "$Id: d5e412cf859761421154f47be2a083ae696d674f $";


    if (displayCVSversion == 1) 
        CVSdisplayVersion("T2model.C","T2model()",CVS_verNum);

    if (param==-1) 
    {
        com1 = 0;
        com2 = psr[p].nCompanion;
    }
    else
    {
        com1 = arr;
        com2 = arr+1;
    }

    //    printf("Number of companions = %d %d\n",com1,com2);

    for (com = com1; com < com2;com++)
    {      
        /* Obtain Keplerian parameters */   
        getKeplerian(&psr[p],com,&pb,&t0,&ecc,&omz,&x,&eps1,&eps2,&t0asc,
                &shapmax,&kom,&ki);
        /* Now add in the jumps */
        addKeplerianJumps(&psr[p],ipos,&torb,&x,&ecc,&omz,&pb);
        /* Parameters derived from the Keplerian parameters */
        deriveKeplerian(pb,kom,&an,&sin_omega,&cos_omega);
        /* Obtain post-Keplerian parameters */
        getPostKeplerian(&psr[p],com,an,&si,&m2,&mtot,&omdot,&gamma,&xdot,&xpbdot,
                &pbdot,&edot,&pmra,&pmdec,&dpara,&dr,&dth,&a0,&b0,
                &xomdot,&afac,&eps1dot,&eps2dot,&daop);

        /* If the beta-prime parameters are set then omdot, gamma, si, dr, er, 
           dth, a0 and b0 can be calculated from the beta-prime values
         * - see papers of Taylor, Wolszczan, Damour & Weisberg 1992 - Nature
         *                 Damour & Taylor 1992 - Phys Rev D
         */
        if (psr[p].param[param_bp].paramSet[0]==1 && 
                psr[p].param[param_bpp].paramSet[0]==1)
        {
            /*	  useBeta(psr[p]); */
            printf("Beta model not implemented yet\n");
        }

        /* If general relativity is assummed to be correct and 
         * the total system mass has been determined then the values 
         * of dr,dth,er, eth, sini, gamma and pbdot can be calculated
         */
        if (psr[p].param[param_mtot].paramSet[com]==1)
        {
            calcGR(mtot,m2,x,ecc,an,afac,(double)psr[p].param[param_f].val[0],
                    &dr,&dth,&er,&eth,&xk,&si,&gamma,&pbdot,&a0,&b0);
            omdot   = xomdot + xk; 
        }
        /* Derive parameters from the post-Keplerian parameters */
        derivePostKeplerian(mtot,m2,dr,dth,ecc,&m1,&er,&eth);
        /* Obtain delta T */
        ct  = psr[p].obsn[ipos].bbat;      
        if (psr[p].param[param_t0].paramSet[com]==1)        
            tt0 = (ct-t0)*SECDAY;
        else if( psr[p].param[param_tasc].paramSet[com]==1) 
            tt0 = (ct-t0asc)*SECDAY;
        else {
            printf("ERROR [T2] T0 or TASC needs to be set in the parameter file\n");
            exit(1);
        }
        //      logdbg("going to update Parameters");
        /* Update parameters with their time derivatives */
        updateParameters(edot,xdot,eps1dot,eps2dot,tt0,&ecc,&x,&eps1,&eps2);
        //      logdbg("updated parameters");

        /* Do some checks */
        if (ecc < 0.0 || ecc > 1.0)
        {
            displayMsg(1,"BIN2","Eccentricity of orbit < 0, setting to 0","",
                    psr[p].noWarnings);
            psr[p].param[param_ecc].val[com]=0.0;
            ecc = 0.0;
        }

        /* Obtain number of orbits in tt0 */
        orbits  = tt0/pb - 0.5*(pbdot+xpbdot)*pow(tt0/pb,2);
        norbits = (int)orbits;
        if (orbits<0.0) norbits--;

        /* Obtain phase of orbit */
        phase=2.0*M_PI*(orbits-norbits);
        //      ld_printf("Orbit phase = %.15Lf %.15g\n",psr[p].obsn[ipos].bbat,phase);
        if (psr[p].param[param_ecc].paramSet[com]==1)
        {
            //          logdbg("going to compute U");
            /* Compute eccentric anomaly u by iterating Kepler's equation */	 
            computeU(phase,ecc,&u);
            //          logdbg("computed U");
            /*  DD equations 17b and 17c */
            su=sin(u); cu=cos(u);
            onemecu=1.0-ecc*cu;
            cae=(cu-ecc)/onemecu;                         /* Equation 17b */
            sae=sqrt(1.0-pow(ecc,2))*su/onemecu;          /* Equation 17c */
            ae=atan2(sae,cae);
            if(ae<0.0) ae=ae+2.0*M_PI;
            ae=2.0*M_PI*orbits + ae - phase;
            omega=omz/rad2deg + omdot*ae;
            sw=sin(omega);
            cw=cos(omega);
            //          logdbg("In the middle of DD");
            /* DD equations 26, 27, 57: */
            sqr1me2=sqrt(1-pow(ecc,2));
            cume=cu-ecc;
            //          logdbg("going to Kopeikin");
            /* Update parameters due to proper motion - Kopeikin 1996 */
            /* And annual-orbital and orbital parallax - Kopeikin 1995 */
            if (psr[p].param[param_kin].paramSet[com]==1 && 
                    psr[p].param[param_kom].paramSet[com]==1 &&
                    (psr[p].param[param_pmra].paramSet[com]==1 || 
                     psr[p].param[param_pmdec].paramSet[com]==1))
            {
                //              logdbg("going to do KopeikinTerms");
                KopeikinTerms(&psr[p],ipos,ki,pmra,sin_omega,pmdec,cos_omega,tt0,
                        dpara,daop,si,&x,&DK011,&DK012,&DK021,&DK022,
                        &DK031,&DK032,&DK041,&DK042,&DK013,&DK014,&DK023,
                        &DK024,&DK033,&DK034,&DK043,&DK044);
                //              logdbg("did KopeikinTerms");
                C = (longdouble)(cw*(cu-er)-sqrt(1.0-pow(eth,2.0))*sw*su);
                S = (longdouble)(sw*(cu-er)+cw*sqrt(1.0-pow(eth,2.0))*su);
                DAOP = (DK011+DK012)*C-(DK021+DK022)*S;
                DSR = (DK031+DK032)*C+(DK041+DK042)*S;
                DOP = dpara/AULTSC/2.0*pow(x,2.0)*
                    ( pow( sin( ki ), -2.0 ) - 0.5 + 0.5 * pow( ecc, 2.0 ) *
                      ( 1 + pow( sw, 2.0 ) - 3.0 / pow( sin( ki ), 2.0 ) ) -
                      2.0 * ecc * ( pow( sin( ki ), -2.0 ) - pow( sw, 2.0 ) ) * 
                      cume - sqr1me2 * 2 * sw * cw * su * cume + 0.5 * 
                      ( cos( 2.0 * omega ) + pow( ecc, 2.0 ) * 
                        ( pow( sin( ki ), -2.0 ) + pow( cu, 2.0 ) ) ) *
                      cos( 2.0 * u ) );

                //	      printf("T2model: %g DAOP = %g DSR = %g DOP = %g\n",(double)psr[p].obsn[ipos].bbat,(double)DAOP,(double)DSR,(double)DOP);

                //                logdbg("DAOP is %g and DSR is %g\n", (double)DAOP, (double)DSR);
                //                logdbg("DAOP is %g, DK011 and DK021 are %f and %f\n",
                //                       (double)DAOP,(double)DK011,(double)DK021);
            }


            if (psr[p].param[param_shapmax].paramSet[com]==1)  /* DDS model */
            {
                sdds  = 1.0 - exp(-1.0*shapmax);
                brace = onemecu-sdds*(sw*cume+sqr1me2*cw*su);
            }
            else
                brace=onemecu-si*(sw*cume+sqr1me2*cw*su);

            da=a0*(sin(omega+ae) + ecc*sw) + b0*(cos(omega+ae) + 
                    ecc*cw); /* Equation 27 */

            /* DD equations 46 to 51 */	  
            alpha=x*sw;                                   /* Equation 46  */
            beta=x*sqrt(1-pow(eth,2))*cw;                 /* Equation 47  */
            bg=beta+gamma;
            dre=alpha*(cu-er) + bg*su;                    /* Equation 48  */
            drep=-alpha*su + bg*cu;                       /* Equation 49  */
            drepp=-alpha*cu - bg*su;                      /* Equation 50  */
            anhat=an/onemecu;                             /* Equation 51  */

            dlogbr=log(brace);
            ds=-2*m2*dlogbr;        /* Equation 26 */

        }
        else if (psr[p].param[param_eps1].paramSet[com]==1)  /* ELL1 model */
        {
            dre  = x*(sin(phase)-0.5*(eps1*cos(2.0*phase)-eps2*sin(2.0*phase)));
            drep = x*cos(phase);
            drepp=-x*sin(phase);
            //          logdbg("going to Kopeikin");
            /* Update parameters due to proper motion - Kopeikin 1996 */
            if (psr[p].param[param_kin].paramSet[com]==1 && 
                    psr[p].param[param_kom].paramSet[com]==1 &&
                    (psr[p].param[param_pmra].paramSet[com]==1 || 
                     psr[p].param[param_pmdec].paramSet[com]==1))
            {
                S = (sin(phase)-0.5*(eps1*cos(2.0*phase)-eps2*sin(2.0*phase)));
                C = cos(phase)+0.5*(eps2*cos(2.0*phase)+eps1*sin(2.0*phase));
                KopeikinTerms(&psr[p],ipos,ki,pmra,sin_omega,pmdec,cos_omega,tt0,
                        dpara,daop,si,&x,&DK011,&DK012,&DK021,&DK022,
                        &DK031,&DK032,&DK041,&DK042,&DK013,&DK014,&DK023,
                        &DK024,&DK033,&DK034,&DK043,&DK044);
                DAOP = (DK011+DK012)*C-(DK021+DK022)*S;
                DSR = (DK031+DK032)*C+(DK041+DK042)*S;
            }

            brace=1-si*sin(phase);
            da=a0*sin(phase)+b0*cos(phase);  

            anhat = an; ecc = 0.0;


            /* Shapiro delay */
            if ( psr[p].param[param_h3].paramSet[0] * psr[p].param[param_stig].paramSet[0] == 1 
                    || psr[p].param[param_h3].paramSet[0] * psr[p].param[param_h4].paramSet[0] == 1){

                //	    printf("Using the Friere & Wex formalism for the Shapiro delay\n");
                // Based on ELL1Hmodel.C

                //h3 = psr[p].param[param_h3].val[0];
                h3 = getParameterValue( &psr[p], param_h3, 0 );

                // Determine fw10 mode
                if( psr[p].param[param_h4].paramSet[0] == 1 ){
                    //	      h4 = psr[p].param[param_h4].val[0];
                    h4 = getParameterValue( &psr[p], param_h4, 0 );
                    // mode 2 or 3 take preference over mode 1 as they are more stable
                    if( psr[p].param[param_nharm].paramSet[0] == 1 ){
                        nharm = (int)psr[p].param[param_nharm].val[0];
                        //nharm = (int)getParameterValue( &psr[p], param_nharm, 0 );
                        if( nharm > 4 )
                            mode = 3;
                        else
                            mode = 2;
                    }
                    if( psr[p].param[param_stig].paramSet[0] == 1 ){
                        // Conflict. Unsure whether to select mode 1 or modes 2/3, so will default
                        // to the most stable one.
                        logerr("You specified both H4 and STIG - Ignoring STIG");
                        logmsg( "WARNING! You specified both H4 and STIG." );
                        logmsg( "We will ignore STIG and perform the approx. H4 fit instead." );
                        logmsg( "If you want to perform the exact fit for H3 and STIG, then " );
                        logmsg( "please remove H4 from your parameter file.");
                    }
                    // Have H3, H4, but no NHARM
                    mode = 2;
                }else{ 
                    // Have H3, but no H4
                    if( psr[p].param[param_stig].paramSet[0] == 1 ){
                        //		stig = psr[p].param[param_stig].val[0];
                        stig = getParameterValue( &psr[p], param_stig, 0 );
                        mode = 1;
                    }else{
                        mode = 0;
                        h4 = 0;
                        nharm = 3;
                    }
                }// fw10 mode determined.

                // Define sin(i) and m2 for calculation of the orbital phases etc.
                if( mode == 1 ){
                    // fw10, Eq. 22:
                    si = 2.0 * stig / ( 1.0 + pow( stig, 2.0 ) );
                    // fw10, Eq. 20:
                    m2 = h3 / pow( stig, 3.0 ); // Shapiro r, not just M2.

                    if( si > 1.0 ){
                        displayMsg(1,"BIN1",
                                "SIN I > 1.0, setting to 1: should probably use DDS model",
                                "",psr[p].noWarnings);
                        si = 1.0;
                        psr[p].param[param_sini].val[0] = longdouble(1.0);
                    }
                }else if( mode == 2 || mode == 3 ){
                    // fw10, Eq. 25:
                    si = 2.0 * h3 * h4 / ( h3 * h3 + h4 * h4 );
                    // fw10, Eq. 26:
                    m2 = pow( h3, 4.0 ) / pow( h4, 3.0 );
                    if( si > 1.0 ){
                        displayMsg(1,"BIN1",
                                "SIN I > 1.0, setting to 1: should probably use DDS model",
                                "",psr[p].noWarnings);
                        si = 1.0;
                        psr[p].param[param_sini].val[0] = longdouble(1.0);
                    }
                }else if( mode == 0 ){
                    // Cannot determine m2 and/or sini. Will have to determine the
                    // Shapiro delay based on h3 alone.
                }else{
                    printf( "This should not be possible. Go Away.\n" );
                    printf( "And tell someone about it: [email protected], e.g.\n" );
                }
                brace=1-si*sin(phase);
                dlogbr=log(brace);

                ecc = sqrt( eps1 * eps1 + eps2 * eps2 );
                TrueAnom = phase;
                //TrueAnom = 2.0 * atan2( sqrt( 1.0 + ecc ) * sin( phase / 2.0 ), 
                //                       sqrt( 1.0 - ecc ) * cos( phase / 2.0 ) );
                omega = atan2( eps1, eps2 );
                //lgf = log( 1.0 + stig * stig - 2.0 * stig * sin( TrueAnom + omega ) );

                fs = 1.0 + stig * stig - 2.0 * stig * sin( TrueAnom );
                lgf = log( fs );
                lsc = lgf + 2.0 * stig * sin( TrueAnom ) - stig * stig * cos( 2.0 * TrueAnom );

                if( mode == 0 ){
                    // mode 0: only h3 is known. 
                    ds = -4.0 / 3.0 * h3 * sin( 3.0 * TrueAnom );
                }else if( mode == 1 ){
                    ds = -2.0 *m2* lsc;
                    //ds = -2.0 * m2 * dlogbr;
                }else{ // modes 2 and 3
                    ds = calcDH( TrueAnom, h3, h4, nharm, 0 );
                }

            }
            else{
                dlogbr=log(brace);
                ds=-2*m2*dlogbr;        /* Equation 26 */
            }

        }
        else
        {
            printf("Require eccentricity set or EPS1/EPS2 parameters for companion %d\n",com+1);
            exit(1);
        }
        // printf("T2: %g %g %g %g %g %g %g\n",brace,phase,a0,b0,dlogbr,ds,m2);

        /* Now compute d2bar, the orbital time correction in DD equation 42. */
        /* Equation 52 */
        if (onemecu != 0.0)
        {
            d2bar=dre*(1-anhat*drep+allTerms*pow(anhat,2)*
                    (pow(drep,2) + 0.5*dre*drepp - 
                     0.5*ecc*su*dre*drep/onemecu)) + allTerms*(ds+da+DAOP+DSR
                     + DOP);
        }
        else
        {
            d2bar=dre*(1-anhat*drep+allTerms*pow(anhat,2)*
                    (pow(drep,2) + 0.5*dre*drepp))
                + allTerms*(ds+da+DAOP+DSR+DOP);
        }    
        //      printf("T2a: %g %g %g %g %g drepp=%g ecc=%g su =%g ome =%g ds = %g da = %g %g %g\n",(double)d2bar,(double)dre,(double)anhat,(double)drep,(double)allTerms,(double)drepp,(double)ecc,(double)su,(double)onemecu,(double)ds,(double)da,(double)DAOP,(double)DSR);
        torb-=d2bar;                                  /* Equation 42  */

        if (param==-1 && com == psr[p].nCompanion-1) return torb;
        else if (param!=-1 && com==arr)
        {
            // Now we need the partial derivatives. Use DD equations 62a - 62k.
            if (psr[p].param[param_ecc].paramSet[com]==1)
            {
                csigma=x*(-sw*su+sqr1me2*cw*cu)/onemecu;      /* Equation 62a */
                ce=su*csigma-x*sw-ecc*x*cw*su/sqr1me2;        /* Equation 62c */
                cx=sw*cume+sqr1me2*cw*su;                     /* Equation 62d */
                comega=x*(cw*cume-sqr1me2*sw*su);             /* Equation 62e */
                cgamma=su;                                    /* Equation 62g */
                cdth=-ecc*ecc*x*cw*su/sqr1me2;                /* Equation 62i */
                cm2=-2*dlogbr;                                /* Equation 62j */
                if (psr[p].param[param_shapmax].paramSet[com]==1)
                    cshapmax = 2*m2*(sw*cume+sqr1me2*cw*su)/brace * (1.0-sdds);
                else if (psr[p].param[param_sini].nLinkTo>0){
                    csi= 2*m2*(sw*cume+sqr1me2*cw*su)*cos(ki)/brace;
                }
                else
                    csi=2*m2*(sw*cume+sqr1me2*cw*su)/brace;     /* Equation 62k */
            }
            else if (psr[p].param[param_eps1].paramSet[com]==1) /* ELL1 model */
            {
                csigma = x*cos(phase);
                cx     = sin(phase);
                ceps1  = -0.5*x*cos(2*phase);
                ceps2  =  0.5*x*sin(2*phase);
                cm2    = -2*dlogbr;
                csi    = 2*m2*sin(phase)/brace;
            }

            if (param==param_pb)	         return -csigma*an*SECDAY*tt0/pb; 
            else if (param==param_a1)      return cx;
            else if (param==param_ecc)     return ce;
            else if (param==param_edot)     return ce*tt0;
            else if (param==param_om)      return comega;
            else if (param==param_omdot)   
                return ae*comega/(an*360.0/(2.0*M_PI)*365.25*SECDAY);
            else if (param==param_t0)      return -csigma*an*SECDAY;
            else if (param==param_pbdot){
                if(psr[p].param[param_pbdot].nLinkFrom>0){
                    return 0.5*tt0*(-csigma*an*SECDAY*tt0/(pb*SECDAY));
                    /*- SPEED_LIGHT/(getParameterValue(&psr[p],param_pb,0)*SECDAY*
                      (pow(getParameterValue(&psr[p],param_pmra,0)*MASYR2RADS,2)+
                      pow(getParameterValue(&psr[p],param_pmdec,0)*MASYR2RADS,2))*
                      getParameterValue(&psr[p],param_daop,0))*
                      (C*(-DK011-DK012)+S*(DK021+DK022));*/
                }
                else  return 0.5*tt0*(-csigma*an*SECDAY*tt0/(pb*SECDAY));
            }
            else if (param==param_sini)    return csi;
            else if (param==param_gamma)   return cgamma;
            else if (param==param_m2)      return cm2*SUNMASS;
            else if (param==param_a1dot)   return cx*tt0;
            else if (param==param_eps1)    return ceps1;
            else if (param==param_eps1dot) return ceps1*tt0;
            else if (param==param_eps2dot) return ceps2*tt0;
            else if (param==param_eps2)    return ceps2;
            else if (param==param_tasc)    return -csigma*an*SECDAY;
            else if (param==param_shapmax) return cshapmax;
            else if (param==param_stig){
                return( -2.0 * m2 / stig * ( 1.0 - 3.0 * lgf - ( 1.0 - stig * stig ) / fs ) 
                        + 2.0 * m2 * ( 4.0 * sin( TrueAnom ) - stig * cos( 2.0 * TrueAnom ) ) );	    
            }
            else if (param==param_h3) {
                if( mode == 0 || mode == 2)
                    return( -4.0 / 3.0 * sin( 3.0 * TrueAnom ) );
                else if( mode == 1 ){
                    return( -2.0 * lsc / pow( stig, 3.0 ) );
                    //return( 2.0 / pow( stig, 3.0 ) * 
                    //        ( lgf + 2.0 * stig * sin( TrueAnom ) - stig * stig * cos( TrueAnom ) ) );
                }else if( mode == 3 )
                    return( calcDH( TrueAnom, h3, h4, nharm, 3 ) );
                else{
                    printf( "ERROR in ELLH model in T2. This really shouldn't happen.\n" );
                }
            }else if( param == param_h4 ){
                if( mode == 2 )
                    return( cos( 4.0 * TrueAnom ) );
                else
                    return( calcDH( TrueAnom, h3, h4, nharm, 4 ) );
            }	  
            else if (param==param_kom){
                ckom = C* (DK033+DK034+DK013+DK014) + S*(DK043+DK044+DK023+DK024);
                return ckom;
            }
            else if (param==param_kin){
                ckin = C/sin(ki)*(DK043+DK044+DK023+DK024)-
                    S/sin(ki)*(DK013+DK014+DK033+DK034);
                if( psr[p].param[param_ecc].paramSet[com]== 1 )
                    ckin += dpara/AULTSC/2.0*pow( x, 2.0 ) * cos( ki ) *
                        pow( sin( ki ), -3.0 ) * 
                        ( pow( ecc, 2.0 ) * ( 3.0 - cos( 2.0 * u ) ) + 
                          4.0 * ecc * cume - 2.0 );
                if(psr[p].param[param_kin].nLinkFrom>0)
                    ckin += csi; //  * cos( ki );
                return ckin;
            }
            /* Update the binary parameter jumps */
            if (psr[p].param[param_bpjep].paramSet[arr]==1 && 
                    psr[p].obsn[ipos].bbat > psr[p].param[param_bpjep].val[arr])
            {
                if (param==param_bpjph)
                    return 1.0/psr[p].param[param_f].val[0];
                else if (param==param_bpja1) return cx;
                else if (param==param_bpjec) return ce;
                else if (param==param_bpjom) return comega;
                else if (param==param_bpjpb)
                    return -csigma*an*SECDAY*tt0/(pb*SECDAY); 
            }
            else
                return 0.0;
        }
    }
    return 0.0;
}
Beispiel #19
0
/* ******************************************** */
double ut1red(double mjd, int warnings)
{
    static int read=0;
    static double mjd1,mjd2;
    static int mjdVal[1000];
    static int entry[10000];
    static int count2=0,count=0;
    double t,s,f2,y2[2],y1[2],ut1;
    double units = 1.0e-4;
    double tab[4];
    int nread,i,iint=5,it,itsav=-1,j,nr;
    char line[1000],fname[MAX_FILELEN];
    FILE *fin;

    if (read==0) /* Read data file */
    {
        strcpy(fname,getenv(TEMPO2_ENVIRON));
        strcat(fname,UT1_FILE);

        fin = fopen(fname,"r");
        if (!fin)
        {
            fprintf(stderr, "Could not open UT1 file: %s\n", fname);
            exit(1);
        }
        fgets(line,1000,fin); /* Read two header lines (I hope that these don't change!!!!) */
        fgets(line,1000,fin); /* ... no checks are done ... */
        nread=1;
        while ( (nread==1) && (fgets(line,1000,fin)!=NULL) )
        {
            // Chop off everything past char 57 to avoid the extra 'item
            // count' value being read in as either a UT1 value or an MJD.
            line[57]='\0';
            nread = sscanf(line,"%d %d %d %d %d %d %d",&mjdVal[count],
                           &entry[count2+0], &entry[count2+1], &entry[count2+2],
                           &entry[count2+3], &entry[count2+4], &entry[count2+5]);
            if (nread>1)
            {
                count++;
                for (i=0; i<nread-1; i++)
                {
                    if (entry[count2]!=0)
                        count2++;
                    else
                        nread=-1;
                }
                if (nread>0) {
                    nread=1;
                }
            }
            else
            {
                nread=-1;
            }
            if (count>999) /* Too many lines? */
            {
                printf("ERROR: Too many lines in ut1 file -- increase array size in tai2tdb\n");
                exit(1);
            }
        }
        fclose(fin);
        mjd1 = mjdVal[0]+iint; /* iint = interval in days between tabular values */
        mjd2 = mjdVal[count-1]-iint; /* Not sure about this + and - iint  *******************/
    }

    read=1;

    /* Is MJD within range of table */
    if (mjd>mjd1 && mjd<mjd2)
    {
        /* Calculate interpolation times and value of tabular points */
        t = (mjd-mjd1)/iint;
        it = (int)t;
        t = t - it;
        s=1.0-t;
        if (it!=itsav)
        {
            for (i=0; i<4; i++)
            {
                j=it+i;
                tab[i]=entry[j];
            }
            for (i=0; i<2; i++)
            {
                nr = i+1;
                f2 = 1.0/6.0 * (tab[nr+1]+tab[nr-1]);
                y1[i] = 4.0/3.0 * tab[nr] -f2;
                y2[i] = -1.0/3.0 * tab[nr]+f2;
            }
            itsav = it;
        }
        /* second difference interpolation */
        ut1 = (t*(y1[1]+t*t*y2[1]) + s*(y1[0]+s*s*y2[0]))*units;
        /*	printf("UT1 for %f = %f\n",mjd,ut1); */
    }
    else
    {
        char msg[1000],msg2[1000];
        sprintf(msg,"MJD is outside of UT1 table range ");
        sprintf(msg2,"(MJD %f)",mjd);
        displayMsg(1,"CLK10",msg,msg2,warnings);

        /* Extrapolate using last value in table */
        if (mjd<=mjd1)
            ut1 = entry[0]*units;
        else
            ut1 = entry[count2-1]*units;
    }

//     ut1 = atut-0.0343817 - ut1; /* Table TAI-UT1 */
    return -ut1;

}
Beispiel #20
0
double DDHmodel(pulsar *psr,int p,int ipos,int param){
    longdouble an; // angular velocity
    longdouble pb,k; // orbital period and unitless orbital precession
    // conversion factors
    longdouble rad2deg = 180.0/M_PI; 
    longdouble SUNMASS = 4.925490947e-6;
    // binary parameters
    longdouble m2,tt0,t0,x,ecc,er,xdot,edot,dr,dth,eth,ct;
    // more obscure orbital parameters
    longdouble pbdot,xpbdot,phase,u,du,gamma;
    longdouble orbits;
    int norbits;
    // DDH specific orbital parameters:
    longdouble h3, stig;// 3rd, 4th harmonics and harmonic ratio
    // needed for intermediate steps in calculations
    longdouble  cu,onemecu,cae,sae,ae,omega,omz,sw,cw,alpha,beta,bg,dre,
                drep,drepp,anhat,su;
    longdouble sqr1me2,cume,brace,si,dlogbr,ds,da,a0,b0,d2bar,torb;
    longdouble csigma,ce,cx,comega,cgamma,cm2,csi;
    // Aberration parameters (JPWV thinks so, at least).
    dr = 0.0; /* WHAT SHOULD THESE BE SET TO? */
    dth = 0.0; 

    // Sanity check
    if( psr[p].param[param_h3].paramSet[0] * psr[p].param[param_stig].paramSet[0] != 1 ){
        printf("ERROR! For the DDH model, both h3 and stig must be set.\n Exiting.\n");
        exit( 1 );
    }
    h3 = getParameterValue( &psr[p], param_h3, 0 );
    stig = getParameterValue( &psr[p], param_stig, 0 );

    // Define sin(i) and m2 for calculation of the orbital phases etc.
    // FW10, Eq. 22:
    si = 2.0 * stig / ( 1.0 + pow( stig, 2.0 ) );

    // FW10, Eq. 20:
    m2 = h3 / pow( stig, 3.0 ); // Shapiro r, not just M2.

    if (si > 1.0){
        displayMsg(1,"BIN1",
                "SIN I > 1.0, setting to 1: should probably use DDS model",
                "",psr[p].noWarnings);
        si = 1.0;
        psr[p].param[param_sini].val[0] = longdouble(1.0);
    }

    pb = psr[p].param[param_pb].val[0]*SECDAY;
    an = 2.0*M_PI/pb;
    // k is the orbital precession expressed in orbits per orbit
    k = psr[p].param[param_omdot].val[0]/(rad2deg*365.25*86400.0*an);
    // this equation is effectively the same as (omdot/360) * (pb/365.25)

    t0 = psr[p].param[param_t0].val[0];
    ct = psr[p].obsn[ipos].bbat;    

    tt0 = (ct-t0)*SECDAY;

    if (psr[p].param[param_gamma].paramSet[0]==1)
        gamma = psr[p].param[param_gamma].val[0];
    else
        gamma = 0.0;

    // JPWV thinks a0 and b0 are the aberration delays and are at
    // present not implemented. No way to be sure though, short of
    // asking George. Or, more likely, to spend more time to try and get
    // to the bottom of this. I cannot be bothered either way.
    a0    = 0.0;
    b0    = 0.0;

    if (psr[p].param[param_om].paramSet[0]==1) 
        omz = psr[p].param[param_om].val[0];
    else omz = 0.0;

    if (psr[p].param[param_a1dot].paramSet[0]==1) 
        xdot  = psr[p].param[param_a1dot].val[0];
    else xdot  = 0.0;

    if (psr[p].param[param_pbdot].paramSet[0] == 1) 
        pbdot = psr[p].param[param_pbdot].val[0];
    else pbdot = 0.0;

    if (psr[p].param[param_edot].paramSet[0] == 1) 
        edot = psr[p].param[param_edot].val[0];
    else edot = 0.0;

    if (psr[p].param[param_xpbdot].paramSet[0] == 1) 
        xpbdot = psr[p].param[param_xpbdot].val[0];
    else xpbdot = 0.0;


    x = psr[p].param[param_a1].val[0]+xdot*tt0;
    ecc = psr[p].param[param_ecc].val[0]+edot*tt0;
    er = ecc*(1.0+dr);
    eth = ecc*(1.0+dth);

    if (ecc < 0.0 || ecc > 1.0){
        ld_printf("DDHmodel: problem with eccentricity = %Lg [%s]\n",
                psr[p].param[param_ecc].val[0],psr[p].name);
        exit(1);
    }

    orbits = tt0/pb - longdouble(0.5)*(pbdot+xpbdot)*(tt0/pb)*(tt0/pb);
    norbits = (int)orbits;
    if (orbits<0.0) norbits--;
    phase=2.0*M_PI*(orbits-norbits);

    //  Compute eccentric anomaly u by iterating Kepler's equation.
    u=phase+ecc*sin(phase)*(1.0+ecc*cos(phase));
    do {
        du=(phase-(u-ecc*sin(u)))/(1.0-ecc*cos(u));
        u=u+du;
    } while (fabs(du)>1.0e-12);

    /*  DD equations 17b, 17c, 29, and 46 through 52 */
    su=sin(u);
    cu=cos(u);
    onemecu=1.0-ecc*cu;
    cae=(cu-ecc)/onemecu;
    sae=sqrt(1.0-pow(ecc,2))*su/onemecu;
    ae=atan2(sae,cae);
    if(ae<0.0) ae=ae+2.0*M_PI;
    ae=2.0*M_PI*orbits + ae - phase;
    omega=omz/rad2deg + k*ae;
    sw=sin(omega);
    cw=cos(omega);
    alpha=x*sw;
    beta=x*sqrt(1-pow(eth,2))*cw;
    bg=beta+gamma;
    dre=alpha*(cu-er) + bg*su;
    drep=-alpha*su + bg*cu;
    drepp=-alpha*cu - bg*su;
    anhat=an/onemecu;

    // DD equations 26, 27, 57:
    sqr1me2=sqrt(1-pow(ecc,2));
    cume=cu-ecc;
    brace=onemecu-si*(sw*cume+sqr1me2*cw*su);
    dlogbr=log(brace);

    // Shapiro delay, ehm06, Eq. 79, identical to DD86, Eq. 26.
    ds=-2*m2*dlogbr;

    // Aberration delay, ehm06, Eq. 76, identical to DD86, Eq. 27.
    da=a0*(sin(omega+ae) + ecc*sw) + b0*(cos(omega+ae) + ecc*cw); // Zero by design

    // Now compute d2bar, the orbital time correction in DD equation 42.
    d2bar=dre*(1-anhat*drep+(pow(anhat,2))*(pow(drep,2) + 0.5*dre*drepp -
                0.5*ecc*su*dre*drep/onemecu)) + ds + da;
    torb=-d2bar;

    if (param==-1) return torb;

    // Now we need the partial derivatives. Use DD equations 62a - 62k.
    csigma=x*(-sw*su+sqr1me2*cw*cu)/onemecu;
    ce=su*csigma-x*sw-ecc*x*cw*su/sqr1me2;
    cx=sw*cume+sqr1me2*cw*su;
    comega=x*(cw*cume-sqr1me2*sw*su);
    cgamma=su;
    //cdth=-ecc*ecc*x*cw*su/sqr1me2;
    cm2=-2*dlogbr;
    csi=2*m2*(sw*cume+sqr1me2*cw*su)/brace; 

    longdouble lgf = log( ( 1.0 + ecc * cos( ae ) ) / 
            (1.0 + pow( stig, 2.0 ) - 2.0 * stig * sin( ae + omega ) ) );

    if( param == param_pb )
        return -csigma * an * SECDAY * tt0 / ( pb * SECDAY ); 

    else if( param == param_a1 )
        return cx;

    else if( param == param_ecc )
        return ce;

    else if( param == param_om )
        return comega;

    else if( param == param_omdot )
        return ae*comega/(an*360.0/(2.0*M_PI)*365.25*SECDAY);

    else if( param == param_t0 )
        return -csigma*an*SECDAY;

    else if( param == param_pbdot )
        return 0.5*tt0*(-csigma*an*SECDAY*tt0/(pb*SECDAY));

    else if( param == param_sini )
        return csi;

    else if( param == param_gamma )
        return cgamma;

    else if( param == param_m2 )
        return cm2*SUNMASS;

    else if( param == param_a1dot ) // Also known as xdot
        return cx*tt0;

    else if( param == param_h3 ) 
        return( 2.0 / pow( stig, 3.0 ) * lgf );

    else if( param == param_stig )
        return( -2.0 * m2 / stig * 
                ( 1.0 + 3.0 * lgf - ( 1.0 - stig * stig ) / 
                  ( 1.0 + stig * stig - 2.0 * stig * sin( ae + omega ) ) ) );

    return 0.0;
}
Beispiel #21
0
/* Function to make a clock correction sequence using Dijkstra's
   shortest path algorithm , see 
http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm */
DynamicArray *makeClockCorrectionSequence(const char *clockFrom, const char *clockTo,
        double mjd,int warnings)
{
    size_t slen = 16;
    DynamicArray names; /* Array of clock names. Other values index this arr */
    int *S; /* Clocks for which shortest path are known */
    int n_known;
    int *Q; /* Remaining clocks */
    float *d; /* Best distance to a clock */
    int *edge_to_previous; /* edge to use to link to previous node */ 
    int s, t; /* indices of clockFrom, clockTo */
    size_t ifunc;
    int iclock;
    ClockCorrectionFunction *func;
    char *clock;
    int to_present, from_present;
    int ibest;
    float best;
    /* make a list of edges */
    typedef struct
    {
        int from;
        int to;
        ClockCorrectionFunction *func;
    } Edge;
    Edge *edges;
    int iedge, v, nedges;
    int istep, nsteps;
    DynamicArray seq;

    //  printf("HERE %s %s %lf %d\n",clockFrom,clockTo,mjd,warnings);

    DynamicArray_init(&names, slen);

    /* initialize list of all known clocks, and list of edges
       for functions that cover the requested mjd */
    edges = (Edge *)malloc(sizeof(Edge)*clockCorrectionFunctions.nelem);
    iedge = 0;

    for (ifunc=0; ifunc < clockCorrectionFunctions.nelem; ifunc++)
    {
        func = ((ClockCorrectionFunction *)clockCorrectionFunctions.data)+ifunc;
        if (ClockCorrectionFunction_getStartMJD(func) <= mjd &&
                ClockCorrectionFunction_getEndMJD(func) >= mjd)
        {
            /* see if to and from clocks there already */
            to_present = from_present = 0;
            for (iclock=0;  
                    iclock < (int)names.nelem && !(to_present && from_present); iclock++)
            {
                clock = ((char *)names.data)+iclock*slen;
                if (!strcasecmp(clock, func->clockTo))
                {
                    to_present = 1;
                    edges[iedge].to = iclock;
                }
                if (!strcasecmp(clock, func->clockFrom))
                {
                    from_present = 1;
                    edges[iedge].from = iclock;
                    // 	  printf("%s present already\n", func->clockFrom); 
                }
                /* 	else */
                /* 	  printf("%s != %s!\n", clock, func->clockFrom); */
            }
            /* add to list if not already present */
            if (!to_present)
            {
                DynamicArray_push_back(&names, func->clockTo);
                edges[iedge].to = names.nelem-1;
            }
            if (!from_present)
            {
                DynamicArray_push_back(&names, func->clockFrom);
                edges[iedge].from = names.nelem-1;
            }
            //        printf("Add edge %d <%s> <%s> %d %d\n", iedge, func->clockTo, func->clockFrom,  
            //  	     edges[iedge].to, edges[iedge].from);  
            edges[iedge].func = func;
            iedge++;
        }
    }
    nedges = iedge;

    /* find requested start (s) and end (t) clock in array of names */
    s = t = -1;
    for (iclock=0; iclock < (int)names.nelem && (t < 0 || s < 0); iclock++)
    {
        clock = ((char *)names.data)+iclock*slen;
        if (!strcasecmp(clock, clockFrom))
            s = iclock;
        if (!strcasecmp(clock, clockTo))
            t = iclock;
    }
    if (s < 0)
    {
        char msg[1000],msg2[1000];
        sprintf(msg,"no clock corrections available for clock %s for MJD",
                clockFrom);
        sprintf(msg2,"%.1f",mjd);
        displayMsg(1,"CLK3",msg,msg2,warnings);
        //logerr("no clock corrections available for clock %s -> %s for MJD %.1f",clockFrom,clockTo,mjd);
        //    printf("EXITING 1\n");
        free(edges); edges = NULL;
        DynamicArray_free(&names);
        return NULL;
    }
    if (t < 0)
    {
        char msg[1000],msg2[1000];
        sprintf(msg,"no clock corrections available for clock %s for MJD",
                clockTo);
        sprintf(msg2,"%.1f",mjd);
        displayMsg(1,"CLK3",msg,msg2,warnings);
        //logerr("no clock corrections available for clock %s -> %s for MJD %.1f",clockFrom,clockTo,mjd);

        //    printf("EXITING 2\n");
        free(edges); edges = NULL;
        DynamicArray_free(&names);
        return NULL;
    }

    /* initialize S, Q, d, p */
    n_known = 0;
    S = (int *)malloc(sizeof(int)*names.nelem);
    Q = (int *)malloc(sizeof(int)*names.nelem);
    d = (float *)malloc(sizeof(float)*names.nelem);
    edge_to_previous = (int *)malloc(sizeof(int)*names.nelem);
    for (iclock=0; iclock < (int)names.nelem; iclock++)
    {
        S[iclock] = 0;
        Q[iclock] = 1;
        d[iclock] = FLT_MAX;
        edge_to_previous[iclock] = -1;
    }
    d[s] = 0.0;
    /* main algorithm */
    while (1)
    {
        /* find the member of Q with the lowest d */
        best = FLT_MAX;
        ibest = -1;
        for (iclock=0; iclock < (int)names.nelem; iclock++)
            if (Q[iclock] && d[iclock] < best)
            {
                best = d[iclock];
                ibest = iclock;
            }
        if (ibest == -1)
            break;
        Q[ibest] = 0; /* remove it from Q */
        S[ibest] = 1; /* add it to S */
        if (ibest == t)
            break; /* shortest path found */
        /* for every edge connected to ibest */
        /*     printf("Looking for edges connected to %s d[%d] = %f\n",   */
        /*  	   ((char *)names.data)+ibest*slen, ibest, best);  */
        for (iedge=0; iedge < nedges; iedge++)
            if (edges[iedge].from==ibest || edges[iedge].to==ibest)
            {
                /* set v to where the edge connects to */
                if (edges[iedge].from==ibest)
                    v = edges[iedge].to;
                else
                    v = edges[iedge].from;
                /* use this edge  if it is better */
                // 	printf("Try %s %s badness %f\n", 
                // 	       edges[iedge].func->clockFrom, edges[iedge].func->clockTo,  
                // 	       edges[iedge].func->badness); 
                if (d[v] > d[ibest] + edges[iedge].func->badness)
                {
                    d[v] = d[ibest] + edges[iedge].func->badness;
                    edge_to_previous[v] = iedge;
                    /*  	  printf("  edge %d --> %d %f\n", iedge, v, d[v]); */
                }
                /*	else */
                /*  printf("Reject %s %s\n", edges[iedge].func->clockFrom, edges[iedge].func->clockTo); */
            }
    }

    //    printf("Badness total = %f\n", best);
    if (ibest == -1)
    {
        char msg[1000],msg2[1000];
        sprintf(msg,"no clock corrections available from %s to %s for MJD",
                clockFrom,clockTo);
        sprintf(msg2,"%.1f",mjd);
        //logerr("no clock corrections available for clock %s -> %s for MJD %.1f",clockFrom,clockTo,mjd);
        displayMsg(1,"CLK7",msg,msg2,warnings);
        //    printf("EXITING 3\n");
        free(edges); edges = NULL;
        DynamicArray_free(&names);
        return NULL;
    }
    else
    {

        /* Write out the best path in reverse order, as an edge list to
           "S" */
        nsteps = 0;
        v = t;
        while (v != s)
        {
            S[nsteps] = edge_to_previous[v];
            v = (edges[edge_to_previous[v]].to==v ? 
                    edges[edge_to_previous[v]].from : edges[edge_to_previous[v]].to);
            nsteps++;
        }

        /* set up the actual sequence now in the correct order */
        DynamicArray_init(&seq, sizeof(ClockCorrectionFunction *));
        if (warnings==0)
            printf("Using the following chain of clock corrections for %s -> %s\n",
                    clockFrom, clockTo);
        for (istep=nsteps-1; istep >=0; istep--)
        {
            /* not any more since some functions are excluded (wrong mjd range) */
            /*     func = ((ClockCorrectionFunction *)clockCorrectionFunctions.data)  */
            /*       + S[istep]; */
            func = edges[S[istep]].func;
            DynamicArray_push_back(&seq, &func);
            if (warnings==0) printf("%s : %s <-> %s\n", func->table.fileName, func->clockFrom, func->clockTo);
        }
    }
    /* free memory */
    free(edges); edges = NULL;
    free(edge_to_previous); edge_to_previous = NULL;
    free(d); d = NULL;
    free(Q); Q = NULL;
    free(S); S = NULL;
    DynamicArray_free(&names);
    //  printf("END HERE\n");
    return (DynamicArray *)DynamicArray_push_back(&clockCorrectionSequences, &seq);
}
Beispiel #22
0
void
get_EOP(double mjd, double *xp, double *yp, double *dut1, 
	      double *dut1dot,
	int dispWarnings,char *eopcFile)
{
  static int first = 1;
  static DynamicArray EOPsamples;
  EOPSample *samp;
  int proxy = -1, isamp;
  double f;
  double leap=0.0;
  // load EOP series first
  if (first)
  {
    load_EOP(&EOPsamples,eopcFile);
    first = 0;
  }
  samp =  (EOPSample *)EOPsamples.data;

  // check for out of bounds
  if (samp[0].mjd > mjd)
    proxy = 0;
  else if (samp[EOPsamples.nelem-1].mjd <= mjd)
    proxy = EOPsamples.nelem-1;
  if (proxy >=0)
  {
    *xp = samp[proxy].xp;
    *yp = samp[proxy].yp;
    *dut1 = samp[proxy].dut1;
    {
      char msg2[1000];
      sprintf(msg2,"%.2f. Using %.1lf instead",mjd,samp[proxy].mjd);
      if( dispWarnings != 2 )
        displayMsg(1,"EPH1","No Earth orientation parameters for MJD ",msg2,dispWarnings);      
    }
    // GHOBBS: Added next line (and removed the 'return' after) otherwise dut1dot never gets set!
    mjd = samp[proxy].mjd;
    //    return;
  }

    /* find first sample to fall after requested time */
  for (isamp = 0; 
       isamp < (int)EOPsamples.nelem  && samp[isamp].mjd <= mjd; 
       isamp++)
    ;

  // cope with leap second ... take it off second point as jump happens
  // right AT second point
  if (samp[isamp].dut1 - samp[isamp-1].dut1 > 0.5)
    leap = 1.0;
  else if (samp[isamp].dut1 - samp[isamp-1].dut1 < -0.5)
    leap = -1.0;
  else
    leap = 0.0;

  *dut1dot = (samp[isamp].dut1 - leap - samp[isamp-1].dut1) / 86400.0;

  /* interpolate */
  f = (mjd - samp[isamp-1].mjd) / (samp[isamp].mjd - samp[isamp-1].mjd);
  *xp = samp[isamp-1].xp + f*(samp[isamp].xp - samp[isamp-1].xp);
  *yp = samp[isamp-1].yp + f*(samp[isamp].yp - samp[isamp-1].yp);
  *dut1 = samp[isamp-1].dut1 + f*(samp[isamp].dut1 - leap - samp[isamp-1].dut1);
 
 
  return;
}
Beispiel #23
0
    void 
getClockCorrections(observation *obs, const char *clockFrom_const, 
        const char *clockTo,int warnings)
{
    DynamicArray *sequence;
    size_t ifunc;
    char *currClock;
    ClockCorrectionFunction *func;
    double correction = 0.0;
    obs->nclock_correction = 0;
    char clockFrom[128];
    strcpy(clockFrom,clockFrom_const);

    char clockFromOrig[128]; 
    //  logdbg("In getClockCorrections");

    //logdbg("Getting clockFrom >%s<",obs->telID);
    if (clockFrom[0]=='\0') // get from observatory instead
        strcpy(clockFrom,getObservatory(obs->telID)->clock_name);
    //  logdbg("Got clockFrom");
    strcpy(clockFromOrig,clockFrom);

    if (!strcasecmp(clockTo, clockFrom))
    {
        obs->nclock_correction = 0;
        return;
    }
    //  logdbg("In getClockCorrections calling sequence 1");
    // Memory leak here
    sequence = getClockCorrectionSequence(clockFrom, clockTo, obs->sat,warnings);

    if (sequence == NULL)
    {
        char msg[1000],msg2[1000];
        sprintf(msg,"Trying assuming UTC =");
        sprintf(msg2,"%s",clockFrom);
        displayMsg(1,"CLK4",msg,msg2,warnings);
        strcpy(clockFrom,"UTC");
        if (!strcasecmp(clockTo, clockFrom))
        {
            obs->nclock_correction = 0;
            return;
        }
        logdbg("In getClockCorrections calling sequence 2");
        sequence = getClockCorrectionSequence(clockFrom, clockTo, obs->sat,
                warnings); 
        if (sequence == NULL)
        {
            char msg[1000],msg2[1000];
            sprintf(msg,"Trying TT(TAI) instead of ");
            sprintf(msg2,"%s",clockTo);
            displayMsg(1,"CLK5",msg,msg2,warnings);
            strcpy(clockFrom,clockFromOrig);
            clockTo="TT(TAI)";
            if (!strcasecmp(clockTo, clockFrom))
            {
                obs->nclock_correction = 0;
                return;
            }
            logdbg("In getClockCorrections calling sequence 3");
            sequence = getClockCorrectionSequence(clockFrom, clockTo, obs->sat,
                    warnings); 
            if (sequence == NULL)
            {
                displayMsg(1,"CLK8","Trying both","",warnings);       
                strcpy(clockFrom,"UTC");
                if (!strcasecmp(clockTo, clockFrom))
                {
                    obs->nclock_correction = 0;
                    return;
                }
                logdbg("In getClockCorrections calling sequence 4");
                sequence = getClockCorrectionSequence(clockFrom, clockTo, obs->sat,
                        warnings); 

                if (sequence==NULL)
                {
                    obs->nclock_correction = 0;
                    if (warnings==0)
                        printf( "Warning [CLK:7], no clock correction available for TOA @ MJD %.4lf!\n",
                                (double)obs->sat);
                    return;
                }
            }
        }
        displayMsg(1,"CLK9","... ok, using stated approximation","",warnings);       
    }
    currClock = clockFrom;
    // Already bad
    for (ifunc=0; ifunc < sequence->nelem 
            && strcasecmp(currClock, clockTo); ifunc++)
    {
        func = ((ClockCorrectionFunction **)sequence->data)[ifunc];
        bool backwards = strcasecmp(currClock, func->clockFrom);
        if (backwards && strcasecmp(currClock, func->clockTo))
        {
            printf("Programming error! Broken clock correction chain!!\n");
            exit(1);
        }
        /* add correction using sign based on direction of correction */
        obs->correctionsTT[obs->nclock_correction].correction = 
            ClockCorrectionFunction_getCorrection(func, obs->sat+correction/SECDAY)
            * (backwards ? -1.0 : 1.0);
        correction += obs->correctionsTT[obs->nclock_correction].correction;
        strcpy(obs->correctionsTT[obs->nclock_correction].corrects_to, 
                (backwards ? func->clockFrom : func->clockTo)); 
        obs->nclock_correction++;
        currClock = (backwards ? func->clockFrom : func->clockTo);
    }
    //  logdbg("leaving getClockCorrections");
    /*   printf("Correction: %lg\n", correction); */
}
Beispiel #24
0
    double
getCorrection(observation *obs, const char *clockFrom_c, const char *clockTo, int warnings)
{
    observatory *site;
    DynamicArray *sequence;
    size_t ifunc;
    ClockCorrectionFunction *func;
    double correction = 0.0;
    const char *CVS_verNum = "$Id: 2ecd61c300367fd1dc527ff60a21468091473d85 $";
    char clockFrom[128];
    char currClock[128];
    strcpy(clockFrom,clockFrom_c);

    if (clockFrom[0]=='\0')
        site = getObservatory(obs->telID);

    if (displayCVSversion == 1) CVSdisplayVersion("clkcorr.C","getCorrection()",CVS_verNum);

    if (clockFrom[0]=='\0')
        strcpy(clockFrom,site->clock_name);
    strcpy(currClock,clockFrom);

    if (!strcasecmp(clockTo, clockFrom))
        return 0.0;

    /*   printf("Getting %s<->%s\n", site->clock_name, clockTo); */
    sequence = getClockCorrectionSequence(clockFrom, clockTo, obs->sat,
            warnings);

    if (sequence == NULL)
    {
        char msg[1000],msg2[1000];
        sprintf(msg,"Proceeding assuming UTC = ");
        sprintf(msg2,"%s",currClock);
        displayMsg(1,"CLK6",msg,msg2,warnings);

        if (!strcasecmp(clockTo, "UTC"))
            return 0.0;
        sequence = getClockCorrectionSequence("UTC", clockTo, obs->sat,
                warnings); 
        strcpy(currClock,"UTC");
        if (sequence == NULL)
        {
            if (warnings==0) 
                printf( "!Warning [CLK:9], no clock correction available for TOA @ MJD %.4lf!\n",
                        (double)obs->sat);
            return 0.0;
        }
    }

    for (ifunc=0; ifunc < sequence->nelem
            && strcasecmp(currClock, clockTo); ifunc++)
    {
        func = ((ClockCorrectionFunction **)sequence->data)[ifunc];
        bool backwards = strcasecmp(currClock, func->clockFrom);
        /* add correction using sign based on direction of correction */
        correction += 
            ClockCorrectionFunction_getCorrection(func, obs->sat+correction/SECDAY)
            * (backwards ? -1.0 : 1.0);
        strcpy(currClock,(backwards ? func->clockFrom : func->clockTo));
        /*     printf("--> %s\n", currClock); */
    }


    return correction;
}
Beispiel #25
0
int main(int argc, char **argv)
{
    LONG               rc            =       RETURN_FAIL;
    STRPTR             filename,
                       commandLine   =       NULL,
                       ixWindow      =       DEFWINDOW;
    LONG               ixWait        =       0,
                       ixStack       =       DEFSTACK;
    BOOL               ixUShell      =       DEFUSHELL;
    BPTR               oldlock       = (BPTR)-1,
                       dirlock       = (BPTR)-1,
                       window        =       NULL;
    struct DiskObject *dobj          =       NULL;

    D(bug("IconX argc %d\n", argc));

    if (argc != 0)
    {
	displayMsg(ERROR_REQUIRED_ARG_MISSING);
	goto exit;
    }

    struct WBStartup *startup = (struct WBStartup *) argv;
    if (startup->sm_NumArgs < 2)
    {
	displayMsg(ERROR_REQUIRED_ARG_MISSING);
	goto exit;
    }
    
    D(bug("[IconX] startup->sm_NumArgs: %d\n", startup->sm_NumArgs));

    dirlock  = startup->sm_ArgList[1].wa_Lock;
    filename = startup->sm_ArgList[1].wa_Name;

    oldlock = CurrentDir(dirlock);

    /* query diskobject for tooltypes */
    dobj = GetDiskObject(filename);
    if (dobj == NULL)
    {
	struct EasyStruct es = {sizeof(struct EasyStruct), 0,
	    "Error", "IconX\nGetDiskObject failed for:\n%s", "OK"};
	EasyRequest(0, &es, 0, filename);
	goto exit;
    }

    if (dobj->do_Type == WBPROJECT)
    {
	const STRPTR *toolarray = (const STRPTR *)dobj->do_ToolTypes;
	STRPTR s;
	if ((s = FindToolType(toolarray, "WINDOW")))
	{
	    ixWindow = s;
	}
	if ((s = FindToolType(toolarray, "STACK")))
	{
	    ixStack = atol(s);
	}
	if ((s = FindToolType(toolarray, "USERSHELL")))
	{
	    if (MatchToolValue(s, "NO"))
	    {
		ixUShell = FALSE;
	    }
	}
	if ((s = FindToolType(toolarray, "WAIT")))
	{
	    ixWait += atol(s) * 50;
	}
	if ((s = FindToolType(toolarray, "DELAY")))
	{
	    ixWait += atol(s);
	}
    }
    else
    {
	displayMsg(ERROR_OBJECT_WRONG_TYPE);
	goto exit;
    }
    
    if (ixWait <= 0)
	ixWait = DEFWAIT;

    if (ixStack <= 4096)
	ixStack = DEFSTACK;
    
    D(bug("wait %d stack %d usershell %d window %s\n", ixWait, ixStack, ixUShell, ixWindow));

    D(bug("Building command line\n"));
    commandLine = BuildCommandLine(startup);
    if (commandLine == NULL)
    {
	displayMsg(IoErr());
	goto exit;
    }
    D(bug("[IconX] commandLine: '%s'\n", commandLine));

    window  = Open(ixWindow, MODE_OLDFILE);
    if (window == NULL)
    {
	/* try to open default window */
	window = Open(DEFWINDOW, MODE_OLDFILE);
    }

    if (window)
    {
	D(bug("[IconX] window ok\n"));
	struct TagItem tags[] =
	{
	    { SYS_Asynch,      FALSE        },
	    { SYS_Background,  TRUE         },
	    { SYS_Input,       (IPTR)window },
	    { SYS_Output,      (IPTR)NULL   },
	    { SYS_Error,       (IPTR)NULL   },
	    { SYS_UserShell,   ixUShell     },
	    { NP_StackSize,    ixStack      },
	    { TAG_DONE,        0            }
	};

	rc = SystemTagList(commandLine, tags);
	if (rc == -1)
	{
	    displayMsg(IoErr());
	    rc = RETURN_FAIL;
	}
    }
    else
    {
	displayMsg(IoErr());
	goto exit;
    }

    Delay(ixWait);
    rc = RETURN_OK;

exit:
    Close(window);
    FreeDiskObject(dobj);

    if (oldlock != (BPTR)-1)
	CurrentDir(oldlock);

    return rc;
}
Beispiel #26
0
int main (void)
{
	// Initialize
	//---------------------------------------
	// 1) set band data inputs
	initPORTS();
	// 2) confgure ADC for ICOM band data
	initADC(); 
	// 3) Read EEPROM data
	readEEConfig();
	// 4) set output
	applyOutPins();
	// 5) Enable 10ms timer
	initTIMER();
	// 6) Enable serial port communication
	initSERIAL();
   	// 7) Initialize LCD module
   	LCDInit(LS_NONE);
	// 8) display welcome message
	showSplashScreen();
	// 9) show status on screen
	displayStatus();
	// 10) set LEDs
	if (BandDecode_Mode == BAND_MODE_AUTO)
	{
		enableAutoLED();
		disableManLED();
	}
	else
	{
		enableManLED();
		disableAutoLED();
	}
	disableLinkLED();


	// Main loop
	//---------------------------------------
	while(1)
	{
		// Get auto band
		//---------------------------------------
		if (BandDecode_Mode == BAND_MODE_AUTO)
		{
			checkAutoBand();
			// check if changed and refresh screen...
			if (current_auto_band != BAND_INVALID)
			{			
				if (BandSelected != current_auto_band)
				{
					if (IS_TX)
					{
						displayMsg(m1_band_change_when_tx_warn, m2_when_tx, 2);
					}
					BandSelected = current_auto_band;

					changeBand();
				}
				disableManLEDBlink();
			}
			else
			{
				enableManLEDBlink();
			}
		}
	
		// Selecting antennas
		//---------------------------------------
		int8_t ant_chng = -1;
		if (sw_state[ANT1_SW_ID] == SW_PRESS)
		{
			sw_state[ANT1_SW_ID] = SW_OPEN;
			ant_chng = 0;
		}
		else if (sw_state[ANT2_SW_ID] == SW_PRESS)
		{
			sw_state[ANT2_SW_ID] = SW_OPEN;
			ant_chng = 1;
		}
		else if (sw_state[ANT3_SW_ID] == SW_PRESS)
		{
			sw_state[ANT3_SW_ID] = SW_OPEN;
			ant_chng = 2;
		}
		if (ant_chng != -1)
		{
			uint8_t new_ant_id = bm_cfg.AntAvailBandCfg[BandSelected][ant_chng];
			if (new_ant_id != NO_ANTENNA && bm_cfg.AntSelBandCfg[BandSelected] != new_ant_id)
			{
				if (IS_TX)
				{
					displayMsg(m1_ant_change_press_when_tx, m2_when_tx, 2);
				}
				else
				{
					bm_cfg.AntSelBandCfg[BandSelected] = new_ant_id;
					applyOutPins();
					updateCurrentEEConfig();
					displayStatus();
				}
			}
		}	
		
		// Selecting band change mode
		//---------------------------------------
		if (sw_state[MODE_SW_ID] == SW_PRESS)
		{
			sw_state[MODE_SW_ID] = SW_OPEN;
			if (BandDecode_Mode == BAND_MODE_AUTO)
			{
				BandDecode_Mode = BAND_MODE_MAN;
				disableManLEDBlink();
				enableManLED();
				disableAutoLED();
				displayMsg(m1_man_mode, m_empty, 2);
			}
			else
			{
				BandDecode_Mode = BAND_MODE_AUTO;
				enableAutoLED();
				disableManLED();
				displayMsg(m1_auto_mode, m_empty, 2);
			}
			updateCurrentEEConfig();
		}

		// Selecting band manual
		//---------------------------------------
		else if (sw_state[UP_SW_ID] == SW_PRESS)
		{
			sw_state[UP_SW_ID] = SW_OPEN;
			if (BandDecode_Mode == BAND_MODE_MAN)
			{
				if (IS_TX)
				{
					displayMsg(m1_band_change_press_when_tx, m2_when_tx, 2);
				}
				else
				{
					if (BandSelected < BAND_MAX)
					{
						BandSelected++;
					}
					else
					{
						BandSelected = 0;
					}
					
					changeBand();
				}
			}
			else
			{
				displayMsg(m1_band_change_press_when_auto, m2_band_change_press_when_auto, 3);
			}
		}

		else if (sw_state[DWN_SW_ID] == SW_PRESS)
		{
			sw_state[DWN_SW_ID] = SW_OPEN;

			if (BandDecode_Mode == BAND_MODE_MAN)
			{
				if (IS_TX)
				{
					displayMsg(m1_band_change_press_when_tx, m2_when_tx, 2);
				}
				else
				{
					if (BandSelected > 0)
					{
						BandSelected--;
					}
					else
					{
						BandSelected = BAND_MAX;
					}
					
					changeBand();
				}
			}
			else
			{
				displayMsg(m1_band_change_press_when_auto, m2_band_change_press_when_auto, 2);
			}
		}

		// Change profile
		//---------------------------------------
		/*
		else if (sw_state[MODE_SW_ID] == SW_HOLD)
		{
			sw_state[MODE_SW_ID] = SW_OPEN;
		
			if (IS_TX)
			{
				displayMsg(m1_profile_change_press_when_tx, m2_when_tx, 2);
			}
			else
			{
				if (profile_Id >= MAX_PROFILES - 1)
				{
					profile_Id = 0;
				}
				else
				{
					profile_Id++;
				}
				char msg[24];
				snprintf(msg, 24, m1_profile, bm_cfg.ProfileName);
				displayMsg(msg, m2_activated, 2);
				readEEConfigProfile(profile_Id);
				//blockPTTTimed();
				applyOutPins();
				updateCurrentEEConfig();
				//displayStatus();
			}
		}
		*/

		// Refresh display if needed after displaying error message
		//---------------------------------------
		if (refresh_disp_needed == 1)
		{
			refresh_disp_needed = 0;
			displayStatus();
		}

		// Refresh output/display if needed after loosing peer link
		//---------------------------------------
		if (refresh_ptt_needed == 1)
		{
			refresh_ptt_needed = 0;
			applyPttStatus();
			displayStatus();
		}

		if (refresh_bandout_needed == 1)
		{
			refresh_bandout_needed = 0;
			applyOutPins();
		}

		// Check and process serial port messages
		//---------------------------------------
		processSerialMsg();

	}
	// Main loop end


}
Beispiel #27
0
int
startClient( volatile int *pid )
{
	const char *home, *sessargs, *desksess;
	char **env, *xma;
	char **argv, *fname, *str;
#ifdef USE_PAM
	char ** volatile pam_env;
# ifndef HAVE_PAM_GETENVLIST
	char **saved_env;
# endif
	int pretc;
#else
# ifdef _AIX
	char *msg;
	char **theenv;
	extern char **newenv; /* from libs.a, this is set up by setpenv */
# endif
#endif
#ifdef HAVE_SETUSERCONTEXT
	extern char **environ;
#endif
	char *failsafeArgv[2];
	char *buf, *buf2;
	int i;

	if (strCmp( dmrcuser, curuser )) {
		if (curdmrc) { free( curdmrc ); curdmrc = 0; }
		if (dmrcuser) { free( dmrcuser ); dmrcuser = 0; }
	}

#if defined(USE_PAM) || defined(_AIX)
	if (!(p = getpwnam( curuser ))) {
		logError( "getpwnam(%s) failed.\n", curuser );
	  pError:
		displayStr( V_MSG_ERR, 0 );
		return 0;
	}
#endif

#ifndef USE_PAM
# ifdef _AIX
	msg = NULL;
	loginsuccess( curuser, hostname, tty, &msg );
	if (msg) {
		debug( "loginsuccess() - %s\n", msg );
		free( (void *)msg );
	}
# else /* _AIX */
#  if defined(KERBEROS) && defined(AFS)
	if (krbtkfile[0] != '\0') {
		if (k_hasafs()) {
			int fail = 0;
			if (k_setpag() == -1) {
				logError( "setpag() for %s failed\n", curuser );
				fail = 1;
			}
			if ((ret = k_afsklog( NULL, NULL )) != KSUCCESS) {
				logError( "AFS Warning: %s\n", krb_get_err_text( ret ) );
				fail = 1;
			}
			if (fail)
				displayMsg( V_MSG_ERR,
				            "Warning: Problems during Kerberos4/AFS setup." );
		}
	}
#  endif /* KERBEROS && AFS */
# endif /* _AIX */
#endif	/* !PAM */

	curuid = p->pw_uid;
	curgid = p->pw_gid;

	env = baseEnv( curuser );
	xma = 0;
	strApp( &xma, "method=", curtype, (char *)0 );
	if (td_setup)
		strApp( &xma, ",auto", (char *)0 );
	if (xma) {
		env = setEnv( env, "XDM_MANAGED", xma );
		free( xma );
	}
	if (td->autoLock && cursource == PWSRC_AUTOLOGIN)
		env = setEnv( env, "DESKTOP_LOCKED", "true" );
	env = setEnv( env, "PATH", curuid ? td->userPath : td->systemPath );
	env = setEnv( env, "SHELL", p->pw_shell );
	env = setEnv( env, "HOME", p->pw_dir );
#if !defined(USE_PAM) && !defined(_AIX) && defined(KERBEROS)
	if (krbtkfile[0] != '\0')
		env = setEnv( env, "KRBTKFILE", krbtkfile );
#endif
	userEnviron = inheritEnv( env, envvars );
	env = systemEnv( curuser );
	systemEnviron = setEnv( env, "HOME", p->pw_dir );
	debug( "user environment:\n%[|''>'\n's"
	       "system environment:\n%[|''>'\n's"
	       "end of environments\n",
	       userEnviron,
	       systemEnviron );

	/*
	 * for user-based authorization schemes,
	 * add the user to the server's allowed "hosts" list.
	 */
	for (i = 0; i < td->authNum; i++) {
#ifdef SECURE_RPC
		if (td->authorizations[i]->name_length == 9 &&
		    !memcmp( td->authorizations[i]->name, "SUN-DES-1", 9 ))
		{
			XHostAddress addr;
			char netname[MAXNETNAMELEN+1];
			char domainname[MAXNETNAMELEN+1];

			getdomainname( domainname, sizeof(domainname) );
			user2netname( netname, curuid, domainname );
			addr.family = FamilyNetname;
			addr.length = strlen( netname );
			addr.address = netname;
			XAddHost( dpy, &addr );
		}
#endif
#ifdef K5AUTH
		if (td->authorizations[i]->name_length == 14 &&
		    !memcmp( td->authorizations[i]->name, "MIT-KERBEROS-5", 14 ))
		{
			/* Update server's auth file with user-specific info.
			 * Don't need to AddHost because X server will do that
			 * automatically when it reads the cache we are about
			 * to point it at.
			 */
			XauDisposeAuth( td->authorizations[i] );
			td->authorizations[i] =
				krb5GetAuthFor( 14, "MIT-KERBEROS-5", td->name );
			saveServerAuthorizations( td, td->authorizations, td->authNum );
		}
#endif
	}

	if (*dmrcDir)
		mergeSessionArgs( TRUE );

	debug( "now starting the session\n" );

#ifdef USE_PAM

# ifdef HAVE_SETUSERCONTEXT
	if (setusercontext( lc, p, p->pw_uid, LOGIN_SETGROUP )) {
		logError( "setusercontext(groups) for %s failed: %m\n",
		          curuser );
		goto pError;
	}
# else
	if (!setGid( curuser, curgid ))
		goto pError;
# endif

# ifndef HAVE_PAM_GETENVLIST
	if (!(pam_env = initStrArr( 0 ))) {
		resetGids();
		goto pError;
	}
	saved_env = environ;
	environ = pam_env;
# endif
	removeCreds = 1; /* set it first - i don't trust PAM's rollback */
	pretc = pam_setcred( pamh, 0 );
	reInitErrorLog();
# ifndef HAVE_PAM_GETENVLIST
	pam_env = environ;
	environ = saved_env;
# endif
# ifdef HAVE_INITGROUPS
	/* This seems to be a strange place for it, but do it:
	   - after the initial groups are set
	   - after pam_setcred might have set something, even in the error case
	   - before pam_setcred(DELETE_CRED) might need it
	 */
	if (!saveGids())
		goto pError;
# endif
	if (pretc != PAM_SUCCESS) {
		logError( "pam_setcred() for %s failed: %s\n",
		          curuser, pam_strerror( pamh, pretc ) );
		resetGids();
		return 0;
	}

	removeSession = 1; /* set it first - same as above */
	pretc = pam_open_session( pamh, 0 );
	reInitErrorLog();
	if (pretc != PAM_SUCCESS) {
		logError( "pam_open_session() for %s failed: %s\n",
		          curuser, pam_strerror( pamh, pretc ) );
		resetGids();
		return 0;
	}

	/* we don't want sessreg and the startup/reset scripts run with user
	   credentials. unfortunately, we can reset only the gids. */
	resetGids();

# define D_LOGIN_SETGROUP LOGIN_SETGROUP
#else /* USE_PAM */
# define D_LOGIN_SETGROUP 0
#endif /* USE_PAM */

	removeAuth = 1;
	chownCtrl( &td->ctrl, curuid );
	endpwent();
#if !defined(USE_PAM) && defined(USESHADOW) && !defined(_AIX)
	endspent();
#endif
	ctltalk.pipe = &ctlpipe;
	ASPrintf( &buf, "sub-daemon for display %s", td->name );
	ASPrintf( &buf2, "client for display %s", td->name );
	switch (gFork( &ctlpipe, buf, buf2, 0, 0, mstrtalk.pipe, pid )) {
	case 0:

		gCloseOnExec( ctltalk.pipe );
		if (Setjmp( ctltalk.errjmp ))
			exit( 1 );

		gCloseOnExec( mstrtalk.pipe );
		if (Setjmp( mstrtalk.errjmp ))
			goto cError;

#ifndef NOXDMTITLE
		setproctitle( "%s'", td->name );
#endif
		strApp( &prog, " '", (char *)0 );
		reInitErrorLog();

		setsid();

		sessreg( td, getpid(), curuser, curuid );

		/* We do this here, as we want to have the session as parent. */
		switch (source( systemEnviron, td->startup, td_setup )) {
		case 0:
			break;
		case wcCompose( 0, 0, 127 ):
			goto cError;
		default: /* Explicit failure => message already displayed. */
			logError( "Startup script returned non-zero exit code\n" );
			exit( 1 );
		}

	/* Memory leaks are ok here as we exec() soon. */

#if defined(USE_PAM) || !defined(_AIX)

# ifdef USE_PAM
		/* pass in environment variables set by libpam and modules it called */
#  ifdef HAVE_PAM_GETENVLIST
		pam_env = pam_getenvlist( pamh );
		reInitErrorLog();
#  endif
		if (pam_env)
			for (; *pam_env; pam_env++)
				userEnviron = putEnv( *pam_env, userEnviron );
# endif

# ifdef HAVE_SETLOGIN
		if (setlogin( curuser ) < 0) {
			logError( "setlogin for %s failed: %m\n", curuser );
			goto cError;
		}
#  define D_LOGIN_SETLOGIN LOGIN_SETLOGIN
# else
#  define D_LOGIN_SETLOGIN 0
# endif

# if defined(USE_PAM) && defined(HAVE_INITGROUPS)
		if (!restoreGids())
			goto cError;
# endif

# ifndef HAVE_SETUSERCONTEXT

#  ifdef USE_PAM
		if (!setUid( curuser, curuid ))
			goto cError;
#  else
		if (!setUser( curuser, curuid, curgid ))
			goto cError;
#  endif

# else /* !HAVE_SETUSERCONTEXT */

		/*
		 * Destroy environment.
		 * We need to do this before setusercontext() because that may
		 * set or reset some environment variables.
		 */
		if (!(environ = initStrArr( 0 )))
			goto cError;

		/*
		 * Set the user's credentials: uid, gid, groups,
		 * environment variables, resource limits, and umask.
		 */
		if (setusercontext( lc, p, p->pw_uid,
		        LOGIN_SETALL & ~(D_LOGIN_SETGROUP|D_LOGIN_SETLOGIN) ) < 0)
		{
			logError( "setusercontext for %s failed: %m\n", curuser );
			goto cError;
		}

		for (i = 0; environ[i]; i++)
			userEnviron = putEnv( environ[i], userEnviron );

# endif /* !HAVE_SETUSERCONTEXT */

#else /* PAM || !_AIX */
		/*
		 * Set the user's credentials: uid, gid, groups,
		 * audit classes, user limits, and umask.
		 */
		if (setpcred( curuser, NULL ) == -1) {
			logError( "setpcred for %s failed: %m\n", curuser );
			goto cError;
		}

		/*
		 * Set the users process environment. Store protected variables and
		 * obtain updated user environment list. This call will initialize
		 * global 'newenv'.
		 */
		if (setpenv( curuser, PENV_INIT | PENV_ARGV | PENV_NOEXEC,
		             userEnviron, NULL ) != 0)
		{
			logError( "Cannot set %s's process environment\n", curuser );
			goto cError;
		}
		userEnviron = newenv;

#endif /* _AIX */

		/*
		 * for user-based authorization schemes,
		 * use the password to get the user's credentials.
		 */
#ifdef SECURE_RPC
		/* do like "keylogin" program */
		if (!curpass[0])
			logInfo( "No password for NIS provided.\n" );
		else {
			char netname[MAXNETNAMELEN+1], secretkey[HEXKEYBYTES+1];
			int nameret, keyret;
			int len;
			int key_set_ok = 0;
			struct key_netstarg netst;

			nameret = getnetname( netname );
			debug( "user netname: %s\n", netname );
			len = strlen( curpass );
			if (len > 8)
				bzero( curpass + 8, len - 8 );
			keyret = getsecretkey( netname, secretkey, curpass );
			debug( "getsecretkey returns %d, key length %d\n",
			       keyret, strlen( secretkey ) );
			netst.st_netname = netname;
			memcpy( netst.st_priv_key, secretkey, HEXKEYBYTES );
			memset( netst.st_pub_key, 0, HEXKEYBYTES );
			if (key_setnet( &netst ) < 0)
				debug( "Could not set secret key.\n" );
			/* is there a key, and do we have the right password? */
			if (keyret == 1) {
				if (*secretkey) {
					keyret = key_setsecret( secretkey );
					debug( "key_setsecret returns %d\n", keyret );
					if (keyret == -1)
						logError( "Failed to set NIS secret key\n" );
					else
						key_set_ok = 1;
				} else {
					/* found a key, but couldn't interpret it */
					logError( "Password incorrect for NIS principal %s\n",
					          nameret ? netname : curuser );
				}
			}
			if (!key_set_ok)
				nukeAuth( 9, "SUN-DES-1" );
			bzero( secretkey, strlen( secretkey ) );
		}
#endif
#ifdef K5AUTH
		/* do like "kinit" program */
		if (!curpass[0])
			logInfo( "No password for Kerberos5 provided.\n" );
		else
			if ((str = krb5Init( curuser, curpass, td->name )))
				userEnviron = setEnv( userEnviron, "KRB5CCNAME", str );
			else
				nukeAuth( 14, "MIT-KERBEROS-5" );
#endif /* K5AUTH */
		if (td->autoReLogin) {
			gSet( &mstrtalk );
			gSendInt( D_ReLogin );
			gSendStr( curuser );
			gSendStr( curpass );
			gSendStr( newdmrc );
		}
		if (curpass)
			bzero( curpass, strlen( curpass ) );
		setUserAuthorization( td );
		home = getEnv( userEnviron, "HOME" );
		if (home && chdir( home ) < 0) {
			logError( "Cannot chdir to %s's home %s: %m\n", curuser, home );
			sendStr( V_MSG_ERR, "Cannot enter home directory. Using /.\n" );
			chdir( "/" );
			userEnviron = setEnv( userEnviron, "HOME", "/" );
			home = 0;
		}
		if (home || td->clientLogFile[0] == '/') {
			if (!createClientLog( td->clientLogFile )) {
				logWarn( "Session log file according to %s cannot be created: %m\n",
				         td->clientLogFile );
				goto tmperr;
			}
		} else {
		  tmperr:
			if (!createClientLog( td->clientLogFallback ))
				logError( "Fallback session log file according to %s cannot be created: %m\n",
				          td->clientLogFallback );
			/* Could inform the user, but I guess this is only confusing. */
		}
		if (!*dmrcDir)
			mergeSessionArgs( home != 0 );
		if (!(desksess = iniEntry( curdmrc, "Desktop", "Session", 0 )))
			desksess = "failsafe"; /* only due to OOM */
		gSet( &mstrtalk );
		gSendInt( D_User );
		gSendInt( curuid );
		gSendStr( curuser );
		gSendStr( desksess );
		close( mstrtalk.pipe->fd.w );
		userEnviron = setEnv( userEnviron, "DESKTOP_SESSION", desksess );
		for (i = 0; td->sessionsDirs[i]; i++) {
			fname = 0;
			if (strApp( &fname, td->sessionsDirs[i], "/", desksess, ".desktop", (char *)0 )) {
				if ((str = iniLoad( fname ))) {
					if (!strCmp( iniEntry( str, "Desktop Entry", "Hidden", 0 ), "true" ) ||
					    !(sessargs = iniEntry( str, "Desktop Entry", "Exec", 0 )))
						sessargs = "";
					free( str );
					free( fname );
					goto gotit;
				}
				free( fname );
			}
		}
		if (!strcmp( desksess, "failsafe" ) ||
		    !strcmp( desksess, "default" ) ||
		    !strcmp( desksess, "custom" ))
			sessargs = desksess;
		else
			sessargs = "";
	  gotit:
		if (!(argv = parseArgs( (char **)0, td->session )) ||
		    !(argv = addStrArr( argv, sessargs, -1 )))
			exit( 1 );
		if (argv[0] && *argv[0]) {
			debug( "executing session %\"[s\n", argv );
			execute( argv, userEnviron );
			logError( "Session %\"s execution failed: %m\n", argv[0] );
		} else
			logError( "Session has no command/arguments\n" );
		failsafeArgv[0] = td->failsafeClient;
		failsafeArgv[1] = 0;
		execute( failsafeArgv, userEnviron );
		logError( "Failsafe client %\"s execution failed: %m\n",
		          failsafeArgv[0] );
	  cError:
		sendStr( V_MSG_ERR, 0 );
		exit( 1 );
	case -1:
		free( buf );
		return 0;
	}
	debug( "StartSession, fork succeeded %d\n", *pid );
	free( buf );

	gSet( &ctltalk );
	if (!Setjmp( ctltalk.errjmp ))
		while (gRecvCmd( &i )) {
			buf = gRecvStr();
			displayStr( i, buf );
			free( buf );
			gSet( &ctltalk );
			gSendInt( 0 );
		}
	gClosen( ctltalk.pipe );
	finishGreet();

	return 1;
}
Beispiel #28
0
/***************************************************************************
 *   Copyright (C) 2005-09 by the Quassel Project                          *
 *   [email protected]                                                 *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) version 3.                                           *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "ctcphandler.h"

#include "message.h"
#include "network.h"
#include "quassel.h"
#include "util.h"

CtcpHandler::CtcpHandler(CoreNetwork *parent)
  : BasicHandler(parent),
    XDELIM("\001")
{

  QByteArray MQUOTE = QByteArray("\020");
  ctcpMDequoteHash[MQUOTE + '0'] = QByteArray(1, '\000');
  ctcpMDequoteHash[MQUOTE + 'n'] = QByteArray(1, '\n');
  ctcpMDequoteHash[MQUOTE + 'r'] = QByteArray(1, '\r');
  ctcpMDequoteHash[MQUOTE + MQUOTE] = MQUOTE;

  QByteArray XQUOTE = QByteArray("\134");
  ctcpXDelimDequoteHash[XQUOTE + XQUOTE] = XQUOTE;
  ctcpXDelimDequoteHash[XQUOTE + QByteArray("a")] = XDELIM;
}

QByteArray CtcpHandler::lowLevelQuote(const QByteArray &message) {
  QByteArray quotedMessage = message;

  QHash<QByteArray, QByteArray> quoteHash = ctcpMDequoteHash;
  QByteArray MQUOTE = QByteArray("\020");
  quoteHash.remove(MQUOTE + MQUOTE);
  quotedMessage.replace(MQUOTE, MQUOTE + MQUOTE);

  QHash<QByteArray, QByteArray>::const_iterator quoteIter = quoteHash.constBegin();
  while(quoteIter != quoteHash.constEnd()) {
    quotedMessage.replace(quoteIter.value(), quoteIter.key());
    quoteIter++;
  }
  return quotedMessage;
}

QByteArray CtcpHandler::lowLevelDequote(const QByteArray &message) {
  QByteArray dequotedMessage;
  QByteArray messagepart;
  QHash<QByteArray, QByteArray>::iterator ctcpquote;

  // copy dequote Message
  for(int i = 0; i < message.size(); i++) {
    messagepart = message.mid(i,1);
    if(i+1 < message.size()) {
      for(ctcpquote = ctcpMDequoteHash.begin(); ctcpquote != ctcpMDequoteHash.end(); ++ctcpquote) {
        if(message.mid(i,2) == ctcpquote.key()) {
          messagepart = ctcpquote.value();
          i++;
          break;
        }
      }
    }
    dequotedMessage += messagepart;
  }
  return dequotedMessage;
}

QByteArray CtcpHandler::xdelimQuote(const QByteArray &message) {
  QByteArray quotedMessage = message;
  QHash<QByteArray, QByteArray>::const_iterator quoteIter = ctcpXDelimDequoteHash.constBegin();
  while(quoteIter != ctcpXDelimDequoteHash.constEnd()) {
    quotedMessage.replace(quoteIter.value(), quoteIter.key());
    quoteIter++;
  }
  return quotedMessage;
}

QByteArray CtcpHandler::xdelimDequote(const QByteArray &message) {
  QByteArray dequotedMessage;
  QByteArray messagepart;
  QHash<QByteArray, QByteArray>::iterator xdelimquote;

  for(int i = 0; i < message.size(); i++) {
    messagepart = message.mid(i,1);
    if(i+1 < message.size()) {
      for(xdelimquote = ctcpXDelimDequoteHash.begin(); xdelimquote != ctcpXDelimDequoteHash.end(); ++xdelimquote) {
        if(message.mid(i,2) == xdelimquote.key()) {
          messagepart = xdelimquote.value();
          i++;
          break;
        }
      }
    }
    dequotedMessage += messagepart;
  }
  return dequotedMessage;
}

void CtcpHandler::parse(Message::Type messageType, const QString &prefix, const QString &target, const QByteArray &message) {
  QByteArray ctcp;

  //lowlevel message dequote
  QByteArray dequotedMessage = lowLevelDequote(message);

  CtcpType ctcptype = messageType == Message::Notice
    ? CtcpReply
    : CtcpQuery;

  Message::Flags flags = (messageType == Message::Notice && !network()->isChannelName(target))
    ? Message::Redirected
    : Message::None;

  // extract tagged / extended data
  int xdelimPos = -1;
  int xdelimEndPos = -1;
  int spacePos = -1;
  while((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) {
    if(xdelimPos > 0)
      displayMsg(messageType, target, userDecode(target, dequotedMessage.left(xdelimPos)), prefix, flags);

    xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1);
    if(xdelimEndPos == -1) {
      // no matching end delimiter found... treat rest of the message as ctcp
      xdelimEndPos = dequotedMessage.count();
    }
    ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
    dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);

    //dispatch the ctcp command
    QString ctcpcmd = userDecode(target, ctcp.left(spacePos));
    QString ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));

    spacePos = ctcp.indexOf(' ');
    if(spacePos != -1) {
      ctcpcmd = userDecode(target, ctcp.left(spacePos));
      ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
    } else {
      ctcpcmd = userDecode(target, ctcp);
      ctcpparam = QString();
    }

    handle(ctcpcmd, Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam));
  }

  if(!dequotedMessage.isEmpty())
    displayMsg(messageType, target, userDecode(target, dequotedMessage), prefix, flags);
}

QByteArray CtcpHandler::pack(const QByteArray &ctcpTag, const QByteArray &message) {
  return XDELIM + ctcpTag + ' ' + xdelimQuote(message) + XDELIM;
}

void CtcpHandler::query(const QString &bufname, const QString &ctcpTag, const QString &message) {
  QList<QByteArray> params;
  params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
  emit putCmd("PRIVMSG", params);
}

void CtcpHandler::reply(const QString &bufname, const QString &ctcpTag, const QString &message) {
  QList<QByteArray> params;
  params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
  emit putCmd("NOTICE", params);
}

//******************************/
// CTCP HANDLER
//******************************/
void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) {
  Q_UNUSED(ctcptype)
  emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix);
}
Beispiel #29
0
static int
#if defined(USE_PAM) || defined(_AIX)
isNoPassAllowed( const char *un )
{
	struct passwd *pw = 0;
# ifdef HAVE_GETSPNAM /* (sic!) - not USESHADOW */
	struct spwd *spw;
# endif
#else
isNoPassAllowed( const char *un, struct passwd *pw )
{
#endif
	struct group *gr;
	char **fp;
	int hg;

	if (!*un)
		return 0;

	if (cursource != PWSRC_MANUAL)
		return 1;

	for (hg = 0, fp = td->noPassUsers; *fp; fp++)
		if (**fp == '@')
			hg = 1;
		else if (!strcmp( un, *fp ))
			return 1;
		else if (!strcmp( "*", *fp )) {
#if defined(USE_PAM) || defined(_AIX)
			if (!(pw = getpwnam( un )))
				return 0;
			if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
				continue;
# ifdef HAVE_GETSPNAM /* (sic!) - not USESHADOW */
			if ((spw = getspnam( un )) &&
			    (spw->sp_pwdp[0] == '!' || spw->sp_pwdp[0] == '*'))
					continue;
# endif
#endif
			if (pw->pw_uid)
				return 1;
		}

#if defined(USE_PAM) || defined(_AIX)
	if (hg && (pw || (pw = getpwnam( un )))) {
#else
	if (hg) {
#endif
		for (setgrent(); (gr = getgrent()); )
			for (fp = td->noPassUsers; *fp; fp++)
				if (**fp == '@' && !strcmp( gr->gr_name, *fp + 1 )) {
					if (pw->pw_gid == gr->gr_gid) {
						endgrent();
						return 1;
					}
					for (; *gr->gr_mem; gr->gr_mem++)
						if (!strcmp( un, *gr->gr_mem )) {
							endgrent();
							return 1;
						}
				}
		endgrent();
	}

	return 0;
}

#if !defined(USE_PAM) && !defined(_AIX) && defined(HAVE_SETUSERCONTEXT)
# define LC_RET0 do { login_close(lc); return 0; } while(0)
#else
# define LC_RET0 return 0
#endif

int
verify( GConvFunc gconv, int rootok )
{
#ifdef USE_PAM
	const char *psrv;
	struct pam_data pdata;
	int pretc, pnopass;
	char psrvb[64];
#elif defined(_AIX)
	char *msg, *curret;
	int i, reenter;
#else
	struct stat st;
	const char *nolg;
	char *buf;
	int fd;
# ifdef HAVE_GETUSERSHELL
	char *s;
# endif
# if defined(HAVE_STRUCT_PASSWD_PW_EXPIRE) || defined(USESHADOW)
	int tim, expir, warntime, quietlog;
# endif
#endif

	debug( "verify ...\n" );

#ifdef USE_PAM

	pnopass = FALSE;
	if (!strcmp( curtype, "classic" )) {
		if (!gconv( GCONV_USER, 0 ))
			return 0;
		if (isNoPassAllowed( curuser )) {
			gconv( GCONV_PASS_ND, 0 );
			if (!*curpass) {
				pnopass = TRUE;
				sprintf( psrvb, "%.31s-np", PAMService );
				psrv = psrvb;
			} else
				psrv = PAMService;
		} else
			psrv = PAMService;
		pdata.usecur = TRUE;
	} else {
		sprintf( psrvb, "%.31s-%.31s", PAMService, curtype );
		psrv = psrvb;
		pdata.usecur = FALSE;
	}
	pdata.gconv = gconv;
	if (!doPAMAuth( psrv, &pdata ))
		return 0;

#elif defined(_AIX)

	if ((td->displayType & d_location) == dForeign) {
		char *tmpch;
		strncpy( hostname, td->name, sizeof(hostname) - 1 );
		hostname[sizeof(hostname)-1] = '\0';
		if ((tmpch = strchr( hostname, ':' )))
			*tmpch = '\0';
	} else
		hostname[0] = '\0';

	/* tty names should only be 15 characters long */
# if 0
	for (i = 0; i < 15 && td->name[i]; i++) {
		if (td->name[i] == ':' || td->name[i] == '.')
			tty[i] = '_';
		else
			tty[i] = td->name[i];
	}
	tty[i] = '\0';
# else
	memcpy( tty, "/dev/xdm/", 9 );
	for (i = 0; i < 6 && td->name[i]; i++) {
		if (td->name[i] == ':' || td->name[i] == '.')
			tty[9 + i] = '_';
		else
			tty[9 + i] = td->name[i];
	}
	tty[9 + i] = '\0';
# endif

	if (!strcmp( curtype, "classic" )) {
		if (!gconv( GCONV_USER, 0 ))
			return 0;
		if (isNoPassAllowed( curuser )) {
			gconv( GCONV_PASS_ND, 0 );
			if (!*curpass) {
				debug( "accepting despite empty password\n" );
				goto done;
			}
		} else
			if (!gconv( GCONV_PASS, 0 ))
				return 0;
		enduserdb();
		msg = NULL;
		if ((i = authenticate( curuser, curpass, &reenter, &msg ))) {
			debug( "authenticate() failed: %s\n", msg );
			if (msg)
				free( msg );
			loginfailed( curuser, hostname, tty );
			if (i == ENOENT || i == ESAD)
				V_RET_AUTH;
			else
				V_RET_FAIL( 0 );
		}
		if (reenter) {
			logError( "authenticate() requests more data: %s\n", msg );
			free( msg );
			V_RET_FAIL( 0 );
		}
	} else if (!strcmp( curtype, "generic" )) {
		if (!gconv( GCONV_USER, 0 ))
			return 0;
		for (curret = 0;;) {
			msg = NULL;
			if ((i = authenticate( curuser, curret, &reenter, &msg ))) {
				debug( "authenticate() failed: %s\n", msg );
				if (msg)
					free( msg );
				loginfailed( curuser, hostname, tty );
				if (i == ENOENT || i == ESAD)
					V_RET_AUTH;
				else
					V_RET_FAIL( 0 );
			}
			if (curret)
				free( curret );
			if (!reenter)
				break;
			if (!(curret = gconv( GCONV_HIDDEN, msg )))
				return 0;
			free( msg );
		}
	} else {
		logError( "Unsupported authentication type %\"s requested\n", curtype );
		V_RET_FAIL( 0 );
	}
	if (msg) {
		displayStr( V_MSG_INFO, msg );
		free( msg );
	}

  done:

#else

	if (strcmp( curtype, "classic" )) {
		logError( "Unsupported authentication type %\"s requested\n", curtype );
		V_RET_FAIL( 0 );
	}

	if (!gconv( GCONV_USER, 0 ))
		return 0;

	if (!(p = getpwnam( curuser ))) {
		debug( "getpwnam() failed.\n" );
		gconv( GCONV_PASS, 0 );
		V_RET_AUTH;
	}
	if (p->pw_passwd[0] == '!' || p->pw_passwd[0] == '*') {
		debug( "account is locked\n" );
		gconv( GCONV_PASS, 0 );
		V_RET_AUTH;
	}

# ifdef USESHADOW
	if ((sp = getspnam( curuser ))) {
		p->pw_passwd = sp->sp_pwdp;
		if (p->pw_passwd[0] == '!' || p->pw_passwd[0] == '*') {
			debug( "account is locked\n" );
			gconv( GCONV_PASS, 0 );
			V_RET_AUTH;
		}
	} else
		debug( "getspnam() failed: %m. Are you root?\n" );
# endif

	if (!*p->pw_passwd) {
		if (!td->allowNullPasswd) {
			debug( "denying user with empty password\n" );
			gconv( GCONV_PASS, 0 );
			V_RET_AUTH;
		}
		goto nplogin;
	}

	if (isNoPassAllowed( curuser, p )) {
	  nplogin:
		gconv( GCONV_PASS_ND, 0 );
		if (!*curpass) {
			debug( "accepting password-less login\n" );
			goto done;
		}
	} else
		if (!gconv( GCONV_PASS, 0 ))
			return 0;

# ifdef KERBEROS
	if (p->pw_uid) {
		int ret;
		char realm[REALM_SZ];

		if (krb_get_lrealm( realm, 1 )) {
			logError( "Cannot get KerberosIV realm.\n" );
			V_RET_FAIL( 0 );
		}

		sprintf( krbtkfile, "%s.%.*s", TKT_ROOT, MAXPATHLEN - strlen( TKT_ROOT ) - 2, td->name );
		krb_set_tkt_string( krbtkfile );
		unlink( krbtkfile );

		ret = krb_verify_user( curuser, "", realm, curpass, 1, "rcmd" );
		if (ret == KSUCCESS) {
			chown( krbtkfile, p->pw_uid, p->pw_gid );
			debug( "KerberosIV verify succeeded\n" );
			goto done;
		} else if (ret != KDC_PR_UNKNOWN && ret != SKDC_CANT) {
			logError( "KerberosIV verification failure %\"s for %s\n",
			          krb_get_err_text( ret ), curuser );
			krbtkfile[0] = '\0';
			V_RET_FAIL( 0 );
		}
		debug( "KerberosIV verify failed: %s\n", krb_get_err_text( ret ) );
	}
	krbtkfile[0] = '\0';
# endif	 /* KERBEROS */

# if defined(ultrix) || defined(__ultrix__)
	if (authenticate_user( p, curpass, NULL ) < 0)
# elif defined(HAVE_PW_ENCRYPT)
	if (strcmp( pw_encrypt( curpass, p->pw_passwd ), p->pw_passwd ))
# elif defined(HAVE_CRYPT)
	if (strcmp( crypt( curpass, p->pw_passwd ), p->pw_passwd ))
# else
	if (strcmp( curpass, p->pw_passwd ))
# endif
	{
		debug( "password verify failed\n" );
		V_RET_AUTH;
	}

  done:

#endif /* !defined(USE_PAM) && !defined(_AIX) */

	debug( "restrict %s ...\n", curuser );

#if defined(USE_PAM) || defined(_AIX)
	if (!(p = getpwnam( curuser ))) {
		logError( "getpwnam(%s) failed.\n", curuser );
		V_RET_FAIL( 0 );
	}
#endif
	if (!p->pw_uid) {
		if (!rootok && !td->allowRootLogin)
			V_RET_FAIL( "Root logins are not allowed" );
		return 1; /* don't deny root to log in */
	}

#ifdef USE_PAM

	debug( " pam_acct_mgmt() ...\n" );
	pretc = pam_acct_mgmt( pamh, 0 );
	reInitErrorLog();
	debug( " pam_acct_mgmt() returned: %s\n", pam_strerror( pamh, pretc ) );
	if (pretc == PAM_NEW_AUTHTOK_REQD) {
		pdata.usecur = FALSE;
		pdata.gconv = conv_interact;
		/* pam will have output a message already, so no prepareErrorGreet() */
		if (gconv != conv_interact || pnopass) {
			pam_end( pamh, PAM_SUCCESS );
			pamh = 0;
			gSendInt( V_CHTOK_AUTH );
			/* this cannot auth the wrong user, as only classic auths get here */
			while (!doPAMAuth( PAMService, &pdata ))
				if (pdata.abort)
					return 0;
			gSendInt( V_PRE_OK );
		} else
			gSendInt( V_CHTOK );
		for (;;) {
			debug( " pam_chauthtok() ...\n" );
			pretc = pam_chauthtok( pamh, PAM_CHANGE_EXPIRED_AUTHTOK );
			reInitErrorLog();
			debug( " pam_chauthtok() returned: %s\n", pam_strerror( pamh, pretc ) );
			if (pdata.abort) {
				pam_end( pamh, PAM_SUCCESS );
				pamh = 0;
				return 0;
			}
			if (pretc == PAM_SUCCESS)
				break;
			/* effectively there is only PAM_AUTHTOK_ERR */
			gSendInt( V_FAIL );
		}
		if (curpass)
			free( curpass );
		curpass = newpass;
		newpass = 0;
	} else if (pretc != PAM_SUCCESS) {
		pam_end( pamh, pretc );
		pamh = 0;
		V_RET_AUTH;
	}

#elif defined(_AIX) /* USE_PAM */

	msg = NULL;
	if (loginrestrictions( curuser,
	                       ((td->displayType & d_location) == dForeign) ? S_RLOGIN : S_LOGIN,
	                       tty, &msg ) == -1)
	{
		debug( "loginrestrictions() - %s\n", msg ? msg : "error" );
		loginfailed( curuser, hostname, tty );
		prepareErrorGreet();
		if (msg) {
			displayStr( V_MSG_ERR, msg );
			free( msg );
		}
		gSendInt( V_AUTH );
		return 0;
	}
	if (msg)
		free( (void *)msg );

#endif /* USE_PAM || _AIX */

#ifndef _AIX

# ifdef HAVE_SETUSERCONTEXT
#  ifdef HAVE_LOGIN_GETCLASS
	lc = login_getclass( p->pw_class );
#  else
	lc = login_getpwclass( p );
#  endif
	if (!lc)
		V_RET_FAIL( 0 );

	p->pw_shell = login_getcapstr( lc, "shell", p->pw_shell, p->pw_shell );
# endif

# ifndef USE_PAM

/* restrict_expired */
#  if defined(HAVE_STRUCT_PASSWD_PW_EXPIRE) || defined(USESHADOW)

#   if !defined(HAVE_STRUCT_PASSWD_PW_EXPIRE) || (!defined(HAVE_SETUSERCONTEXT) && defined(USESHADOW))
	if (sp)
#   endif
	{

#   define DEFAULT_WARN	(2L * 7L)  /* Two weeks */

		tim = time( NULL ) / 86400L;

#   ifdef HAVE_SETUSERCONTEXT
		quietlog = login_getcapbool( lc, "hushlogin", 0 );
		warntime = login_getcaptime( lc, "warnexpire",
		                             DEFAULT_WARN * 86400L,
		                             DEFAULT_WARN * 86400L ) / 86400L;
#   else
		quietlog = 0;
#    ifdef USESHADOW
		warntime = sp->sp_warn != -1 ? sp->sp_warn : DEFAULT_WARN;
#    else
		warntime = DEFAULT_WARN;
#    endif
#   endif

#   ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
		if (p->pw_expire) {
			expir = p->pw_expire / 86400L;
#   else
		if (sp->sp_expire != -1) {
			expir = sp->sp_expire;
#   endif
			if (tim > expir) {
				displayStr( V_MSG_ERR,
				            "Your account has expired;"
				            " please contact your system administrator" );
				gSendInt( V_FAIL );
				LC_RET0;
			} else if (tim > (expir - warntime) && !quietlog) {
				displayMsg( V_MSG_INFO,
				            "Warning: your account will expire in %d day(s)",
				            expir - tim );
			}
		}

#   ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
		if (p->pw_change) {
			expir = p->pw_change / 86400L;
#   else
		if (!sp->sp_lstchg) {
			displayStr( V_MSG_ERR,
			            "You are required to change your password immediately"
			            " (root enforced)" );
			/* XXX todo password change */
			gSendInt( V_FAIL );
			LC_RET0;
		} else if (sp->sp_max != -1) {
			expir = sp->sp_lstchg + sp->sp_max;
			if (sp->sp_inact != -1 && tim > expir + sp->sp_inact) {
				displayStr( V_MSG_ERR,
				            "Your account has expired;"
				            " please contact your system administrator" );
				gSendInt( V_FAIL );
				LC_RET0;
			}
#   endif
			if (tim > expir) {
				displayStr( V_MSG_ERR,
				            "You are required to change your password immediately"
				            " (password aged)" );
				/* XXX todo password change */
				gSendInt( V_FAIL );
				LC_RET0;
			} else if (tim > (expir - warntime) && !quietlog) {
				displayMsg( V_MSG_INFO,
				            "Warning: your password will expire in %d day(s)",
				            expir - tim );
			}
		}

	}

#  endif /* HAVE_STRUCT_PASSWD_PW_EXPIRE || USESHADOW */

/* restrict_nologin */
#  ifndef _PATH_NOLOGIN
#   define _PATH_NOLOGIN "/etc/nologin"
#  endif

	if ((
#  ifdef HAVE_SETUSERCONTEXT
	     /* Do we ignore a nologin file? */
	     !login_getcapbool( lc, "ignorenologin", 0 )) &&
	    (!stat( (nolg = login_getcapstr( lc, "nologin", "", NULL )), &st ) ||
#  endif
		 !stat( (nolg = _PATH_NOLOGIN), &st )))
	{
		if (st.st_size && (fd = open( nolg, O_RDONLY )) >= 0) {
			if ((buf = Malloc( st.st_size + 1 ))) {
				if (read( fd, buf, st.st_size ) == st.st_size) {
					close( fd );
					buf[st.st_size] = 0;
					displayStr( V_MSG_ERR, buf );
					free( buf );
					gSendInt( V_FAIL );
					LC_RET0;
				}
				free( buf );
			}
			close( fd );
		}
		displayStr( V_MSG_ERR,
		            "Logins are not allowed at the moment.\nTry again later" );
		gSendInt( V_FAIL );
		LC_RET0;
	}

/* restrict_time */
#  if defined(HAVE_SETUSERCONTEXT) && defined(HAVE_AUTH_TIMEOK)
	if (!auth_timeok( lc, time( NULL ) )) {
		displayStr( V_MSG_ERR,
		            "You are not allowed to login at the moment" );
		gSendInt( V_FAIL );
		LC_RET0;
	}
#  endif

#  ifdef HAVE_GETUSERSHELL
	for (;;) {
		if (!(s = getusershell())) {
			debug( "shell not in /etc/shells\n" );
			endusershell();
			V_RET_FAIL( "Your login shell is not listed in /etc/shells" );
		}
		if (!strcmp( s, p->pw_shell )) {
			endusershell();
			break;
		}
	}
#  endif

# endif /* !USE_PAM */

/* restrict_nohome */
# ifdef HAVE_SETUSERCONTEXT
	if (login_getcapbool( lc, "requirehome", 0 )) {
		struct stat st;
		if (!*p->pw_dir || stat( p->pw_dir, &st ) || st.st_uid != p->pw_uid) {
			displayStr( V_MSG_ERR, "Home folder not available" );
			gSendInt( V_FAIL );
			LC_RET0;
		}
	}
# endif

#endif /* !_AIX */

	return 1;

}


static const char *envvars[] = {
	"TZ", /* SYSV and SVR4, but never hurts */
#ifdef _AIX
	"AUTHSTATE", /* for kerberos */
#endif
	NULL
};


#if defined(USE_PAM) && defined(HAVE_INITGROUPS)
static int num_saved_gids;
static gid_t *saved_gids;

static int
saveGids( void )
{
	num_saved_gids = getgroups( 0, 0 );
	if (!(saved_gids = Malloc( sizeof(gid_t) * num_saved_gids )))
		return 0;
	if (getgroups( num_saved_gids, saved_gids ) < 0) {
		logError( "saving groups failed: %m\n" );
		return 0;
	}
	return 1;
}

static int
restoreGids( void )
{
	if (setgroups( num_saved_gids, saved_gids ) < 0) {
		logError( "restoring groups failed: %m\n" );
		return 0;
	}
	if (setgid( p->pw_gid ) < 0) {
		logError( "restoring gid failed: %m\n" );
		return 0;
	}
	return 1;
}
#endif /* USE_PAM && HAVE_INITGROUPS */

static int
resetGids( void )
{
#ifdef HAVE_INITGROUPS
	if (setgroups( 0, &p->pw_gid /* anything */ ) < 0) {
		logError( "restoring groups failed: %m\n" );
		return 0;
	}
#endif
	if (setgid( 0 ) < 0) {
		logError( "restoring gid failed: %m\n" );
		return 0;
	}
	return 1;
}

static int
setGid( const char *name, int gid )
{
	if (setgid( gid ) < 0) {
		logError( "setgid(%d) (user %s) failed: %m\n", gid, name );
		return 0;
	}
#ifdef HAVE_INITGROUPS
	if (initgroups( name, gid ) < 0) {
		logError( "initgroups for %s failed: %m\n", name );
		setgid( 0 );
		return 0;
	}
#endif	 /* QNX4 doesn't support multi-groups, no initgroups() */
	return 1;
}

static int
setUid( const char *name, int uid )
{
	if (setuid( uid ) < 0) {
		logError( "setuid(%d) (user %s) failed: %m\n", uid, name );
		return 0;
	}
	return 1;
}

static int
setUser( const char *name, int uid, int gid )
{
	if (setGid( name, gid )) {
		if (setUid( name, uid ))
			return 1;
		resetGids();
	}
	return 0;
}

#if defined(SECURE_RPC) || defined(K5AUTH)
static void
nukeAuth( int len, const char *name )
{
	int i;

	for (i = 0; i < td->authNum; i++)
		if (td->authorizations[i]->name_length == len &&
		    !memcmp( td->authorizations[i]->name, name, len ))
		{
			memcpy( &td->authorizations[i], &td->authorizations[i+1],
			        sizeof(td->authorizations[i]) * (--td->authNum - i) );
			break;
		}
}
#endif

static void
mergeSessionArgs( int cansave )
{
	char *mfname;
	const char *fname;
	int i, needsave;

	mfname = 0;
	fname = ".dmrc";
	if ((!curdmrc || newdmrc) && *dmrcDir)
		if (strApp( &mfname, dmrcDir, "/", curuser, fname, (char *)0 ))
			fname = mfname;
	needsave = 0;
	if (!curdmrc) {
		curdmrc = iniLoad( fname );
		if (!curdmrc) {
			strDup( &curdmrc, "[Desktop]\nSession=default\n" );
			needsave = 1;
		}
	}
	if (newdmrc) {
		curdmrc = iniMerge( curdmrc, newdmrc );
		needsave = 1;
	}
	if (needsave && cansave)
		if (!iniSave( curdmrc, fname ) && errno == ENOENT && mfname) {
			for (i = 0; mfname[i]; i++)
				if (mfname[i] == '/') {
					mfname[i] = 0;
					mkdir( mfname, 0755 );
					mfname[i] = '/';
				}
			iniSave( curdmrc, mfname );
		}
	if (mfname)
		free( mfname );
}

static int
createClientLog( const char *log )
{
	char randstr[32], *randstrp = 0, *lname;
	int lfd;

	for (;;) {
		struct expando macros[] = {
			{ 'd', 0, td->name },
			{ 'u', 0, curuser },
			{ 'r', 0, randstrp },
			{ 0, 0, 0 }
		};
		if (!(lname = expandMacros( log, macros )))
			exit( 1 );
		unlink( lname );
		if ((lfd = open( lname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) >= 0) {
			dup2( lfd, 1 );
			dup2( lfd, 2 );
			close( lfd );
			free( lname );
			return TRUE;
		}
		if (errno != EEXIST || !macros[2].uses) {
			free( lname );
			return FALSE;
		}
		logInfo( "Session log file %s not usable, trying another one.\n",
		         lname );
		free( lname );
		sprintf( randstr, "%d", secureRandom() );
		randstrp = randstr;
	}
}
Beispiel #30
-1
static void MAMACALLTYPE
wildCardMsgCb (mamaSubscription       subscription, 
               mamaMsg                msg, 
               const char*            topic,
               void *                 closure,
               void *                 itemClosure)
{
    static int i = 0;
    
    if (gMuteTopic)
    {
        const char* topic = NULL;
        mamaMsg_getString (msg, "PublisherTopic", 10002, &topic);
        if (0 == strncmp (topic, gMuteTopic, strlen(topic)))
        {
            gMuteTopic = NULL;
            printf ("Mutting %s\n", topic);
            mamaSubscription_muteCurrentTopic (subscription);
            return;
        }
    }
    if (itemClosure == NULL)
    {
        mamaSubscription_setItemClosure (subscription, (void*)strdup(topic));
    }
    if (gQuietLevel < 2)
    {
        printf ("Received Wild Card Message with topic %s closure=%s\n",
                topic,
                (char*)itemClosure);
    }
    displayMsg (msg);
}