Beispiel #1
0
static int	
sysconwrite(void *va, ulong count)
{
	Cmdbuf *cb;
	int e;
	cb = parsecmd(va, count);
	if(waserror()){
		free(cb);
		nexterror();
	}
	if(cb->nf == 0)
		error(Enoctl);
	if(strcmp(cb->f[0], "reboot") == 0){
		osreboot(rebootargv[0], rebootargv);
		error("reboot not supported");
	}else if(strcmp(cb->f[0], "halt") == 0){
		if(cb->nf > 1)
			e = atoi(cb->f[1]);
		else
			e = 0;
		cleanexit(e);		/* XXX ignored for the time being (and should be a string anyway) */
	}else if(strcmp(cb->f[0], "broken") == 0)
		keepbroken = 1;
	else if(strcmp(cb->f[0], "nobroken") == 0)
		keepbroken = 0;
	else if(strcmp(cb->f[0], "exdebug") == 0)
		exdebug = !exdebug;
	else
		error(Enoctl);
	poperror();
	free(cb);
	return count;
} 
Beispiel #2
0
Datei: os.c Projekt: 8l/inferno
int
readkbd(void)
{
	int n;
	char buf[1];

	n = read(0, buf, sizeof(buf));
	if(n < 0)
		print("keyboard close (n=%d, %s)\n", n, strerror(errno));
	if(n <= 0)
		pexit("keyboard thread", 0);

	switch(buf[0]) {
	case '\r':
		buf[0] = '\n';
		break;
	case DELETE:
		buf[0] = 'H' - '@';
		break;
	case CTRLC:
		cleanexit(0);
		break;
	}
	return buf[0];
}
Beispiel #3
0
void
netClient::StartClient( char * serverAddress )
{
	//int sock_fd;
	hostent 	*he;
	
	//printf("Doing host lookup...\n");
	if ( ( he = gethostbyname(serverAddress) ) == NULL ) // getting host information...
	{
#if HAS_HERROR
		herror("gethostbyname");
#endif
		cleanexit(1);
	}
	
	
	//printf("Opening socket...\n");
	if ( (m_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
	{
		perror("socket");
		cleanexit(1);
	}

	m_serverAddress->sin_family = AF_INET;				// host byte order
	m_serverAddress->sin_port = htons(HACKNET_PORT);		// short, network byte order
	m_serverAddress->sin_addr = *((in_addr *)he->h_addr);
	bzero((char *)&(m_serverAddress->sin_zero),8);				// zero out the rest of the struct

	// okay, we're all ready to go now!  (But we haven't yet connected)

	if ( signal( SIGPIPE, SIG_IGN ) == SIG_ERR )
	{
		perror("signal");
		exit(1);
	}
}
Beispiel #4
0
void
panic(char *fmt, ...)
{
	va_list arg;
	char buf[512];

	va_start(arg, fmt);
	vseprint(buf, buf+sizeof(buf), fmt, arg);
	va_end(arg);
	fprint(2, "panic: %s\n", buf);
	if(sflag)
		abort();

	cleanexit(0);
}
Beispiel #5
0
void sig_handler(int signo)
{
    switch(signo) {
      case SIGUSR1:
	  opt_debug = opt_debug ? 0 : 1;
	  break;
#if defined(_WanAutoDetect_) || defined(_IQSETUP_)
      case SIGUSR2:
    	  always_fake=1;
    	  break;
#endif
      default:
	  cleanexit(0);
    }
}
Beispiel #6
0
/*
 * sig_handler()
 *
 * In:       signo - the type of signal that has been recieved.
 *
 * Abstract: If we receive SIGUSR1, we toggle debugging mode.
 *           Otherwise, we assume that we should die.
 */
void sig_handler(int signo)
{
    switch(signo) {
      case SIGUSR1:
	  opt_debug = opt_debug ? 0 : 1;
	  break;
      case SIGHUP:		// hangup server
      	  // reset server list
      	  parse_serfile();
#ifndef EMBED
	  master_reinit();
#endif
	  cache_expireAll();
	  break;
      default:
	  cleanexit(0);
    }
}
Beispiel #7
0
static int
makesharedfb(void)
{
	XShmSegmentInfo *shminfo;

	shminfo = malloc(sizeof(XShmSegmentInfo));
	if(shminfo == nil) {
		fprint(2, "emu: cannot allocate XShmSegmentInfo\n");
		cleanexit(0);
	}

	/* setup to catch X11 error(s) */
	XSync(xdisplay, 0); 
	shm_got_x_error = 0; 
	if(old_handler != shm_ehandler)
		old_handler = XSetErrorHandler(shm_ehandler);
	if(old_io_handler != shm_ehandler)
		old_io_handler = XSetErrorHandler(shm_ehandler);

	img = XShmCreateImage(xdisplay, xvis, xscreendepth, ZPixmap, 
			      NULL, shminfo, Xsize, Ysize);
	XSync(xdisplay, 0);

	/* did we get an X11 error? if so then try without shm */
	if(shm_got_x_error) {
		free(shminfo);
		shminfo = NULL;
		clean_errhandlers();
		return 0;
	}
	
	if(img == nil) {
		fprint(2, "emu: cannot allocate virtual screen buffer\n");
		cleanexit(0);
	}
	
	shminfo->shmid = shmget(IPC_PRIVATE, img->bytes_per_line * img->height, IPC_CREAT|0777);
	shminfo->shmaddr = img->data = shmat(shminfo->shmid, 0, 0);
	shminfo->readOnly = True;

	if(!XShmAttach(xdisplay, shminfo)) {
		fprint(2, "emu: cannot allocate virtual screen buffer\n");
		cleanexit(0);
	}
	XSync(xdisplay, 0);

	/*
	 * Delete the shared segment right now; the segment
	 * won't actually go away until both the client and
	 * server have deleted it.  The server will delete it
	 * as soon as the client disconnects, so we might as
	 * well delete our side now as later.
	 */
	shmctl(shminfo->shmid, IPC_RMID, 0);

	/* did we get an X11 error? if so then try without shm */
	if(shm_got_x_error) {
		XDestroyImage(img);
		XSync(xdisplay, 0);
		free(shminfo);
		shminfo = NULL;
		clean_errhandlers();
		return 0;
	}

	gscreendata = malloc(Xsize * Ysize * (displaydepth >> 3));
	if(gscreendata == nil) {
		fprint(2, "emu: cannot allocate screen buffer (%dx%dx%d)\n", Xsize, Ysize, displaydepth);
		cleanexit(0);
	}
	xscreendata = (uchar*)img->data;
	
	clean_errhandlers();
	return 1;
}
Beispiel #8
0
/*
 *  Called on invalid command line args.
 *  Prints correct usage and cleanexits the program.
 */
void argerror() {
    printf("Correct Usage: ./trafficmgr <d1d2d3d4...>\n Where dn E [n,s,e,w] is the direction of the nth cart.\n");
    cleanexit();
}
Beispiel #9
0
int main(int argc, char** argv) {

    int rc;
    arg_t n,s,e,w;
    pthread_t north, south, east, west;

    if (argc == 2 && check_match(argv[1],"^[nsew]*$") > 0) {
        init(argv[1]);
        monitor_init();

        if (gl_env.n) {
            n.direction = 'n';
            rc = pthread_create(&north, NULL, cart, (void*)&n);
            if(rc){
                perror("Error creating North thread");
                cleanexit();
            }
        }

        if (gl_env.s) {
            s.direction = 's';
            rc = pthread_create(&south, NULL, cart, (void*)&s);
            if (rc) {
                perror("Error creating South thread");
                cleanexit();
            }
        }

        if (gl_env.e) {
            e.direction = 'e';
            rc = pthread_create(&east, NULL, cart, (void*)&e);
            if(rc){
                perror("Error creating East thread");
                cleanexit();
            }
        }

        if (gl_env.w) {
            w.direction = 'w';
            rc = pthread_create(&west, NULL, cart, (void*)&w);
            if (rc) {
                perror("Error creating West thread");
                cleanexit();
            }
        }

        if(gl_env.n)
            pthread_join(north, NULL);
        if(gl_env.s)
            pthread_join(south, NULL);
        if(gl_env.e)
            pthread_join(east, NULL);
        if(gl_env.w)
            pthread_join(west, NULL);

        monitor_shutdown();

    } else {
        /* invalid arguements entered */
        argerror();
    }


    cleanexit();
}
Beispiel #10
0
/*
 * main() - startup the program.
 *
 * In:      argc - number of command-line arguments.
 *          argv - string array containing command-line arguments.
 *
 * Returns: 0 on exit, -1 on error.
 *
 * Abstract: We set up the signal handler, parse arguments,
 *           turn into a daemon, write our pid to /var/run/dnrd.pid,
 *           setup our sockets, and then parse packets until we die.
 */
int main(int argc, char *argv[])
{
    int                i;
    FILE              *filep;
    struct servent    *servent;   /* Let's be good and find the port numbers
				     the right way */
    struct passwd     *pwent;
    DIR               *dirp;
    struct dirent     *direntry;
    struct stat        st;
    int                rslt;

    /*
     * Setup signal handlers.
     */
    signal(SIGINT,  sig_handler);
    signal(SIGQUIT, sig_handler);
    signal(SIGTERM, sig_handler);
    signal(SIGUSR1, sig_handler);
#if defined(_WanAutoDetect_) || defined(_IQSETUP_)
    signal(SIGUSR2, sig_handler);
#endif
    /*
     * Handling TCP requests is done by forking a child.  When they terminate
     * they send SIGCHLDs to the parent.  This will eventually interrupt
     * some system calls.  Because I don't know if this is handled it's better
     * to ignore them -- 14OCT99wzk
     */
    signal(SIGCHLD, SIG_IGN);

    /*
     * Parse the command line.
     */
    parse_args(argc, argv);

    openlog(progname, LOG_PID, LOG_DAEMON);

    /*
     * Kill any currently running copies of the program.
     */
    kill_current();

    /*
     * Setup the thread synchronization semaphore
     */
#if PTHREAD_LIB
    if (sem_init(&dnrd_sem, 0, 1) == -1) {
	log_msg(LOG_ERR, "Couldn't initialize semaphore");
	cleanexit(-1);
    }
#endif

    /*
     * Write our pid to the appropriate file.
     * Just open the file here.  We'll write to it after we fork.
     */
    filep = fopen(pid_file, "w");
    if (!filep) {
	log_msg(LOG_ERR, "can't write to %s.  "
		"Check that dnrd was started by root.", pid_file);
	exit(-1);
    }

    /*
     * Pretend we don't know that we want port 53
     */
    servent = getservbyname("domain", "udp");
    if (servent != getservbyname("domain", "tcp")) {
	log_msg(LOG_ERR, "domain ports for udp & tcp differ.  "
	       "Check /etc/services");
	exit(-1);
    }
    recv_addr.sin_port = servent ? servent->s_port : htons(53);

    /*
     * Setup our DNS query reception socket.
     */
    if ((isock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	log_msg(LOG_ERR, "isock: Couldn't open socket");
	cleanexit(-1);
    }
    else {
	int opt = 1;
	setsockopt(isock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }

    if (bind(isock, (struct sockaddr *)&recv_addr, sizeof(recv_addr)) < 0) {
	log_msg(LOG_ERR, "isock: Couldn't bind local address");
	cleanexit(-1);
    }

    /*
     * Setup our DNS tcp proxy socket.
     */
    if ((tcpsock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	log_msg(LOG_ERR, "tcpsock: Couldn't open socket");
	cleanexit(-1);
    }
    else {
	int opt = 1;
	setsockopt(tcpsock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
    if (bind(tcpsock, (struct sockaddr *)&recv_addr, sizeof(recv_addr)) < 0) {
	log_msg(LOG_ERR, "tcpsock: Couldn't bind local address");
	cleanexit(-1);
    }
    if (listen(tcpsock, 5) != 0) {
	log_msg(LOG_ERR, "tcpsock: Can't listen");
	cleanexit(-1);
    }

    /* Initialise our cache */
#ifdef ENABLE_CACHE
    cache_init();

    /* Initialise out master DNS */
    master_init();
#endif

    pwent = getpwnam("nobody");

    /*
     * Change our root and current working directories to /etc/dnrd.
     * Also, so some sanity checking on that directory first.
     */
    dirp = opendir("/etc/dnrd");
    if (!dirp) {
	log_msg(LOG_ERR, "The directory /etc/dnrd must be created before "
		"dnrd will run");
    }

    rslt = stat("/etc/dnrd", &st);
    if (st.st_uid != 0) {
	log_msg(LOG_ERR, "The /etc/dnrd directory must be owned by root");
	cleanexit(-1);
    }
    if ((st.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
	log_msg(LOG_ERR,
		"The /etc/dnrd directory should only be user writable");
	cleanexit(-1);
    }

    while ((direntry = readdir(dirp)) != NULL) {

	if (!strcmp(direntry->d_name, ".") ||
	    !strcmp(direntry->d_name, "..")) {
	    continue;
	}

	rslt = stat(direntry->d_name, &st);

	if (rslt) continue;
	if (S_ISDIR(st.st_mode)) {
	    log_msg(LOG_ERR, "The /etc/dnrd directory must not contain "
		    "subdirectories");
	    cleanexit(-1);
	}
	if ((st.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH|S_IWGRP|S_IWOTH)) != 0) {
	    log_msg(LOG_ERR, "A file in /etc/dnrd has either execute "
		    "permissions or non-user write permission.  Please do a "
		    "\"chmod a-x,go-w\" on all files in this directory");
	    cleanexit(-1);
	}
	if (st.st_uid != 0) {
	    log_msg(LOG_ERR, "All files in /etc/dnrd must be owned by root");
	    cleanexit(-1);
	}
    }
    closedir(dirp);

    if (chdir("/etc/dnrd")) {
	log_msg(LOG_ERR, "couldn't chdir to %s, %s",
		"/etc/dnrd", strerror(errno));
	cleanexit(-1);
    }
    if (chroot("/etc/dnrd")) {
	log_msg(LOG_ERR, "couldn't chroot to %s, %s",
		"/etc/dnrd", strerror(errno));
	cleanexit(-1);
    }

    /*
     * Change uid/gid to something other than root.
     */

    /* drop supplementary groups */
    if (setgroups(0, NULL) < 0) {
	log_msg(LOG_ERR, "can't drop supplementary groups");
	cleanexit(-1);
    }
    /*
     * Switch uid/gid to something safer than root if requested.
     * By default, attempt to switch to user & group id 65534.
     */

    if (daemongid != 0) {
	if (setgid(daemongid) < 0) {
	    log_msg(LOG_ERR, "couldn't switch to gid %i", daemongid);
	    cleanexit(-1);
	}
    }
    else if (!pwent) {
	log_msg(LOG_ERR, "Couldn't become the \"nobody\" user.  Please use "
		"the \"-uid\" option.\n"
		"       dnrd must become a non-root process.");
	cleanexit(-1);
    }
    else if (setgid(pwent->pw_gid) < 0){
	log_msg(LOG_ERR, "couldn't switch to gid %i", pwent->pw_gid);
	cleanexit(-1);
    }

    if (daemonuid != 0) {
	if (setuid(daemonuid) < 0) {
	    log_msg(LOG_ERR, "couldn't switch to uid %i", daemonuid);
	    cleanexit(-1);
	}
    }
    else if (!pwent) {
	log_msg(LOG_ERR, "Couldn't become the \"nobody\" user.  Please use "
		"the \"-uid\" option.\n"
		"       dnrd must become a non-root process.");
	cleanexit(-1);
    }
    else if (setuid(pwent->pw_uid) < 0){
	log_msg(LOG_ERR, "couldn't switch to uid %i", pwent->pw_uid);
	cleanexit(-1);
    }


    /*
     * Setup our DNS query forwarding socket.
     */
    for (i = 0; i < serv_cnt; i++) {
	if ((dns_srv[i].sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	    log_msg(LOG_ERR, "osock: Couldn't open socket");
	    cleanexit(-1);
	}

	dns_srv[i].addr.sin_family = AF_INET;
	dns_srv[i].addr.sin_port   = htons(53);
    }

    /*
     * Now it's time to become a daemon.
     */
    if (!opt_debug) {
	pid_t pid = fork();
	if (pid < 0) {
	    log_msg(LOG_ERR, "%s: Couldn't fork\n", progname);
	    exit(-1);
	}
	if (pid != 0) exit(0);
	gotterminal = 0;
	setsid();
	chdir("/");
	umask(077);
	fclose(stdin);
	fclose(stdout);
	fclose(stderr);
    }

    /*
     * Write our pid to the appropriate file.
     * Now we actually write to it and close it.
     */
    fprintf(filep, "%i\n", (int)getpid());
    fclose(filep);

    /*
     * Run forever.
     */
    run();
    exit(0); /* to make compiler happy */
}
Beispiel #11
0
void
netClient::Go()
{
	mapClientTile 	tile;				// for use in map updates
	netMapTile tileData;
	netMapEntity entityData;
	netMapUpdateBBox bbox;
	netMapReset mapReset;
	netGroupData groupData;
	netClientLocation clientLoc;
	hnPoint	point;
	sint8	levelCount;
	netInventory inven;
	netInventoryItem item;
	objDescription *objList;
	uint16	objectID;
	objType objectType;
	
	
	m_display->TextMessage("Trying to connect to server...\n");
	if ( connect( m_socket, (sockaddr *)m_serverAddress, sizeof(sockaddr) ) == -1 )
	{
		perror("connect");
		cleanexit(1);
	}
	m_display->TextMessage("Connected!\n");
	
	// Now that we're connected, send the server our name.

	SendName( m_display->GetName() );
	
	// now that we've connected, we wait for packets from the server or a key from our hnClient...
	
	
	m_display->Go();
	
	while(!m_done){
		// do stuff here until we quit.
		
		short 	readSizeBytesLeft = sizeof(sint16);
		short 	incomingBytes;
		char *	incomingBuffer = (char *)&incomingBytes;
		
		//  Emulate functionality of MSG_WAITALL, 'cause some architectures don't support it.
		while ( readSizeBytesLeft > 0 )
		{
#ifdef __DEBUGGING_NETWORK__
			printf("Waiting for %d bytes of packet size data..\n", readSizeBytesLeft);
#endif
			int bytesRead = recv( m_socket, incomingBuffer, readSizeBytesLeft, 0 );
#ifdef __DEBUGGING_NETWORK__
			printf("Received %d bytes.\n",bytesRead);
#endif
			if ( bytesRead == -1 )
			{
				perror("recv");
				cleanexit(1);
			}
			
			incomingBuffer += bytesRead;
			readSizeBytesLeft -= bytesRead;
		}
		incomingBytes = ntohs(incomingBytes);
		int  remainingBytes = incomingBytes;
		//printf("Receiving %d bytes...\n", incomingBytes);
		char buffer[incomingBytes];
		char *bufferPointer = buffer;
		
		//  Emulate functionality of MSG_WAITALL, 'cause some architectures don't support it.
		while ( remainingBytes > 0 )
		{
#ifdef __DEBUGGING_NETWORK__
			printf("Waiting for %d bytes of packet data..\n", remainingBytes );
#endif
			int bytesRead = recv( m_socket, bufferPointer, remainingBytes, 0 );
#ifdef __DEBUGGING_NETWORK__
			printf("Received %d bytes.\n", bytesRead);
#endif
			if ( bytesRead == -1 )
			{
				perror("recv");
				cleanexit(1);
			}
			bufferPointer += bytesRead;
			remainingBytes -= bytesRead;
		}
#ifdef __DISPLAY_PACKET_CONTENT__	
		printf("Packet of %d bytes:\n", incomingBytes );
		char *bufferstart = buffer;
		
		for ( int i = 0; i < incomingBytes; i++ )	
		{
			printf("Value: %d\n",*(bufferstart + i));
		}
		printf("\n");
		
#endif
		netMetaPacketInput *packet = new netMetaPacketInput(buffer, incomingBytes);
		
		while ( !packet->Done() )
		{
			sint8 type = packet->PeekSint8();
#define MAX_MESSAGE_BYTES	(256)
			char	messageBuffer[MAX_MESSAGE_BYTES];
			sint16 	messageBufferLength = MAX_MESSAGE_BYTES;
			
			switch ( type )
			{
				case SPT_ClientLocation:
					packet->ClientLocation(clientLoc);
					m_display->UpdateLocation( clientLoc.loc );
					break;
				case SPT_GroupData:
					packet->GroupData(groupData);
					m_display->UpdateGroupData(groupData.memberCount, groupData.memberTurns, groupData.haveTurnFromClient );
					break;
				case SPT_ClientStatistics:
				case SPT_ClientHitPoints:
				case SPT_ClientSpellPoints:
				case SPT_ClientExperience:
					m_display->GetStatus()->ReceiveChanges( packet );
					break;
				case SPT_MapTile:
					packet->MapTile(tileData);
					if ( m_display->isMapReady( tileData.loc.z ) )
					{
						tile.material = (hnMaterialType)tileData.material;
						tile.wall = (hnWallType)tileData.wall;
						m_display->UpdateMapTile(tileData.loc, tile);
					}
					break;
				case SPT_Message:
					packet->TextMessage(messageBuffer, messageBufferLength);
					m_display->TextMessage(messageBuffer);
					break;
				case SPT_ObjectStats:
					packet->ObjectStats(objectID);
					m_display->SetObjectStats(objectID);
					break;
				case SPT_ObjectName:
					packet->ObjectName(objectID, objectType, messageBuffer, messageBufferLength);
					m_display->SetObjectName(objectID, objectType, messageBuffer);
					break;
				case SPT_MapEntity:
					packet->MapEntity(entityData);
					
					if ( m_display->isMapReady( bbox.loc.z ) )
						m_display->UpdateMapCreature(entityData.loc, entityData.objectType);
					break;
				case SPT_DungeonReset:
					packet->DungeonReset(levelCount);
					m_display->DungeonReset(levelCount);
				case SPT_MapReset:
					packet->MapReset(mapReset);
					m_display->MapReset(mapReset.width, mapReset.height, mapReset.depth);
					break;
				case SPT_MapUpdateBBox:
					packet->MapUpdateBBox(bbox);

					//  If we haven't prepared this map yet, ask for a full refresh of
					//  this map, so we can initialise our map structures.
					if ( !m_display->isMapReady( bbox.loc.z ) )
					{
						SendRefreshRequest( bbox.loc.z );
						break;
					}
					
					for ( int i = 0; i < bbox.width; i++ )
						for ( int j = 0; j < bbox.height; j++ )
						{
							tile.material = bbox.material[i+(j*bbox.width)];
							tile.wall = bbox.wall[i+(j*bbox.width)];
							point.Set(bbox.loc.x+i, bbox.loc.y+j, 0);
							tile.entity = bbox.entityType[i+(j*bbox.width)];
							tile.objectCount = bbox.objectCount[i+(j*bbox.width)];
							tile.object = new objDescription[tile.objectCount];
							for ( int k = 0; k < tile.objectCount; k++ )
								tile.object[k] = bbox.object[i+(j*bbox.width)][k];
							m_display->UpdateMapTile( hnPoint(bbox.loc.x+i, bbox.loc.y+j, bbox.loc.z), tile);
							delete [] tile.object;
						}

					break;
				case SPT_Inventory:
					packet->Inventory(inven);
					objList = new objDescription[inven.GetObjectCount()];
					for ( int i = 0; i < inven.GetObjectCount(); i++ )
						objList[i] = inven.GetObject(i);
					m_display->UpdateInventory(inven.GetObjectCount(), objList);
					delete [] objList;
					break;
				case SPT_InventoryItem:
					packet->InventoryItem(item);
					m_display->UpdateInventoryItem(item.object, item.inventorySlot);
					break;
				case SPT_TakenItem:
					packet->TakenItem(item);
					m_display->TakenItem(item.object, item.inventorySlot);
					break;
				case SPT_DroppedItem:
					packet->DroppedItem(item);
					m_display->DroppedItem(item.object);
					break;
				case SPT_WieldedItem:
					packet->WieldedItem(item);
					m_display->WieldedItem(item.object, item.inventorySlot);
					break;
				case SPT_BadPacketNotice:
					packet->BadPacketNotice();
					delete m_display;
					printf("Server killed us for sending an unknown packet.  Version mismatch?\n");
					m_done = true;
					//exit(1);
					break;
				case SPT_QuitConfirm:
					packet->QuitConfirm();
					m_done = true;
					break;
				default:
					printf("Unknown packet type %d!!  :(\n", type);
					break;
			}
		}
		m_display->Refresh();	// do a screen refresh if we need it.
	}
	close( m_socket );
}
Beispiel #12
0
int main(int argc, const char ** argv)
{
    struct IntuiMessage *winmsg;
    ULONG signals, conreadsig, windowsig;
    LONG lch;
    WORD InControl = 0;
    BOOL Done = FALSE;
    UBYTE ch, ibuf;
    UBYTE obuf[200];
    BYTE error;

    FromWb = (argc==0L) ? TRUE : FALSE;

    if(!(IntuitionBase=OpenLibrary("intuition.library",0)))
         cleanexit("Can't open intuition\n",RETURN_FAIL);

    /* Create reply port and io block for writing to console */
    if(!(writePort = CreatePort("RKM.console.write",0)))
         cleanexit("Can't create write port\n",RETURN_FAIL);

    if(!(writeReq = (struct IOStdReq *)
                    CreateExtIO(writePort,(LONG)sizeof(struct IOStdReq))))
         cleanexit("Can't create write request\n",RETURN_FAIL);

    /* Create reply port and io block for reading from console */
    if(!(readPort = CreatePort("RKM.console.read",0)))
         cleanexit("Can't create read port\n",RETURN_FAIL);

    if(!(readReq = (struct IOStdReq *)
                   CreateExtIO(readPort,(LONG)sizeof(struct IOStdReq))))
         cleanexit("Can't create read request\n",RETURN_FAIL);

    /* Open a window */
    if(!(win = OpenWindow(&nw)))
         cleanexit("Can't open window\n",RETURN_FAIL);

    /* Now, attach a console to the window */
    if(error = OpenConsole(writeReq,readReq,win))
         cleanexit("Can't open console.device\n",RETURN_FAIL);
    else OpenedConsole = TRUE;

    /* Demonstrate some console escape sequences */
    ConPuts(writeReq,"Here's some normal text\n");
    sprintf(obuf,"%s%sHere's text in color 3 & italics\n",COLOR03,ITALICS);
    ConPuts(writeReq,obuf);
    ConPuts(writeReq,NORMAL);
    Delay(50);      /* Delay for dramatic demo effect */
    ConPuts(writeReq,"We will now delete this asterisk =*=");
    Delay(50);
    ConPuts(writeReq,"\b\b");  /* backspace twice */
    Delay(50);
    ConPuts(writeReq,DELCHAR); /* delete the character */
    Delay(50);

    QueueRead(readReq,&ibuf); /* send the first console read request */

    ConPuts(writeReq,"\n\nNow reading console\n");
    ConPuts(writeReq,"Type some keys.  Close window when done.\n\n");

    conreadsig = 1 << readPort->mp_SigBit;
    windowsig = 1 << win->UserPort->mp_SigBit;

    while(!Done)
        {
        /* A character, or an IDCMP msg, or both could wake us up */
        signals = Wait(conreadsig|windowsig);

        /* If a console signal was received, get the character */
        if (signals & conreadsig)
            {
            if((lch = ConMayGetChar(readPort,&ibuf)) != -1)
                {
                ch = lch;
                /* Show hex and ascii (if printable) for char we got.
                 * If you want to parse received control sequences, such as
                 * function or Help keys,you would buffer control sequences
                 * as you receive them, starting to buffer whenever you
                 * receive 0x9B (or 0x1B[ for user-typed sequences) and
                 * ending when you receive a valid terminating character
                 * for the type of control sequence you are receiving.
                 * For CSI sequences, valid terminating characters
                 * are generally 0x40 through 0x7E.
                 * In our example, InControl has the following values:
                 * 0 = no, 1 = have 0x1B, 2 = have 0x9B OR 0x1B and [,
                 * 3 = now inside control sequence, -1 = normal end esc,
                 * -2 = non-CSI(no [) 0x1B end esc
                 * NOTE - a more complex parser is required to recognize
                 *  other types of control sequences.
                 */

                /* 0x1B ESC not followed by '[', is not CSI seq */
                if (InControl==1)
                    {
                    if(ch=='[') InControl = 2;
                    else InControl = -2;
                    }

                if ((ch==0x9B)||(ch==0x1B))  /* Control seq starting */
                    {
                    InControl = (ch==0x1B) ? 1 : 2;
                    ConPuts(writeReq,"=== Control Seq ===\n");
                    }

                /* We'll show value of this char we received */
                if (((ch >= 0x1F)&&(ch <= 0x7E))||(ch >= 0xA0))
                   sprintf(obuf,"Received: hex %02x = %c\n",ch,ch);
                else sprintf(obuf,"Received: hex %02x\n",ch);
                ConPuts(writeReq,obuf);

                /* Valid ESC sequence terminator ends an ESC seq */
                if ((InControl==3)&&((ch >= 0x40) && (ch <= 0x7E)))
                    {
                    InControl = -1;
                    }
                if (InControl==2) InControl = 3;
                /* ESC sequence finished (-1 if OK, -2 if bogus) */
                if (InControl < 0)
                    {
                    InControl = 0;
                    ConPuts(writeReq,"=== End Control ===\n");
                    }
                }
            }

        /* If IDCMP messages received, handle them */
        if (signals & windowsig)
            {
            /* We have to ReplyMsg these when done with them */
            while (winmsg = (struct IntuiMessage *)GetMsg(win->UserPort))
                {
                switch(winmsg->Class)
                    {
                    case IDCMP_CLOSEWINDOW:
                      Done = TRUE;
                      break;
                    default:
                      break;
                     }
                ReplyMsg((struct Message *)winmsg);
                }
            }
        }

    /* We always have an outstanding queued read request
     * so we must abort it if it hasn't completed,
     * and we must remove it.
     */
    if(!(CheckIO(readReq)))  AbortIO(readReq);
    WaitIO(readReq);     /* clear it from our replyport */

    cleanup();
    exit(RETURN_OK);
    }