Example #1
0
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdParamarg, int cmdShow) {
    openLog();

#ifdef _NEED_WIN_GENERATE_DUMP
    _oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter);
#endif

    writeLog(L"Updaters started..");

    LPWSTR *args;
    int argsCount;

    bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, testmode = false;
    args = CommandLineToArgvW(GetCommandLine(), &argsCount);
    if (args) {
        for (int i = 1; i < argsCount; ++i) {
            if (equal(args[i], L"-update")) {
                needupdate = true;
            } else if (equal(args[i], L"-autostart")) {
                autostart = true;
            } else if (equal(args[i], L"-debug")) {
                debug = _debug = true;
                openLog();
            } else if (equal(args[i], L"-startintray")) {
                startintray = true;
            } else if (equal(args[i], L"-testmode")) {
                testmode = true;
            } else if (equal(args[i], L"-writeprotected") && ++i < argsCount) {
                writeprotected = true;
                updateTo = args[i];
                for (int i = 0, l = updateTo.size(); i < l; ++i) {
                    if (updateTo[i] == L'/') {
                        updateTo[i] = L'\\';
                    }
                }
            }
        }
        if (needupdate) writeLog(L"Need to update!");
        if (autostart) writeLog(L"From autostart!");
        if (writeprotected) writeLog(L"Write Protected folder!");

        exeName = args[0];
        writeLog(L"Exe name is: " + exeName);
        if (exeName.size() > 11) {
            if (equal(exeName.substr(exeName.size() - 11), L"Updater.exe")) {
                exeDir = exeName.substr(0, exeName.size() - 11);
                writeLog(L"Exe dir is: " + exeDir);
                if (!writeprotected) {
                    updateTo = exeDir;
                }
                writeLog(L"Update to: " + updateTo);
                if (needupdate && update()) {
                    updateRegistry();
                }
                if (writeprotected) { // if we can't clear all tupdates\ready (Updater.exe is there) - clear only version
                    if (DeleteFile(L"tupdates\\temp\\tdata\\version") || DeleteFile(L"tupdates\\ready\\tdata\\version")) {
                        writeLog(L"Version file deleted!");
                    } else {
                        writeLog(L"Error: could not delete version file");
                    }
                }
            } else {
                writeLog(L"Error: bad exe name!");
            }
        } else {
            writeLog(L"Error: short exe name!");
        }
        LocalFree(args);
    } else {
        writeLog(L"Error: No command line arguments!");
    }

    wstring targs;
    if (autostart) targs += L" -autostart";
    if (debug) targs += L" -debug";
    if (startintray) targs += L" -startintray";
    if (testmode) targs += L" -testmode";

    bool executed = false;
    if (writeprotected) { // run un-elevated
        writeLog(L"Trying to run un-elevated by temp.lnk");

        HRESULT hres = CoInitialize(0);
        if (SUCCEEDED(hres)) {
            IShellLink* psl;
            HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
            if (SUCCEEDED(hres)) {
                IPersistFile* ppf;

                wstring exe = updateTo + L"Telegram.exe", dir = updateTo;
                psl->SetArguments((targs.size() ? targs.substr(1) : targs).c_str());
                psl->SetPath(exe.c_str());
                psl->SetWorkingDirectory(dir.c_str());
                psl->SetDescription(L"");

                hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);

                if (SUCCEEDED(hres)) {
                    wstring lnk = L"tupdates\\temp\\temp.lnk";
                    hres = ppf->Save(lnk.c_str(), TRUE);
                    if (!SUCCEEDED(hres)) {
                        lnk = L"tupdates\\ready\\temp.lnk"; // old
                        hres = ppf->Save(lnk.c_str(), TRUE);
                    }
                    ppf->Release();

                    if (SUCCEEDED(hres)) {
                        writeLog(L"Executing un-elevated through link..");
                        ShellExecute(0, 0, L"explorer.exe", lnk.c_str(), 0, SW_SHOWNORMAL);
                        executed = true;
                    } else {
                        writeLog(L"Error: ppf->Save failed");
                    }
                } else {
                    writeLog(L"Error: Could not create interface IID_IPersistFile");
                }
                psl->Release();
            } else {
                writeLog(L"Error: could not create instance of IID_IShellLink");
            }
            CoUninitialize();
        } else {
            writeLog(L"Error: Could not initialize COM");
        }
    }
    if (!executed) {
        ShellExecute(0, 0, (updateTo + L"Telegram.exe").c_str(), (L"-noupdate" + targs).c_str(), 0, SW_SHOWNORMAL);
    }

    writeLog(L"Executed Telegram.exe, closing log and quiting..");
    closeLog();

    return 0;
}
Example #2
0
bool operator ==(const read_t& r1, const read_t& r2) {
  if (r1.size() != r2.size())
    return false;
  return equal(r1.begin(), r1.end(), r2.begin());
}
Example #3
0
//ntlTree::ntlTree(int depth, int objnum, vector<ntlVec3Gfx> *vertices, vector<ntlVec3Gfx> *normals, vector<ntlTriangle> *trilist) :
ntlTree::ntlTree(int depth, int objnum, ntlScene *scene, int triFlagMask) :
  mStart(0.0), mEnd(0.0), mMaxDepth( depth ), mMaxListLength( objnum ), mpRoot( NULL) ,
  mpNodeStack( NULL), mpTBB( NULL ),
	mTriangleMask( 0xFFFF ),
  mCurrentDepth(0), mCurrentNodes(0), mTriDoubles(0)
{  
	// init scene data pointers
	mpVertices = scene->getVertexPointer();
	mpVertNormals = scene->getVertexNormalPointer();
	mpTriangles = scene->getTrianglePointer();
	mTriangleMask = triFlagMask;

  if(mpTriangles == NULL) {
    errFatal( "ntlTree Cons","no triangle list!\n",SIMWORLD_INITERROR);
    return;
  }
  if(mpTriangles->size() == 0) {
    warnMsg( "ntlTree::ntlTree","No triangles ("<< mpTriangles->size()  <<")!\n");
		mStart = mEnd = ntlVec3Gfx(0,0,0);
    return;
  }
  if(depth>=BSP_STACK_SIZE) {
    errFatal( "ntlTree::ntlTree","Depth to high ("<< mMaxDepth  <<")!\n", SIMWORLD_INITERROR );
    return;
  }

  /* check triangles (a bit inefficient, but we dont know which vertices belong
     to this tree), and generate bounding boxes */
	mppTriangles = new vector<ntlTriangle *>;
	int noOfTriangles = mpTriangles->size();
	mpTBB = new TriangleBBox[ noOfTriangles ];
	int bbCount = 0;
  mStart = mEnd = (*mpVertices)[ mpTriangles->front().getPoints()[0] ];
	//errMsg("TreeDebug","Start");
  for (vector<ntlTriangle>::iterator iter = mpTriangles->begin();
       iter != mpTriangles->end(); 
       iter++ ) {
		//errorOut(" d "<< convertFlags2String((int)(*iter).getFlags()) <<" "<< convertFlags2String( (int)mTriangleMask)<<" add? "<<( ((int)(*iter).getFlags() & (int)mTriangleMask) != 0 ) );
		// discard triangles that dont match mask
		if( ((int)(*iter).getFlags() & (int)mTriangleMask) == 0 ) {
			continue;
		}

		// test? TODO
		ntlVec3Gfx tnormal = (*mpVertNormals)[ (*iter).getPoints()[0] ]+
			(*mpVertNormals)[ (*iter).getPoints()[1] ]+
			(*mpVertNormals)[ (*iter).getPoints()[2] ];
		ntlVec3Gfx triangleNormal = (*iter).getNormal();
		if( equal(triangleNormal, ntlVec3Gfx(0.0)) ) continue;
		if( equal(       tnormal, ntlVec3Gfx(0.0)) ) continue;
		// */

		ntlVec3Gfx bbs, bbe;
		//errMsg("TreeDebug","Triangle");
		for(int i=0;i<3;i++) {
			int index = (*iter).getPoints()[i];
			ntlVec3Gfx tp = (*mpVertices)[ index ];
			//errMsg("TreeDebug","  Point "<<i<<" = "<<tp<<" ");
			if(tp[0] < mStart[0]) mStart[0]= tp[0];
			if(tp[0] > mEnd[0])   mEnd[0]= tp[0];
			if(tp[1] < mStart[1]) mStart[1]= tp[1];
			if(tp[1] > mEnd[1])   mEnd[1]= tp[1];
			if(tp[2] < mStart[2]) mStart[2]= tp[2];
			if(tp[2] > mEnd[2])   mEnd[2]= tp[2];
			if(i==0) {
				bbs = bbe = tp; 
			} else {
				if( tp[0] < bbs[0] ) bbs[0] = tp[0];
				if( tp[0] > bbe[0] ) bbe[0] = tp[0];
				if( tp[1] < bbs[1] ) bbs[1] = tp[1];
				if( tp[1] > bbe[1] ) bbe[1] = tp[1];
				if( tp[2] < bbs[2] ) bbs[2] = tp[2];
				if( tp[2] > bbe[2] ) bbe[2] = tp[2];
			}
		}
		mppTriangles->push_back( &(*iter) );
		//errMsg("TreeDebug","Triangle "<<(*mpVertices)[(*iter).getPoints()[0]]<<" "<<(*mpVertices)[(*iter).getPoints()[1]]<<" "<<(*mpVertices)[(*iter).getPoints()[2]]<<" ");

		// add BB
		mpTBB[ bbCount ].start = bbs;
		mpTBB[ bbCount ].end = bbe;
		(*iter).setBBoxId( bbCount );
		bbCount++;
  }
	
	

  /* slighlty enlarge bounding tolerance for tree 
     to avoid problems with triangles paralell to slabs */
  mStart -= ntlVec3Gfx( getVecEpsilon() );
  mEnd   += ntlVec3Gfx( getVecEpsilon() );

  /* init root node and stack */
  mpNodeStack = new BSPStack;
  mpRoot = new BSPNode;
  mpRoot->min = mStart;
  mpRoot->max = mEnd;
  mpRoot->axis = AXIS_X;
  mpRoot->members = mppTriangles;
	mpRoot->child[0] = mpRoot->child[1] = NULL;
	mpRoot->cloneVec = 0;
	globalSortingPoints = mpVertices;
	mpTriDist = new char[ mppTriangles->size() ];
	mNumNodes = 1;
	mAbortSubdiv = 0;

  /* create tree */
  debugOutInter( "Generating BSP Tree...  (Nodes "<< mCurrentNodes <<
						", Depth "<<mCurrentDepth<< ") ", 2, 2000 );
  subdivide(mpRoot, 0, AXIS_X);
  debMsgStd("ntlTree::ntlTree",DM_MSG,"Generated Tree: Nodes "<< mCurrentNodes <<
							 ", Depth "<<mCurrentDepth<< " with "<<noOfTriangles<<" triangles", 2 );

	delete [] mpTriDist;
	delete [] mpTBB;
	mpTriDist = NULL;
	mpTBB = NULL;

	/* calculate some stats about tree */
	int noLeafs = 0;
	gfxReal avgDepth = 0.0;
	gfxReal triPerLeaf = 0.0;
	int totalTris = 0;
	
	calcStats(mpRoot,0, noLeafs, avgDepth, triPerLeaf, totalTris);
	avgDepth /= (gfxReal)noLeafs;
	triPerLeaf /= (gfxReal)noLeafs;
	debMsgStd("ntlTree::ntlTree",DM_MSG,"Tree ("<<doSort<<","<<chooseAxis<<") Stats: Leafs:"<<noLeafs<<", avgDepth:"<<avgDepth<<
			", triPerLeaf:"<<triPerLeaf<<", triDoubles:"<<mTriDoubles<<", totalTris:"<<totalTris
			<<" nodes:"<<mNumNodes
			//<<" T"<< (totalTris%3)  // 0=ich, 1=f, 2=a
			, 2 );

	if(mAbortSubdiv) {
		errMsg("ntlTree::ntlTree","Aborted... "<<mNumNodes);
  	deleteNode(mpRoot);
		mpRoot = NULL;
	}
}
Example #4
0
int
main(int argc, char **argv)
{
	char cnambuf[DLPI_LINKNAME_MAX], device[DLPI_LINKNAME_MAX];
	struct scc_mode sm;
	struct strioctl sioc;
	int fd, speed;
	int retval;
	char *arg, *cp;
	char loopchange = 0;
	char echochange = 0;
	char clockchange = 0;
	uint_t ppa;
	dlpi_handle_t dh;

	if (argc == 1) {
		usage();
		exit(1);
	}
	argc--;
	argv++;

	if (strlcpy(cnambuf, argv[0], sizeof (cnambuf)) >=
	    sizeof (cnambuf)) {
		(void) fprintf(stderr,
		    "syncinit: invalid device name (too long) %s\n", argv[0]);
		exit(1);
	}

	cp = cnambuf;
	while (*cp)			/* find the end of the name */
		cp++;
	cp--;
	if (!isdigit(*cp)) {
		(void) fprintf(stderr,
		    "syncinit: %s missing minor device number\n", cnambuf);
		exit(1);
	}

	retval = dlpi_open(cnambuf, &dh, DLPI_EXCL|DLPI_SERIAL);
	if (retval != DLPI_SUCCESS) {
		(void) fprintf(stderr, "syncinit: dlpi_open %s: %s\n", cnambuf,
		    dlpi_strerror(retval));
		exit(1);
	}

	(void) dlpi_parselink(cnambuf, device, &ppa);
	(void) printf("device: %s  ppa: %u\n", device, ppa);

	fd = dlpi_fd(dh);

	argc--;
	argv++;
	if (argc) {	/* setting things */
		sioc.ic_cmd = S_IOCGETMODE;
		sioc.ic_timout = -1;
		sioc.ic_len = sizeof (struct scc_mode);
		sioc.ic_dp = (char *)&sm;

		if (ioctl(fd, I_STR, &sioc) < 0) {
			perror("S_IOCGETMODE");
			(void) fprintf(stderr,
				"syncinit: can't get sync mode info for %s\n",
				cnambuf);
			exit(1);
		}
		while (argc-- > 0) {
			arg = *argv++;
			if (sscanf(arg, "%d", &speed) == 1)
				sm.sm_baudrate = speed;
			else if (strchr(arg, '=')) {
				if (prefix(arg, "loop")) {
					if (lookup(yesno, arg))
						sm.sm_config |= CONN_LPBK;
					else
						sm.sm_config &= ~CONN_LPBK;
					loopchange++;
				} else if (prefix(arg, "echo")) {
					if (lookup(yesno, arg))
						sm.sm_config |= CONN_ECHO;
					else
						sm.sm_config &= ~CONN_ECHO;
					echochange++;
				} else if (prefix(arg, "nrzi")) {
					if (lookup(yesno, arg))
						sm.sm_config |= CONN_NRZI;
					else
						sm.sm_config &= ~CONN_NRZI;
				} else if (prefix(arg, "txc")) {
					sm.sm_txclock = lookup(txnames, arg);
					clockchange++;
				} else if (prefix(arg, "rxc")) {
					sm.sm_rxclock = lookup(rxnames, arg);
					clockchange++;
				} else if (prefix(arg, "speed")) {
					arg = strchr(arg, '=') + 1;
					if (sscanf(arg, "%d", &speed) == 1) {
						sm.sm_baudrate = speed;
					} else
						(void) fprintf(stderr,
						    "syncinit: %s %s\n",
						    "bad speed:", arg);
				}
			} else if (equal(arg, "external")) {
				sm.sm_txclock = TXC_IS_TXC;
				sm.sm_rxclock = RXC_IS_RXC;
				sm.sm_config &= ~CONN_LPBK;
			} else if (equal(arg, "sender")) {
				sm.sm_txclock = TXC_IS_BAUD;
				sm.sm_rxclock = RXC_IS_RXC;
				sm.sm_config &= ~CONN_LPBK;
			} else if (equal(arg, "internal")) {
				sm.sm_txclock = TXC_IS_PLL;
				sm.sm_rxclock = RXC_IS_PLL;
				sm.sm_config &= ~CONN_LPBK;
			} else if (equal(arg, "stop")) {
				sm.sm_baudrate = 0;
			} else
				(void) fprintf(stderr, "Bad arg: %s\n", arg);
		}

		/*
		 * If we're going to change the state of loopback, and we
		 * don't have our own plans for clock sources, use defaults.
		 */
		if (loopchange && !clockchange) {
			if (sm.sm_config & CONN_LPBK) {
				sm.sm_txclock = TXC_IS_BAUD;
				sm.sm_rxclock = RXC_IS_BAUD;
			} else {
				sm.sm_txclock = TXC_IS_TXC;
				sm.sm_rxclock = RXC_IS_RXC;
			}
		}
		sioc.ic_cmd = S_IOCSETMODE;
		sioc.ic_timout = -1;
		sioc.ic_len = sizeof (struct scc_mode);
		sioc.ic_dp = (char *)&sm;
		if (ioctl(fd, I_STR, &sioc) < 0) {
			perror("S_IOCSETMODE");
			(void) ioctl(fd, S_IOCGETMODE, &sm);
			(void) fprintf(stderr,
				"syncinit: ioctl failure code = %x\n",
				sm.sm_retval);
			exit(1);
		}
	}

	/* Report State */
	sioc.ic_cmd = S_IOCGETMODE;
	sioc.ic_timout = -1;
	sioc.ic_len = sizeof (struct scc_mode);
	sioc.ic_dp = (char *)&sm;
	if (ioctl(fd, I_STR, &sioc) < 0) {
		perror("S_IOCGETMODE");
		(void) fprintf(stderr,
			"syncinit: can't get sync mode info for %s\n",
			cnambuf);
		exit(1);
	}
	(void) printf(
		"speed=%d, loopback=%s, echo=%s, nrzi=%s, txc=%s, rxc=%s\n",
		sm.sm_baudrate,
		yesno[((int)(sm.sm_config & CONN_LPBK) > 0)],
		yesno[((int)(sm.sm_config & CONN_ECHO) > 0)],
		yesno[((int)(sm.sm_config & CONN_NRZI) > 0)],
		txnames[sm.sm_txclock],
		rxnames[sm.sm_rxclock]);
	return (0);
}
Example #5
0
static int
yysimfac(int h)
{
	int i, j;

	for (i = h; i < tos; i++) {
		p1 = stack[i];
		for (j = h; j < tos; j++) {
			if (i == j)
				continue;
			p2 = stack[j];

			//	n! / n		->	(n - 1)!

			if (car(p1) == symbol(FACTORIAL)
			&& car(p2) == symbol(POWER)
			&& isminusone(caddr(p2))
			&& equal(cadr(p1), cadr(p2))) {
				push(cadr(p1));
				push(one);
				subtract();
				factorial();
				stack[i] = pop();
				stack[j] = one;
				return 1;
			}

			//	n / n!		->	1 / (n - 1)!
			{
				int a,b,c,d;
				a = car(p2) == symbol(POWER);
				b = isminusone(caddr(p2));
				c = caadr(p2) == symbol(FACTORIAL);
				d = equal(p1, cadadr(p2));
				if ( a
				&& b
				&& c
				&& d){
					push(p1);
					push_integer(-1);
					add();
					factorial();
					reciprocate();
					stack[i] = pop();
					stack[j] = one;
					return 1;
				}
			}
			//	(n + 1) n!	->	(n + 1)!

			if (car(p2) == symbol(FACTORIAL)) {
				push(p1);
				push(cadr(p2));
				subtract();
				p3 = pop();
				if (isplusone(p3)) {
					push(p1);
					factorial();
					stack[i] = pop();
					stack[j] = one;
					return 1;
				}
			}

			//	1 / ((n + 1) n!)	->	1 / (n + 1)!

			if (car(p1) == symbol(POWER)
			&& isminusone(caddr(p1))
			&& car(p2) == symbol(POWER)
			&& isminusone(caddr(p2))
			&& caadr(p2) == symbol(FACTORIAL)) {
				push(cadr(p1)); // modified

				push(car(cdr(cadr(p2))));
				subtract();
				p3 = pop();
				if (isplusone(p3)) {
					push(cadr(p1));
					factorial();
					reciprocate();
					stack[i] = pop();
					stack[j] = one;
					return 1;
				}
			}

			//	(n + 1)! / n!	->	n + 1

			//	n! / (n + 1)!	->	1 / (n + 1)

			if (car(p1) == symbol(FACTORIAL)
			&& car(p2) == symbol(POWER)
			&& isminusone(caddr(p2))
			&& caadr(p2) == symbol(FACTORIAL)) {
				push(cadr(p1));
				push(car(cdr(cadr(p2))));
				subtract();
				p3 = pop();
				if (isplusone(p3)) {
					stack[i] = cadr(p1);
					stack[j] = one;
					return 1;
				}
				if (isminusone(p3)) {
					push(car(cdr(cadr(p2))));
					reciprocate();
					stack[i] = pop();
					stack[j] = one;
					return 1;
				}
				if (equaln(p3, 2)) {
					stack[i] = cadr(p1);
					push(cadr(p1));
					push_integer(-1);
					add();
					stack[j] = pop();
					return 1;
				}
				if (equaln(p3, -2)) {
					push(car(cdr(cadr(p2))));
					reciprocate();
					stack[i] = pop();
					push(car(cdr(cadr(p2))));
					push_integer(-1);
					add();
					reciprocate();
					stack[j] = pop();
					return 1;
				}
			}
		}
	}

	return 0;
}
Example #6
0
int __EXPORT quaternionTest()
{
	printf("Test Quaternion\t\t: ");
	// test default ctor
	Quaternion q;
	ASSERT(equal(q.getA(), 1));
	ASSERT(equal(q.getB(), 0));
	ASSERT(equal(q.getC(), 0));
	ASSERT(equal(q.getD(), 0));
	// test float ctor
	q = Quaternion(0, 1, 0, 0);
	ASSERT(equal(q.getA(), 0));
	ASSERT(equal(q.getB(), 1));
	ASSERT(equal(q.getC(), 0));
	ASSERT(equal(q.getD(), 0));
	// test euler ctor
	q = Quaternion(EulerAngles(0, 0, 0));
	ASSERT(equal(q.getA(), 1));
	ASSERT(equal(q.getB(), 0));
	ASSERT(equal(q.getC(), 0));
	ASSERT(equal(q.getD(), 0));
	// test dcm ctor
	q = Quaternion(Dcm());
	ASSERT(equal(q.getA(), 1));
	ASSERT(equal(q.getB(), 0));
	ASSERT(equal(q.getC(), 0));
	ASSERT(equal(q.getD(), 0));
	// TODO test derivative
	// test accessors
	q.setA(0.1);
	q.setB(0.2);
	q.setC(0.3);
	q.setD(0.4);
	ASSERT(equal(q.getA(), 0.1));
	ASSERT(equal(q.getB(), 0.2));
	ASSERT(equal(q.getC(), 0.3));
	ASSERT(equal(q.getD(), 0.4));
	printf("PASS\n");
	return 0;
}
Example #7
0
 static constexpr auto equal_impl(M1 x, M2 y)
 { return equal(x.value, y.value); }
Example #8
0
bool operator == (const Point3D<T>& lhs, const Point3D<T>& rhs) {
	std::equal_to<T> equal;
	return equal(lhs.x, rhs.x) &&
	       equal(lhs.y, rhs.y) &&
	       equal(lhs.z, rhs.z);
}
Example #9
0
bool operator < (const Point2D<T>& lhs, const Point2D<T>& rhs) {
	std::less<T> less;
	std::equal_to<T> equal;
	return less(lhs.x, rhs.x) || equal(lhs.x, rhs.x) && less(lhs.y, rhs.y);
}
Example #10
0
/*
 * Return a pointer to a map projection structure given the arguments
 * below.  If this is a new projection we'll allocate a new projection
 * struct and return a pointer to it.  If this projection is already in
 * the list, just return a pointer to it.
 * Input:  kind - the type of projection, one of PROJ_*
 *         nr, nc - number of rows and columns of data
 *         args - array of projection parameters
 * Return:  pointer to a projection struct.
 */
struct projection *new_projection( struct grid_db *db, int kind,
                                   int nr, int nc, float *args )
{
   int p, i, nargs;

   /* determine how many arguments are in the args array */
   switch (kind) {
      case PROJ_GENERIC:  nargs = 4;        break;
      case PROJ_LINEAR:   nargs = 4;        break;
      case PROJ_LAMBERT:  nargs = 6;        break;
      case PROJ_STEREO:   nargs = 5;        break;
      case PROJ_ROTATED:  nargs = 7;        break;
      case PROJ_EPA:      nargs = nr*nc*2;  break;
      case PROJ_CYLINDRICAL: nargs = 4;     break;
      case PROJ_SPHERICAL:   nargs = 4;     break;
      case PROJ_MERCATOR: nargs = 4;        break;
      default:
         printf("Fatal error in new_projection!\n");
         exit(-1);
   }

   /* Search projection list for a possible match */
   for (p=0; p<db->NumProj; p++) {
      if (   db->ProjList[p]->Kind==kind
          && db->ProjList[p]->Nr==nr
          && db->ProjList[p]->Nc==nc) {
         int same = 1;
         for (i=0;i<nargs;i++) {
            if ( !equal(args[i], db->ProjList[p]->Args[i]) ) {
               same = 0;
               break;
            }
         }
         if (same) {
            return db->ProjList[p];
         }
      }
   }

   /* if we get here, the projection is not in the list, make a new one */
   if (db->NumProj<IMAXPROJ) {
      struct projection *newp;
/* 01Feb06  Phil McDonald */
      newp = (struct projection *) TMP_CALLOC (1, sizeof (struct projection));
/* end PM */
      newp->Kind = kind;
      newp->Nr = nr;
      newp->Nc = nc;
      newp->Args = (float *) MALLOC( nargs * sizeof(float) );
      for (i=0;i<nargs;i++) {
         newp->Args[i] = args[i];
      }
      /* compute extra, optional proj args */
      compute_aux_proj_args( newp );
      /* add to end of list */
      db->ProjList[db->NumProj] = newp;
      db->NumProj++;
      return newp;
   }
   else {
      printf("Error:  too many map projections, %d is limit\n", IMAXPROJ );
      return NULL;
   }
}
Example #11
0
STATIC union node *
command() {
      union node *n1, *n2;
      union node *ap, **app;
      union node *cp, **cpp;
      union node *redir, **rpp;
      int t;

      checkkwd();
      switch (readtoken()) {
      case TIF:
	    n1 = (union node *)stalloc(sizeof (struct nif));
	    n1->type = NIF;
	    n1->nif.test = list(0);
	    if (readtoken() != TTHEN)
		  synexpect(TTHEN);
	    n1->nif.ifpart = list(0);
	    n2 = n1;
	    while (readtoken() == TELIF) {
		  n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
		  n2 = n2->nif.elsepart;
		  n2->type = NIF;
		  n2->nif.test = list(0);
		  if (readtoken() != TTHEN)
			synexpect(TTHEN);
		  n2->nif.ifpart = list(0);
	    }
	    if (lasttoken == TELSE)
		  n2->nif.elsepart = list(0);
	    else {
		  n2->nif.elsepart = NULL;
		  tokpushback++;
	    }
	    if (readtoken() != TFI)
		  synexpect(TFI);
	    break;
      case TWHILE:
      case TUNTIL:
	    n1 = (union node *)stalloc(sizeof (struct nbinary));
	    n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
	    n1->nbinary.ch1 = list(0);
	    if (readtoken() != TDO)
		  synexpect(TDO);
	    n1->nbinary.ch2 = list(0);
	    if (readtoken() != TDONE)
		  synexpect(TDONE);
	    break;
      case TFOR:
	    if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
		  synerror("Bad for loop variable");
	    n1 = (union node *)stalloc(sizeof (struct nfor));
	    n1->type = NFOR;
	    n1->nfor.var = wordtext;
	    if (readtoken() == TWORD && ! quoteflag && equal(wordtext, "in")) {
		  app = &ap;
		  while (readtoken() == TWORD) {
			n2 = (union node *)stalloc(sizeof (struct narg));
			n2->type = NARG;
			n2->narg.text = wordtext;
			n2->narg.backquote = backquotelist;
			*app = n2;
			app = &n2->narg.next;
		  }
		  *app = NULL;
		  n1->nfor.args = ap;
	    } else {
#ifndef GDB_HACK
		  static const char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
						  '@', '=', '\0'};
#endif
		  n2 = (union node *)stalloc(sizeof (struct narg));
		  n2->type = NARG;
		  n2->narg.text = (char *)argvars;
		  n2->narg.backquote = NULL;
		  n2->narg.next = NULL;
		  n1->nfor.args = n2;
	    }
	    if (lasttoken != TNL && lasttoken != TSEMI)
		  synexpect(-1);
	    checkkwd();
	    if ((t = readtoken()) == TDO)
		  t = TDONE;
	    else if (t == TBEGIN)
		  t = TEND;
	    else
		  synexpect(-1);
	    n1->nfor.body = list(0);
	    if (readtoken() != t)
		  synexpect(t);
	    break;
      case TCASE:
	    n1 = (union node *)stalloc(sizeof (struct ncase));
	    n1->type = NCASE;
	    if (readtoken() != TWORD)
		  synexpect(TWORD);
	    n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
	    n2->type = NARG;
	    n2->narg.text = wordtext;
	    n2->narg.backquote = backquotelist;
	    n2->narg.next = NULL;
	    while (readtoken() == TNL);
	    if (lasttoken != TWORD || ! equal(wordtext, "in"))
		  synerror("expecting \"in\"");
	    cpp = &n1->ncase.cases;
	    while (checkkwd(), readtoken() == TWORD) {
		  *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
		  cp->type = NCLIST;
		  app = &cp->nclist.pattern;
		  for (;;) {
			*app = ap = (union node *)stalloc(sizeof (struct narg));
			ap->type = NARG;
			ap->narg.text = wordtext;
			ap->narg.backquote = backquotelist;
			if (readtoken() != TPIPE)
			      break;
			app = &ap->narg.next;
			if (readtoken() != TWORD)
			      synexpect(TWORD);
		  }
		  ap->narg.next = NULL;
		  if (lasttoken != TRP)
			synexpect(TRP);
		  cp->nclist.body = list(0);
		  if ((t = readtoken()) == TESAC)
			tokpushback++;
		  else if (t != TENDCASE)
			synexpect(TENDCASE);
		  cpp = &cp->nclist.next;
	    }
	    *cpp = NULL;
	    if (lasttoken != TESAC)
		  synexpect(TESAC);
	    break;
      case TLP:
	    n1 = (union node *)stalloc(sizeof (struct nredir));
	    n1->type = NSUBSHELL;
	    n1->nredir.n = list(0);
	    n1->nredir.redirect = NULL;
	    if (readtoken() != TRP)
		  synexpect(TRP);
	    break;
      case TBEGIN:
	    n1 = list(0);
	    if (readtoken() != TEND)
		  synexpect(TEND);
	    break;
      case TWORD:
      case TREDIR:
	    tokpushback++;
	    return simplecmd();
      default:
	    synexpect(-1);
      }

      /* Now check for redirection which may follow command */
      rpp = &redir;
      while (readtoken() == TREDIR) {
	    *rpp = n2 = redirnode;
	    rpp = &n2->nfile.next;
	    parsefname();
      }
      tokpushback++;
      *rpp = NULL;
      if (redir) {
	    if (n1->type != NSUBSHELL) {
		  n2 = (union node *)stalloc(sizeof (struct nredir));
		  n2->type = NREDIR;
		  n2->nredir.n = n1;
		  n1 = n2;
	    }
	    n1->nredir.redirect = redir;
      }
      return n1;
}
Example #12
0
template <typename P> bool   operator==(const P& p)    const { return equal(p, mpl::bool_<is_pixel<P>::value>()); } 
Example #13
0
	bool startsWith(const T &str, const T &prefix) {
		return equal(begin(prefix), end(prefix), begin(str));
	};
Example #14
0
 static bool unequal(value_type a, value_type b) { return !equal(a,b); }
Example #15
0
void Automate::standardisation(){

    /* Standardise l'automate en ajoutant l'etat 'i'
     * */

    list<list<string>*>::iterator iQ;

    // Insere l'etat i dans la liste des etats
    _Q.push_front(new list<string>);
    iQ = _Q.begin();
    (*iQ)->push_back("i");
    _tab[*iQ] = new list<list<string>*>[_A.size()];

    // Insere les transitions de l'etat 'i' (regroupant les transitions des etats initiaux)
    for(iQ=++_Q.begin(); iQ!=_Q.end(); iQ++){

        for(list<list<string>*>::iterator iI=_I.begin(); iI!=_I.end(); iI++){

            if(((*iQ)->size() == (*iI)->size())&&(equal((*iQ)->begin(), ((*iQ)->end()), (*iI)->begin()))){

                list<list<string>*>::iterator iiTab;

                for(unsigned int cpt=0; cpt<_A.size(); cpt++){
					for(list<list<string>*>::iterator iTab=_tab[*iQ][cpt].begin(); iTab!=_tab[*iQ][cpt].end(); iTab++){
						_tab[*_Q.begin()][cpt].push_back(new list<string>);
                        iiTab =-- _tab[*_Q.begin()][cpt].end();
                        (*iiTab)->insert((*iiTab)->begin(),(*iTab)->begin(),(*iTab)->end());
					}
                }
            }
        }
    }

    // Tri les transitions de l'etat 'i'
    iQ = _Q.begin();
    for(unsigned int cpt=0; cpt<_A.size(); cpt++){
		for(list<list<string>*>::iterator iTab=_tab[*iQ][cpt].begin(); iTab!=_tab[*iQ][cpt].end(); iTab++){

			(*iTab)->sort();
			(*iTab)->unique();
		}
    }
\
    // Si un des etats initiaux est terminal
    int temp = 0;
    list<list<string>*>::iterator iI;
    list<list<string>*>::iterator iT;

    iI=_I.begin();
    while ((iI != _I.end())&&(temp == 0)){

        iT=_T.begin();
        while ((iT != _T.end())&&(temp == 0)){

            if (((*iI)->size() == (*iT)->size())&&(equal((*iI)->begin(),(*iI)->end(),(*iT)->begin())))
                temp = 1;
            iT++;
        }
        iI++;
    }

    // Insere 'i' dans les etats terminaux
    if (temp == 1){

        _T.push_front(new list<string>);
        (*_T.begin())->push_back("i");
    }

    // Remplace les etats initiaux par 'i'
    deleteI();
    _I.push_front(new list<string>);
    (*_I.begin())->push_back("i");
}
Example #16
0
 // equality and relational operators
 bool operator == ( const Ptr < T > & p ) const
 { return equal ( p ); }
Example #17
0
int main(int argc, char *argv[])
{
    /*
                [ Executable file format ]

    +-------------------------------------------------+ <-+
    | Bss size in bytes (4 bytes)                     |   |
    +-------------------------------------------------+   |
    | Data size in bytes (4 bytes)                    |   |
    +-------------------------------------------------+   |
    | Text size in bytes (4 bytes)                    |   |-> Header
    +-------------------------------------------------+   |
    | Number of entries in data relocation table      |   |
    +-------------------------------------------------+   |
    | Number of entries in text relocation table      |   |
    +-------------------------------------------------+ <-+
    | Data                                            |
    +-------------------------------------------------+
    | Text                                            |
    +-------------------------------------------------+
    | Data relocation table                           |
    +-------------------------------------------------+
    | Text relocation table                           |
    +-------------------------------------------------+


    Each entry of the relocation tables:
        - offset: the offset from the start of the segment (data or text) where the fix
        must be made.
        - segment: indicates if the runtime start address of the bss, data, or text segment
        must be added to do the fix.
    */

    int i;
    FILE *fout;
    char *outpath;
    char *infiles[64];
    int ninf;
    int print_stats;

    prog_name = argv[0];
    if (argc == 1)
        err_no_input();
    ninf = 0;
    print_stats = FALSE;
    outpath = "a.out.vme";
    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            infiles[ninf++] = argv[i];
            continue;
        }
        switch (argv[i][1]) {
        case 'o':
            if (argv[i][2] != '\0') {
                outpath = argv[i]+2;
            } else if (argv[i+1] == NULL) {
                fprintf(stderr, "%s: option `o' requires an argument\n", prog_name);
                exit(1);
            } else {
                outpath = argv[++i];
            }
            break;
        case 's':
            print_stats = TRUE;
            break;
        case 'v':
            if (equal(argv[i]+1, "vm64"))
                targeting_vm64 = TRUE;
            else if (equal(argv[i]+1, "vm32"))
                ;
            else
                unk_opt(argv[i]);
            break;
        case 'h':
            printf("usage: %s [ options ] <input-file> ...\n"
                   "  The available options are:\n"
                   "    -o<file>    write output to <file>\n"
                   "    -s          print linking stats\n"
                   "    -vm32       output a 32-bit executable (default)\n"
                   "    -vm64       output a 64-bit executable\n"
                   "    -h          print this help\n", prog_name);
            exit(0);
            break;
        case '\0':
            break;
        default:
            unk_opt(argv[i]);
            break;
        }
    }
    if (ninf == 0)
        err_no_input();

    init_local_table();
    text_max = 65536;
    text_seg = malloc(text_max);
    data_max = 65536;
    data_seg = malloc(data_max);
    dreloc_max = 8192;
    data_relocation_table = malloc(sizeof(Reloc)*dreloc_max);
    treloc_max = 8192;
    text_relocation_table = malloc(sizeof(Reloc)*treloc_max);

    /*
     * crt.o must be the first file (crt.o's code must be physically at the
     * beginning of the resulting executable). An alternative would be to label
     * crt.o's code as, say, `_start:' and emit an "jmp _start;" before the
     * program's code.
     * crt.o has code to initialize some variables and call main.
     */
    for (i = 0; i < ninf; i++) {
        FILE *fin;
        char name[MAX_SYM_LEN], *cp;
        int j;
        int nsym;
        int curr_bss_size;
        int curr_text_size;
        int curr_data_size;
        int curr_nreloc;
        int segment, offset, kind;

        if ((fin=fopen(infiles[i], "rb")) == NULL)
            TERMINATE("%s: error reading file `%s'", prog_name, infiles[i]);

        /* header */
        fread(&nsym, sizeof(int), 1, fin);
        fread(&curr_bss_size, sizeof(int), 1, fin);
        fread(&curr_data_size, sizeof(int), 1, fin);
        fread(&curr_text_size, sizeof(int), 1, fin);
        fread(&curr_nreloc, sizeof(int), 1, fin);

        /* symbol table entries */
        for (j = 0; j < nsym; j++) {
            for (cp = name; ; cp++) {
                if ((*cp=(char)fgetc(fin)) == '\0')
                    break;
            }
            fread(&segment, sizeof(int), 1, fin);
            fread(&offset, sizeof(int), 1, fin);
            fread(&kind, sizeof(int), 1, fin);
            if (kind == LOCAL_SYM)
                define_local_symbol(name, segment, SEG_SIZ(segment)+offset);
            else
                define_symbol(name, kind, segment, SEG_SIZ(segment)+offset);
            // if (segment == TEXT_SEG)
				// printf("%s, %d\n", name, SEG_SIZ(segment)+offset);
        }

        /* data&text */
        if (data_size+curr_data_size > data_max) {
            char *p;

            data_max = data_max*2+curr_data_size;
            if ((p=realloc(data_seg, data_max)) == NULL)
                TERMINATE("out of memory");
            data_seg = p;
        }
        fread(data_seg+data_size, curr_data_size, 1, fin);
        if (text_size+curr_text_size > text_max) {
            char *p;

            text_max = text_max*2+curr_text_size;
            if ((p=realloc(text_seg, text_max)) == NULL)
                TERMINATE("out of memory");
            text_seg = p;
        }
        fread(text_seg+text_size, curr_text_size, 1, fin);

        /* relocation table entries */
        for (j = 0; j < curr_nreloc; j++) {
            Symbol *s;

            fread(&segment, sizeof(int), 1, fin);
            fread(&offset, sizeof(int), 1, fin);
            for (cp = name; ; cp++) {
                if ((*cp=(char)fgetc(fin)) == '\0')
                    break;
            }
            s = lookup_symbol(name);
            if (s->kind != EXTERN_SYM) {
                if (segment == TEXT_SEG) {
                    if (targeting_vm64)
                        *(long long *)&text_seg[SEG_SIZ(segment)+offset] += s->offset;
                    else
                        *(int *)&text_seg[SEG_SIZ(segment)+offset] += s->offset;
                    append_text_reloc(s->segment, SEG_SIZ(segment)+offset, NULL);
                } else {
                    if (targeting_vm64)
                        *(long long *)&data_seg[SEG_SIZ(segment)+offset] += s->offset;
                    else
                        *(int *)&data_seg[SEG_SIZ(segment)+offset] += s->offset;
                    append_data_reloc(s->segment, SEG_SIZ(segment)+offset, NULL);
                }
            } else {
                /*
                 * The file that contains the symbol definition
                 * has not been seen yet. Mark it to fix later.
                 */
                if (segment == TEXT_SEG)
                    append_text_reloc(0, SEG_SIZ(segment)+offset, strdup(name));
                else
                    append_data_reloc(0, SEG_SIZ(segment)+offset, strdup(name));
            }
        }

        if (targeting_vm64) {
            bss_size  += round_up(curr_bss_size,  MAX_ALIGN64);
            data_size += round_up(curr_data_size, MAX_ALIGN64);
            text_size += round_up(curr_text_size, MAX_ALIGN64);
        } else {
            bss_size  += round_up(curr_bss_size,  MAX_ALIGN32);
            data_size += round_up(curr_data_size, MAX_ALIGN32);
            text_size += round_up(curr_text_size, MAX_ALIGN32);
        }
        reset_local_table();
        fclose(fin);
    }

    /*
     * Try to fix the relocs that couldn't be fixed before
     * because they depended on not-yet-defined extern symbols.
     * Fail if a symbol is still undefined.
     */
    for (i = 0; i < ntreloc; i++) {
        if (text_relocation_table[i].symbol != NULL) {
            Symbol *s;

            if ((s=lookup_global_symbol(text_relocation_table[i].symbol))->kind == EXTERN_SYM)
                TERMINATE("%s: undefined reference to `%s'", prog_name, s->name);
            if (targeting_vm64)
                *(long long *)&text_seg[text_relocation_table[i].offset] += s->offset;
            else
                *(int *)&text_seg[text_relocation_table[i].offset] += s->offset;
            text_relocation_table[i].segment = s->segment;
        }
    }
    for (i = 0; i < ndreloc; i++) {
        if (data_relocation_table[i].symbol != NULL) {
            Symbol *s;

            if ((s=lookup_global_symbol(data_relocation_table[i].symbol))->kind == EXTERN_SYM)
                TERMINATE("%s: undefined reference to `%s'", prog_name, s->name);
            if (targeting_vm64)
                *(long long *)&data_seg[data_relocation_table[i].offset] += s->offset;
            else
                *(int *)&data_seg[data_relocation_table[i].offset] += s->offset;
            data_relocation_table[i].segment = s->segment;
        }
    }

    /* Write the final executable file. */
    fout = fopen(outpath, "wb");
    /* header */
    fwrite(&bss_size, sizeof(int), 1, fout);
    fwrite(&data_size, sizeof(int), 1, fout);
    fwrite(&text_size, sizeof(int), 1, fout);
    fwrite(&ndreloc, sizeof(int), 1, fout);
    fwrite(&ntreloc, sizeof(int), 1, fout);
    /* data&text */
    fwrite(data_seg, data_size, 1, fout);
    fwrite(text_seg, text_size, 1, fout);
    /* data relocation table */
    for (i = 0; i < ndreloc; i++) {
        fwrite(&data_relocation_table[i].segment, sizeof(int), 1, fout);
        fwrite(&data_relocation_table[i].offset, sizeof(int), 1, fout);
    }
    /* text relocation table */
    for (i = 0; i < ntreloc; i++) {
        fwrite(&text_relocation_table[i].segment, sizeof(int), 1, fout);
        fwrite(&text_relocation_table[i].offset, sizeof(int), 1, fout);
    }
    fclose(fout);

    if (print_stats) {
        printf("Text size: %d\n", text_size);
        printf("Data size: %d\n", data_size);
        printf("Bss size: %d\n", bss_size);
        printf("Number of text relocations: %d\n", ntreloc);
        printf("Number of data relocations: %d\n", ndreloc);
    }

    free(data_seg);
    free(text_seg);
    free(data_relocation_table);
    free(text_relocation_table);

    return 0;
}
Example #18
0
 bool operator != ( const Ptr < T > & p ) const
 { return ! equal ( p ); }
Example #19
0
 /**
 * \brief Equal to operator.
 */
 FRAMEWORK_ALWAYS_INLINE
 friend bool operator== (Parent const& lhs, Parent const& rhs)
 {
     return equal(lhs, rhs);
 }
Example #20
0
int
main(int argc, char *argv[])
{
	char *sys = NOSTR, sbuf[12], *p;
	int i;

	/* XXX preserve previous braindamaged behavior */
	setboolean(value(DC), TRUE);

	gid = getgid();
	egid = getegid();
	uid = getuid();
	euid = geteuid();
	if (equal(__progname, "cu")) {
		cumode = 1;
		cumain(argc, argv);
		goto cucommon;
	}

	if (argc > 4) {
		fprintf(stderr, "usage: tip [-v] [-speed] [system-name]\n");
		exit(1);
	}
	if (!isatty(0)) {
		fprintf(stderr, "%s: must be interactive\n", __progname);
		exit(1);
	}

	for (; argc > 1; argv++, argc--) {
		if (argv[1][0] != '-')
			sys = argv[1];
		else switch (argv[1][1]) {

		case 'v':
			vflag++;
			break;

		case 'n':
			noesc++;
			break;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			BR = atoi(&argv[1][1]);
			break;

		default:
			fprintf(stderr, "%s: %s, unknown option\n", __progname,
			    argv[1]);
			break;
		}
	}

	if (sys == NOSTR)
		goto notnumber;
	if (isalpha(*sys))
		goto notnumber;
	/*
	 * System name is really a phone number...
	 * Copy the number then stomp on the original (in case the number
	 *	is private, we don't want 'ps' or 'w' to find it).
	 */
	if (strlen(sys) > sizeof PNbuf - 1) {
		fprintf(stderr, "%s: phone number too long (max = %d bytes)\n",
			__progname, (int)sizeof(PNbuf) - 1);
		exit(1);
	}
	strlcpy(PNbuf, sys, sizeof PNbuf - 1);
	for (p = sys; *p; p++)
		*p = '\0';
	PN = PNbuf;
	(void)snprintf(sbuf, sizeof(sbuf), "tip%ld", BR);
	sys = sbuf;

notnumber:
	(void)signal(SIGINT, cleanup);
	(void)signal(SIGQUIT, cleanup);
	(void)signal(SIGHUP, cleanup);
	(void)signal(SIGTERM, cleanup);
	(void)signal(SIGCHLD, SIG_DFL);

	if ((i = hunt(sys)) == 0) {
		printf("all ports busy\n");
		exit(3);
	}
	if (i == -1) {
		printf("link down\n");
		(void)uu_unlock(uucplock);
		exit(3);
	}
	setbuf(stdout, NULL);
	loginit();

	/*
	 * Now that we have the logfile and the ACU open
	 *  return to the real uid and gid.  These things will
	 *  be closed on exit.  Swap real and effective uid's
	 *  so we can get the original permissions back
	 *  for removing the uucp lock.
	 */
	user_uid();

	/*
	 * Kludge, their's no easy way to get the initialization
	 *   in the right order, so force it here
	 */
	if ((PH = getenv("PHONES")) == NOSTR)
		PH = _PATH_PHONES;
	vinit();				/* init variables */
	setparity("none");			/* set the parity table */

	/*
	 * Hardwired connections require the
	 *  line speed set before they make any transmissions
	 *  (this is particularly true of things like a DF03-AC)
	 */
	if (HW && ttysetup(number(value(BAUDRATE)))) {
		fprintf(stderr, "%s: bad baud rate %ld\n", __progname,
		    number(value(BAUDRATE)));
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(3);
	}
	if ((p = con())) {
		printf("\07%s\n[EOT]\n", p);
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(1);
	}
	if (!HW && ttysetup(number(value(BAUDRATE)))) {
		fprintf(stderr, "%s: bad baud rate %ld\n", __progname,
		    number(value(BAUDRATE)));
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(3);
	}
cucommon:
	/*
	 * From here down the code is shared with
	 * the "cu" version of tip.
	 */

	i = fcntl(FD, F_GETFL);
	if (i == -1) {
		perror("fcntl");
		cleanup(0);
	}
	i = fcntl(FD, F_SETFL, i & ~O_NONBLOCK);
	if (i == -1) {
		perror("fcntl");
		cleanup(0);
	}

	tcgetattr(0, &defterm);
	gotdefterm = 1;
	term = defterm;
	term.c_lflag &= ~(ICANON|IEXTEN|ECHO);
	term.c_iflag &= ~(INPCK|ICRNL);
	term.c_oflag &= ~OPOST;
	term.c_cc[VMIN] = 1;
	term.c_cc[VTIME] = 0;
	defchars = term;
	term.c_cc[VINTR] = term.c_cc[VQUIT] = term.c_cc[VSUSP] =
	    term.c_cc[VDSUSP] = term.c_cc[VDISCARD] =
	    term.c_cc[VLNEXT] = _POSIX_VDISABLE;
	raw();

	pipe(fildes); pipe(repdes);
	(void)signal(SIGALRM, timeout);

	if (value(LINEDISC) != TTYDISC) {
		int ld = (int)(intptr_t)value(LINEDISC);
		ioctl(FD, TIOCSETD, &ld);
	}		

	/*
	 * Everything's set up now:
	 *	connection established (hardwired or dialup)
	 *	line conditioned (baud rate, mode, etc.)
	 *	internal data structures (variables)
	 * so, fork one process for local side and one for remote.
	 */
	printf(cumode ? "Connected\r\n" : "\07connected\r\n");
	tipin_pid = getpid();
	if ((tipout_pid = fork()))
		tipin();
	else
		tipout();
	/*NOTREACHED*/
	exit(0);
}
Example #21
0
struct p_node *find_patient(struct p_node *list, char *const name) {
	struct p_node *it = list;
	while (it != NULL && !equal(it->name, name, MAX_STR_LEN))
		it = it->next;
	return it;
}
Example #22
0
    static int lineSegmentPolyIntersections(const P2Vector &points,
                                            LineSegment2 line,
                                            std::vector<PolyIntersectionInfo> &out) {
      int count = 0;

      if (line.v2 < line.v1) { line.flip(); }
      out.clear();

      for (P2Vector::size_type i = 0, l = points.size(); i < l; i++) {
        P2Vector::size_type j = (i + 1) % l;
        LineIntersectionInfo e =
          lineSegmentIntersection(LineSegment2(points[i], points[j]), line);
    
        switch (e.iclass) {
        case INTERSECTION_PL: {
          out.push_back(PolyIntersectionInfo(INTERSECT_EDGE, e.ipoint, i));
          count++;
          break;
        }
        case INTERSECTION_PP: {
          out.push_back(PolyIntersectionInfo(INTERSECT_VERTEX, e.ipoint, i + (size_t)e.p2 - 2));
          count++;
          break;
        }
        case INTERSECTION_LP: {
          out.push_back(PolyIntersectionInfo(INTERSECT_VERTEX, e.ipoint, i + (size_t)e.p2 - 2));
          count++;
          break;
        }
        case INTERSECTION_LL: {
          out.push_back(PolyIntersectionInfo(INTERSECT_EDGE, e.ipoint, i));
          count++;
          break;
        }
        case COLINEAR: {
          size_t n1 = i;
          size_t n2 = j;

          P2 q1 = points[i], q2 = points[j];

          if (q2 < q1) { std::swap(q1, q2); std::swap(n1, n2); }

          if (equal(q1, line.v1)) {
            out.push_back(PolyIntersectionInfo(INTERSECT_VERTEX, q1, n1));
          } else if (q1.x < line.v1.x) {
            out.push_back(PolyIntersectionInfo(INTERSECT_EDGE, line.v1, i));
          } else {
            out.push_back(PolyIntersectionInfo(INTERSECT_VERTEX, q1, n1));
          }
          if (equal(q2, line.v2)) {
            out.push_back(PolyIntersectionInfo(INTERSECT_VERTEX, q2, n2));
          } else if (line.v2.x < q2.x) {
            out.push_back(PolyIntersectionInfo(INTERSECT_EDGE, line.v2, i));
          } else {
            out.push_back(PolyIntersectionInfo(INTERSECT_VERTEX, q2, n2));
          }

          count += 2;

          break;
        }
        default:
          break;
        }
      }
      return count;
    }
Example #23
0
 static constexpr auto equal_impl(X x, Y y)
 { return equal(eval(x), eval(y)); }
Example #24
0
void Automate::determinisation(){

    /* Determinise l'automate
     * */

    list<list<string>*> Qdet;
    list<list<string>*> Tdet;

    // Creation de l'etat initial (= premier etat de la liste des etats)
    Qdet.push_back(new list<string>);
    list<list<string>*>::iterator iQdet = Qdet.begin();
    _tab[*iQdet] = new list<list<string>*>[_A.size()];

    for(list<list<string>*>::iterator iI=_I.begin(); iI!=_I.end(); iI++)
        (*iQdet)->insert((*iQdet)->begin(),(*iI)->begin(),(*iI)->end());


    (*iQdet)->sort();
    (*iQdet)->unique();

    // Remplace les etats initiaux pour le nouvel etat initial
    _I.clear();
    _I.push_back(new list<string>);
    (*_I.begin())->assign((*iQdet)->begin(),(*iQdet)->end());

    // Creer la nouvelle table de transition et la nouvelle liste des etats
    list<list<string>*>::iterator iQ;
    list<string>::iterator iiQdet;
    unsigned int cpt;

    // Tant qu'il y a des etats dans la nouvelle liste des etats
    while(iQdet != Qdet.end()){

        for(cpt=0; cpt<_A.size(); cpt++){
            _tab[*iQdet][cpt].push_back(new list<string>);
        }

        // Creation des nouvelles transitions pour l'etat concerne
        for(iQ=_Q.begin(); iQ!=_Q.end(); iQ++){
            for(iiQdet=(*iQdet)->begin(); iiQdet!=(*iQdet)->end(); iiQdet++){

                if (find((*iQ)->begin(),(*iQ)->end(),*iiQdet) != (*iQ)->end()){

                    for(cpt=0; cpt<_A.size(); cpt++){

                        list<list<string>*>::iterator iiTab;

                        iiTab = _tab[*iQdet][cpt].begin();
                        for(list<list<string>*>::iterator iTab=_tab[*iQ][cpt].begin(); iTab!=_tab[*iQ][cpt].end(); iTab++)
                            (*iiTab)->insert(--(*iiTab)->end(),(*iTab)->begin(),(*iTab)->end());
                    }
                }
            }
        }

        int temp;
        list<list<string>*>::iterator iTab;

        // Tri des nouvelles transitions pour l'etat concerne, et creation d'un nouvel etat a partir des nouvelles transition (s'il n'existait pas deja)
        for(cpt=0; cpt<_A.size(); cpt++){

            iTab=_tab[*iQdet][cpt].begin();
            while((!_tab[*iQdet][cpt].empty())&&(iTab!=_tab[*iQdet][cpt].end())){

                if((*iTab)->empty()){
                    _tab[*iQdet][cpt].erase(iTab);
                    iTab--;
                }
                else{
                    (*iTab)->sort();
                    (*iTab)->unique();
                }

                iTab++;
            }

            temp = 0;
            iTab = _tab[*iQdet][cpt].begin();

            // Creation d'un nouvel etat (s'il n'existait pas deja)
            for(iQ=Qdet.begin(); iQ!=Qdet.end(); iQ++){

                if((_tab[*iQdet][cpt].empty())||(((*iTab)->size() == (*iQ)->size())&&(equal((*iTab)->begin(),(*iTab)->end(),(*iQ)->begin()))))
                    temp = 1;
            }
            if (temp == 0){

                Qdet.push_back(new list<string>);
                _tab[*(--Qdet.end())] = new list<list<string>*>[_A.size()];
                (*(--Qdet.end()))->assign((*iTab)->begin(),(*iTab)->end());
            }
        }

        iQdet++;
    }

    // Suppression de l'ancienne table de transition
    deleteTableTranstion();

    // Remplace l'ancienne liste des etats par la nouvelle
    deleteQ();
    _Q = Qdet;

    // Creation de la nouvelle liste des etats teminaux (tout etat contenant un ancien etat terminal est terminal)
    for(list<list<string>*>::iterator iT=_T.begin(); iT!=_T.end(); iT++){
        for(iQ=_Q.begin(); iQ!=_Q.end(); iQ++){

            if(search((*iQ)->begin(),(*iQ)->end(),(*iT)->begin(),(*iT)->end()) != (*iQ)->end()){

                int temp = 0;
                list<list<string>*>::iterator iTdet;

                iTdet = Tdet.begin();
                while ((iTdet != Tdet.end())&&(temp == 0)){

                    if (((*iQ)->size() == (*iTdet)->size())&&(equal((*iQ)->begin(),(*iQ)->end(),(*iTdet)->begin())))
                        temp = 1;
                    iTdet++;
                }

                if (temp == 0){
                    Tdet.push_back(new list<string>);
                    (*(--Tdet.end()))->assign((*iQ)->begin(),(*iQ)->end());
                }
            }
        }
    }

    // Remplace l'ancienne liste des etats terminaux par la nouvelle
    deleteT();
    _T = Tdet;

}
Example #25
0
bool WebString::equals(const WebString& s) const
{
    return equal(m_private, s.m_private);
}
Example #26
0
bool Automate::minimiser(){

    /* Minimise l'automate
     * Retourne true si l'automate etait deja minimal <=> Le nombre de groupe cree lors de la minimisation est egal au nombre d'etat de l'automate
     * Retourne false si l'automate n'etait pas minimal
     * */

    list<string> groupes; // La liste des groupes Ex : {NT, T}
    list<string> tempgroupes; // Une liste des groupes temporaires
    string  groupeString; // Le groupe auquel appartient un etat
    map<string, list<list<string>*>*> tabG; // Un tableau indexe par les groupes contenant la liste des etats dans un groupe

    //Initialisation de tempGroupes et de tabG
    tempgroupes.push_back("NT");
    tempgroupes.push_back("T");

    tabG["NT"] = new list<list<string>*>;
    tabG["T"] = new list<list<string>*>;

    for(list<list<string>*>::iterator iQ=_T.begin(); iQ!=_T.end(); iQ++)
        tabG["T"]->push_back(*iQ);

    for(list<list<string>*>::iterator iQ=_Q.begin(); iQ!=_Q.end(); iQ++){

        int temp = 0;

        for(list<list<string>*>::iterator iT=_T.begin(); iT!=_T.end(); iT++){

             if( ((*iT)->size() == (*iQ)->size()) && (equal(  (*iQ)->begin(), (*iQ)->end(), (*iT)->begin())  )){
                 temp = 1;
             }
        }

        if(temp == 0)
           tabG["NT"]->push_back(*iQ);
    }

    list<string>::iterator iG;
    QStringList liste;
    QString tempS;
    int cptG;

    // Tant que le nombre de groupe n'est pas egal a celui de la derniere iteration
    while (groupes.size() != tempgroupes.size()) {

        // Initialisation de groupes et reinitialisation de tempgroupes
        groupes = tempgroupes;
        tempgroupes.clear();

        cptG = 1;

        for(list<string>::iterator i = groupes.begin(); i != groupes.end(); i++){

            tempS.clear();

            tempS += "Group " + QString::number(cptG) + " : ";
            for(list<list<string>*>::iterator ii = tabG[*i]->begin(); ii != tabG[*i]->end(); ii++){

                if (ii != tabG[*i]->begin())
                    tempS += ", ";

                tempS += "{";

                for(list<string>::iterator iii = (*ii)->begin(); iii != (*ii)->end(); iii++){

                    if(iii != (*ii)->begin())
                        tempS += ", ";

                    tempS += QString::fromStdString(*iii);
                }

                tempS += "}";
            }

            liste << tempS;
            cptG++;
        }

        liste << "";


        // Pour chaque etat
        for(list<list<string>*>::iterator iQ=_Q.begin(); iQ!=_Q.end(); iQ++){

            // Reinitialisation de groupeString
            groupeString.clear();

            iG = groupes.begin();

            int temp;

            // Faire tant que nous ne trouvons pas dans quel groupe est cet etat
            temp = 1;
            do {

                for(list<list<string>*>::iterator iiG = tabG[*iG]->begin(); iiG != tabG[*iG]->end(); iiG++){

                    // Si les etats sont egaux
                    if (((*iiG)->size() == (*iQ)->size())&&(equal((*iiG)->begin(), (*iiG)->end(), (*iQ)->begin())))
                        temp = 0;
                }

                iG++;

            }while(temp == 1);

            iG--;

            // Insertion de ce groupe dans groupeString
            groupeString = groupeString + *iG;

            for (unsigned int cpt = 0; cpt != _A.size(); cpt++){

                int temp;
                iG = groupes.begin();

                temp = 1;
                 do{

                     list<list<string>*>::iterator iTab = _tab[*iQ][cpt].begin();

                     for(list<list<string>*>::iterator iiG = tabG[*iG]->begin(); iiG != tabG[*iG]->end(); iiG++){

                         if (((*iiG)->size() == (*iTab)->size())&&(equal((*iiG)->begin(), (*iiG)->end(), (*iTab)->begin()))) // Si les etats ne sont pas egaux
                             temp = 0;
                     }

                     iG++;

                 }while(temp == 1);

                 iG--;

                 // Insertion de ce groupe dans groupeString
                 groupeString = groupeString + *iG;
             }

             if(tabG[groupeString] == NULL){
                 tabG[groupeString] = new list<list<string>*>;
             }

             // Insertion de cet etat dans son groupe
             tabG[groupeString]->push_back(*iQ);

             tempgroupes.push_back(groupeString);

             tempgroupes.sort();
             tempgroupes.unique();
        }

        // Suppression des anciens groupes
        for (list<string>::iterator it=groupes.begin(); it != groupes.end(); it++)
            tabG[*it]->clear();
    }

    Interface::messageMinimiser(&liste);

    groupes = tempgroupes;
    tempgroupes.clear();

    if(groupes.size() == _Q.size())
        return true;

    list<list<string>*> Qmin, Tmin, Imin;

    list<string>::iterator iGG;
    list<list<string>*>::iterator iTabG;
    list<list<string>*>::iterator iTab;

    int temp;

    list<list<string>*>::iterator iI;
    list<list<string>*>::iterator iIm;

    iI = _I.begin();
    iG=groupes.begin();
    temp = 1;
    do {

        for(list<list<string>*>::iterator iiG = tabG[*iG]->begin(); iiG != tabG[*iG]->end(); iiG++){

            if (((*iiG)->size() == (*iI)->size())&&(equal((*iiG)->begin(), (*iiG)->end(), (*iI)->begin()))) // Si les etats ne sont pas egaux
                temp = 0;
        }

        iG++;

    }while(temp == 1);

    iG--;

    Imin.push_back(new list<string>);
    iIm =-- Imin.end();

    for(list<list<string>*>::iterator iTabGG = tabG[*iG]->begin(); iTabGG != tabG[*iG]->end(); iTabGG++)
        (*iIm)->insert(--(*iIm)->end(), (*iTabGG)->begin(), (*iTabGG)->end());

    deleteI();
    _I = Imin;

    list<list<string>*>::iterator iTmin;

    for(list<string>::iterator iG = groupes.begin(); iG != groupes.end(); iG++){

        if ((*iG).at(0) == 'T'){

            Tmin.push_back(new list<string>);
            iTmin =-- Tmin.end();

            for(list<list<string>*>::iterator iTabG = tabG[*iG]->begin(); iTabG != tabG[*iG]->end(); iTabG++){

                (*iTmin)->insert(--(*iTmin)->end(), (*iTabG)->begin(), (*iTabG)->end());
            }
        }
    }

    deleteT();
    _T = Tmin;

    list<list<string>*>::iterator iQmin;
    list<list<string>*>::iterator iTabmin;

    for(list<string>::iterator iG=groupes.begin(); iG != groupes.end(); iG++){

        // Creation des états
        Qmin.push_back(new list<string>);
        iQmin = --Qmin.end();

        for(iTabG = tabG[*iG]->begin(); iTabG != tabG[*iG]->end(); iTabG++){

            (*iQmin)->insert(--(*iQmin)->end(), (*iTabG)->begin(), (*iTabG)->end());
        }

        // Creation des transitions associes a chaque etat
        _tab[*(--Qmin.end())] = new list<list<string>*>[_A.size()];

        // Pour chaque transition
        for(unsigned int cpt = 0; cpt < _A.size(); cpt++){

            // Pour un etat dans le groupe
            iTabG = tabG[*iG]->begin();

            // Pour une transition de de cet etat dans le groupe
            iTab = _tab[*iTabG][cpt].begin();

            int temp;
            iGG = groupes.begin();

            temp = 1;

            // Faire tant que nous ne trouvons pas dans quel groupe est cet etat
            do {

                for(list<list<string>*>::iterator iiG = tabG[*iGG]->begin(); iiG != tabG[*iGG]->end(); iiG++){

                    if (((*iiG)->size() == (*iTab)->size())&&(equal((*iiG)->begin(), (*iiG)->end(), (*iTab)->begin())))
                        temp = 0;
                    }

                    iGG++;

            }while(temp == 1);

            iGG--;

            _tab[*(--Qmin.end())][cpt].push_back(new list<string>);

            iTabmin =-- _tab[*(--Qmin.end())][cpt].end();

            for(list<list<string>*>::iterator iTabGG = tabG[*iGG]->begin(); iTabGG != tabG[*iGG]->end(); iTabGG++)
                (*iTabmin)->insert(--(*iTabmin)->end(), (*iTabGG)->begin(), (*iTabGG)->end());
        }
    }

    deleteQ();
    _Q = Qmin;

    return false;
}
bool LibraryItem::operator!=(const LibraryItem& item) 
{
    return !equal(item);
}
Example #28
0
int Automate::lecture(const string& mot){

    /* Retourne 1 si le mot n'est pas reconnu par l'automate <=> Le caractere lu n'appartient pas a l'alphabet
     * Retourne 2 si le mot n'est pas reconnu par l'automate <=> L'etat sur lequel nous arrivons en lisant le mot n'est pas terminal
     * Retourne r < 0 si le mot n'est pas reconnu par l'automate <=> Il n'existe pas de transition dans cet etat pour le caractere
     * Retourne 0 si le mot est reconnu par l'automate
     * */

    list<string>* etatCourant = NULL;

    list<list<string>*>::iterator iI;
    list<list<string>*>::iterator iQ;

    iI=_I.begin();
    iQ=_Q.begin();

    while ((iQ != _Q.end())&&(etatCourant == NULL)){

        if (((*iQ)->size() == (*iI)->size())&&(equal((*iQ)->begin(),(*iQ)->end(),(*iI)->begin())))
            etatCourant = *iQ;
        iQ++;
    }

    int cpt;
    list<string>::iterator iA;
    list<string>* etatCourantTemp;

    cpt = 0;
    while (mot[cpt] != 0){

        iA = find(_A.begin(),_A.end(),mot.substr(cpt,1));

        if (iA == _A.end())
            return 1;

        if (_tab[etatCourant][distance(_A.begin(),iA)].empty())
            return (-cpt)-1;
        etatCourant = *_tab[etatCourant][distance(_A.begin(),iA)].begin();

        iQ=_Q.begin();
        etatCourantTemp = etatCourant;

        while ((iQ != _Q.end())&&(etatCourant == etatCourantTemp)){

            if (((*iQ)->size() == etatCourant->size())&&(equal((*iQ)->begin(),(*iQ)->end(),etatCourant->begin())))
                etatCourant = *iQ;
            iQ++;
        }

        cpt++;
    }

    int temp;
    list<list<string>*>::iterator iT;

    temp = 0;
    iT=_T.begin();
    while ((iT != _T.end())&&(temp == 0)){

        if (((*iT)->size() == etatCourant->size())&&(equal((*iT)->begin(),(*iT)->end(),etatCourant->begin())))
            temp = 1;
        iT++;
    }

    if (temp == 0)
        return 2;

    return 0;
}
Example #29
0
int
main(int argc, char *argv[])
{
	char *system = NULL;
	int i;
	char *p;
	char sbuf[12];

	gid = getgid();
	egid = getegid();
	uid = getuid();
	euid = geteuid();

#if INCLUDE_CU_INTERFACE
	if (equal(sname(argv[0]), "cu")) {
		cumode = 1;
		cumain(argc, argv);
		goto cucommon;
	}
#endif /* INCLUDE_CU_INTERFACE */

	if (argc > 4)
		usage();
	if (!isatty(0))
		errx(1, "must be interactive");

	for (; argc > 1; argv++, argc--) {
		if (argv[1][0] != '-')
			system = argv[1];
		else switch (argv[1][1]) {

		case 'v':
			vflag++;
			break;

		case '0': case '1': case '2': case '3': case '4':
		case '5': case '6': case '7': case '8': case '9':
			BR = atoi(&argv[1][1]);
			break;

		default:
			warnx("%s, unknown option", argv[1]);
			break;
		}
	}

	if (system == NULL)
		goto notnumber;
	if (isalpha(*system))
		goto notnumber;
	/*
	 * System name is really a phone number...
	 * Copy the number then stomp on the original (in case the number
	 *	is private, we don't want 'ps' or 'w' to find it).
	 */
	if (strlen(system) > sizeof(PNbuf) - 1)
		errx(1, "phone number too long (max = %zd bytes)", sizeof PNbuf - 1);
	strncpy(PNbuf, system, sizeof(PNbuf) - 1);
	for (p = system; *p; p++)
		*p = '\0';
	PN = PNbuf;
	(void)snprintf(sbuf, sizeof(sbuf), "tip%ld", BR);
	system = sbuf;

notnumber:
	(void)signal(SIGINT, cleanup);
	(void)signal(SIGQUIT, cleanup);
	(void)signal(SIGHUP, cleanup);
	(void)signal(SIGTERM, cleanup);
	(void)signal(SIGUSR1, tipdone);

	if ((i = hunt(system)) == 0) {
		printf("all ports busy\n");
		exit(3);
	}
	if (i == -1) {
		printf("link down\n");
		(void)uu_unlock(uucplock);
		exit(3);
	}
	setbuf(stdout, NULL);
	loginit();

	/*
	 * Kludge, their's no easy way to get the initialization
	 *   in the right order, so force it here
	 */
	if ((PH = getenv("PHONES")) == NULL)
		PH = _PATH_PHONES;
	vinit();				/* init variables */
	setparity("even");			/* set the parity table */
	if ((i = speed(number(value(BAUDRATE)))) == 0) {
		printf("tip: bad baud rate %d\n", number(value(BAUDRATE)));
		(void)uu_unlock(uucplock);
		exit(3);
	}

	/*
	 * Now that we have the logfile and the ACU open
	 *  return to the real uid and gid.  These things will
	 *  be closed on exit.  Swap real and effective uid's
	 *  so we can get the original permissions back
	 *  for removing the uucp lock.
	 */
	user_uid();

	/*
	 * Hardwired connections require the
	 *  line speed set before they make any transmissions
	 *  (this is particularly true of things like a DF03-AC)
	 */
	if (HW)
		ttysetup(i);
	if ((p = connect())) {
		printf("\07%s\n[EOT]\n", p);
		daemon_uid();
		(void)uu_unlock(uucplock);
		exit(1);
	}
	if (!HW)
		ttysetup(i);
cucommon:
	/*
	 * From here down the code is shared with
	 * the "cu" version of tip.
	 */

#if HAVE_TERMIOS
	tcgetattr (0, &otermios);
	ctermios = otermios;
#ifndef _POSIX_SOURCE
	ctermios.c_iflag = (IMAXBEL|IXANY|ISTRIP|IXON|BRKINT);
	ctermios.c_lflag = (PENDIN|IEXTEN|ISIG|ECHOCTL|ECHOE|ECHOKE);
#else
	ctermios.c_iflag = (ISTRIP|IXON|BRKINT);
	ctermios.c_lflag = (PENDIN|IEXTEN|ISIG|ECHOE);
#endif
	ctermios.c_cflag = (CLOCAL|HUPCL|CREAD|CS8);
	ctermios.c_cc[VINTR] = 	ctermios.c_cc[VQUIT] = -1;
	ctermios.c_cc[VSUSP] = ctermios.c_cc[VDSUSP] = ctermios.c_cc[VDISCARD] =
		ctermios.c_cc[VLNEXT] = -1;
#else /* HAVE_TERMIOS */
	ioctl(0, TIOCGETP, (char *)&defarg);
	ioctl(0, TIOCGETC, (char *)&defchars);
	ioctl(0, TIOCGLTC, (char *)&deflchars);
	ioctl(0, TIOCGETD, (char *)&odisc);
	arg = defarg;
	arg.sg_flags = ANYP | CBREAK;
	tchars = defchars;
	tchars.t_intrc = tchars.t_quitc = -1;
	ltchars = deflchars;
	ltchars.t_suspc = ltchars.t_dsuspc = ltchars.t_flushc
		= ltchars.t_lnextc = -1;
#endif /* HAVE_TERMIOS */
	raw();

	pipe(fildes); pipe(repdes);
	(void)signal(SIGALRM, timeoutfunc);

	/*
	 * Everything's set up now:
	 *	connection established (hardwired or dialup)
	 *	line conditioned (baud rate, mode, etc.)
	 *	internal data structures (variables)
	 * so, fork one process for local side and one for remote.
	 */
	printf(cumode ? "Connected\r\n" : "\07connected\r\n");

	if (LI != NULL && tiplink (LI, 0) != 0) {
		tipabort ("login failed");
	}

	if ((pid = fork()))
		tipin();
	else
		tipout();
	/*NOTREACHED*/
}
Example #30
0
bool update() {
    writeLog(L"Update started..");

    wstring updDir = L"tupdates\\temp", readyFilePath = L"tupdates\\temp\\ready", tdataDir = L"tupdates\\temp\\tdata";
    {
        HANDLE readyFile = CreateFile(readyFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
        if (readyFile != INVALID_HANDLE_VALUE) {
            CloseHandle(readyFile);
        } else {
            updDir = L"tupdates\\ready"; // old
            tdataDir = L"tupdates\\ready\\tdata";
        }
    }

    HANDLE versionFile = CreateFile((tdataDir + L"\\version").c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if (versionFile != INVALID_HANDLE_VALUE) {
        if (!ReadFile(versionFile, &versionNum, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD)) {
            versionNum = 0;
        } else if (!ReadFile(versionFile, &versionLen, sizeof(DWORD), &readLen, NULL) || readLen != sizeof(DWORD) || versionLen > 63) {
            versionNum = 0;
        } else if (!ReadFile(versionFile, versionStr, versionLen, &readLen, NULL) || readLen != versionLen) {
            versionNum = 0;
        }
        CloseHandle(versionFile);
        writeLog(L"Version file read.");
    } else {
        writeLog(L"Could not open version file to update registry :(");
    }

    deque<wstring> dirs;
    dirs.push_back(updDir);

    deque<wstring> from, to, forcedirs;

    do {
        wstring dir = dirs.front();
        dirs.pop_front();

        wstring toDir = updateTo;
        if (dir.size() > updDir.size() + 1) {
            toDir += (dir.substr(updDir.size() + 1) + L"\\");
            forcedirs.push_back(toDir);
            writeLog(L"Parsing dir '" + toDir + L"' in update tree..");
        }

        WIN32_FIND_DATA findData;
        HANDLE findHandle = FindFirstFileEx((dir + L"\\*").c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, 0, 0);
        if (findHandle == INVALID_HANDLE_VALUE) {
            DWORD errorCode = GetLastError();
            if (errorCode == ERROR_PATH_NOT_FOUND) { // no update is ready
                return true;
            }
            writeLog(L"Error: failed to find update files :(");
            updateError(L"Failed to find update files", errorCode);
            delFolder();
            return false;
        }

        do {
            wstring fname = dir + L"\\" + findData.cFileName;
            if (fname.substr(0, tdataDir.size()) == tdataDir && (fname.size() <= tdataDir.size() || fname.at(tdataDir.size()) == '/')) {
                writeLog(L"Skipped 'tdata' path '" + fname + L"'");
            } else if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                if (findData.cFileName != wstring(L".") && findData.cFileName != wstring(L"..")) {
                    dirs.push_back(fname);
                    writeLog(L"Added dir '" + fname + L"' in update tree..");
                }
            } else {
                wstring tofname = updateTo + fname.substr(updDir.size() + 1);
                if (equal(tofname, exeName)) { // bad update - has Updater.exe - delete all dir
                    writeLog(L"Error: bad update, has Updater.exe! '" + tofname + L"' equal '" + exeName + L"'");
                    delFolder();
                    return false;
                } else if (equal(fname, readyFilePath)) {
                    writeLog(L"Skipped ready file '" + fname + L"'");
                } else {
                    from.push_back(fname);
                    to.push_back(tofname);
                    writeLog(L"Added file '" + fname + L"' to be copied to '" + tofname + L"'");
                }
            }
        } while (FindNextFile(findHandle, &findData));
        DWORD errorCode = GetLastError();
        if (errorCode && errorCode != ERROR_NO_MORE_FILES) { // everything is found
            writeLog(L"Error: failed to find next update file :(");
            updateError(L"Failed to find next update file", errorCode);
            delFolder();
            return false;
        }
        FindClose(findHandle);
    } while (!dirs.empty());

    for (size_t i = 0; i < forcedirs.size(); ++i) {
        wstring forcedir = forcedirs[i];
        writeLog(L"Forcing dir '" + forcedir + L"'..");
        if (!forcedir.empty() && !CreateDirectory(forcedir.c_str(), NULL)) {
            DWORD errorCode = GetLastError();
            if (errorCode && errorCode != ERROR_ALREADY_EXISTS) {
                writeLog(L"Error: failed to create dir '" + forcedir + L"'..");
                updateError(L"Failed to create directory", errorCode);
                delFolder();
                return false;
            }
            writeLog(L"Already exists!");
        }
    }

    for (size_t i = 0; i < from.size(); ++i) {
        wstring fname = from[i], tofname = to[i];
        BOOL copyResult;
        do {
            writeLog(L"Copying file '" + fname + L"' to '" + tofname + L"'..");
            int copyTries = 0;
            do {
                copyResult = CopyFile(fname.c_str(), tofname.c_str(), FALSE);
                if (!copyResult) {
                    ++copyTries;
                    Sleep(100);
                } else {
                    break;
                }
            } while (copyTries < 30);
            if (!copyResult) {
                writeLog(L"Error: failed to copy, asking to retry..");
                WCHAR errMsg[2048];
                wsprintf(errMsg, L"Failed to update Telegram :(\n%s is not accessible.", tofname);
                if (MessageBox(0, errMsg, L"Update error!", MB_ICONERROR | MB_RETRYCANCEL) != IDRETRY) {
                    delFolder();
                    return false;
                }
            }
        } while (!copyResult);
    }

    writeLog(L"Update succeed! Clearing folder..");
    delFolder();
    return true;
}