TweetFollow Us on Twitter

ATalk Server
Volume Number:1
Issue Number:10
Column Tag:C Workshop

"Dial a Fortune Apple Talk Server"

By Robert B. Denny, Timothy T. Coad, Alisa Systems, Inc., MacTutor Editorial Board

It's been about six months since the AppleTalk network was released. Yet there seems to be little software available which uses this network. One reason is that the market is too small as yet and developers can't see enough potential to risk the investment. Another reason is that AppleTalk applications appear difficult to implement, requiring a great deal of knowledge and understanding that is not easy to obtain. Last, but certainly not least, Apple has failed to complete the basic services that history has shown are required for successful introduction of a computer network.

About six or seven months ago, Apple released a publication called Inside AppleTalk, available from the same source as Inside Macintosh. In addition, most developers who subscribed to the Apple "Software Supplement" have received The AppleTalk Manager: A Programmer's Guide, a part of Inside AppleTalk. These documents do a fairly good job of describing the network architecture and the details of using the AppleTalk services. If you have no experience with local area networks, however, you may get lost in the jargon and fail to "see the forest through the trees".

This month's C Workshop is devoted to AppleTalk. It includes a complete server application called Confucious which, when run on a Mac connected to the network, provides a "guru" service. A Mac Pascal client application is described by Alan Wootton in a separate article in this issue of Mac Tutor. The Pascal client, running on another Mac, locates the C server and makes requests for pearls of wisdom, which the server gladly sends back.

In order to keep this article's size reasonable, we assume that (1) you understand how to use the Mac's I/O services and (2) you have access to (at least) the AppleTalk Manager Programmer's Guide. The article describes the overall architecture of the AppleTalk network, and concludes with a listing of the server's code, written mostly in C. We'll look at programming details next month.

Fig. 1 - AppleTalk Components

NOTE: The descriptions given in this article are simplified so as to make it easier to understand the overall architecture of AppleTalk. Please consult the Apple documentation for full details.

Protocols and Layers

The lifeblood of any network is its suite of protocols that are used to negotiate and communicate. Usually, there are two agents in a network operation, the client and the server. The operation consists of a set of information exchanges between the client and the server, according to a protocol.

In order to bring some order to the chaos that would be created by a multitude of protocols, some of which are clients of other protocols and servers to yet others, network designers use the concepts of layers and interfaces. A layer implements a set of services via an interface. For example, the file system on the Mac has a layer that handles "raw" disk I/O (the device manager), and a layer on top of that which handles the organization of data on the disk into files and directories (the file manager). This separation of functions makes it possible to handle both hard disks and floppies with the same file manager routines. The file manager uses a defined interface to the device manager for its requests. Finally, the organization of data on the disk as files and directories is a sort of "spatial protocol".

Network architectures are normally divided into seven layers, according to the ISO "Open Systems Interconnection" convention adopted about five years ago. These layers, from lowest to highest are:

Physical: Electrical and mechanical aspects of communication circuits.

Data Link: Data and frame formats, bus access & contention protocols, error detection, other low level link services.

Network: Addressing and routing of messages between "sockets" transparently across multiple data links.

Transport: Error and flow control between sockets. Exchanges of information between routing agents on special sockets.

Session: Opening and closing logical links between sockets. Starting up remote servers on request. Naming of entities and name services.

Presentation: Cryptosystems, code conversion (e.g., ASCII to EBCDIC), other transformations needed for the native application environment.

Application: Protocols used between specific applications.

AppleTalk Architecture

Apple Computer has so far defined and published protocols for the physical through the transport layers of AppleTalk. Generally speaking, AppleTalk has a bus oriented, packet-based architecture, supporting internetworking, named objects, adaptive routing and a transaction-oriented transport service.

Services are implemented in a pair of I/O drivers and associated resources which are opened permanently on 512K Macs, and live in the system heap. On 128K Macs, applications which want to use the network must manually open the drivers, loading them into the application heap. This means that no "detached" service processes in the system heap can be supported on the smaller systems. Figure 1 shows the breakdown of AppleTalk functions and the drivers that implement them.

Physical & Data Link Layers: ALAP

The physical layer consists of a bus topology twisted-pair cable carrying electrical signals conforming to the EIA RS-422 standard. The Mac hardware has a "serial communications controller" (SCC) which is capable of being software configured as a standard async or sync port, or as an AppleTalk port. AppleTalk uses the printer port on the Mac.

The data link layer is implemented in software and uses the "AppleTalk Link Access Protocol" (ALAP) to manage usage of the common bus and to detect transmission errors between physically connected Mac systems. ALAP uses a frame format which is similar to that used by several well known block-oriented protocols such as HDLC. The algorithms used to manage multiple access to the bus are specific to AppleTalk, and fall into the category of "Carrier Sense Multiple Access" (CSMA).

Simply stated, the rules of CSMA are: (1) talk if no one else is talking; (2) if you want to talk and some one else is already talking, go away and try again later; (3) if two of you start talking at the same time, yell "Abort!" so everyone else knows, then both of you go away and try again later.

One other thing to note: The assignment of node numbers to each station on a network is not done by the user. Rather, the ALAP software tries to assign a random node number when the Mac is booted, then shouts it out over the net. If no one else objects, that is the node number to be used. Otherwise, another try is made.As an application developer, you'll rarely deal directly with ALAP.

Network Layer: DDP

The network layer uses the "Datagram Delivery Protocol" (DDP), which defines the format of the address header which is included in each packet and which stays with the packet between cooperating processes through communication endpoints called sockets. The path between sockets may span several physical links, and may go through intermediate systems. One Mac may have several AppleTalk connections open at a time, so the node number is not enough to identify a network address.

An address must consist of at least a node number and a socket number. In fact, AppleTalk considers a socket to be the one and only network-visible entity. Socket numbers fall into two groups. The "well-known" sockets (1-127) are assigned by Apple for specific generic network services and experimentation. The others (128-254) are called "dynamic" sockets. They are assigned temporarily and are often associated with a name managed by the Name Binding service of AppleTalk (see below).

Individual AppleTalk networks may be tied together to form an internetwork. Node numbers are unique only within a single physical network, so DDP requires that each network be assigned a network number. Figure 2 (see top of next page) shows a three-net internetwork. The Networks are connected by either a full bridge or a pair of half-bridges. The full bridge attaches directly to two physical networks and provides datagram routing from one to the other. The pair of half bridges does the same thing, but they use an intermediate transmission medium such as a long-distance telephone line.

Fig. 2 - An AppleTalk Internetwork

DDP defines an internet address consisting of a net number, a node number and a socket number. One might argue that the net number is superfluous, since the node number could be made unique within the entire internet. True, but the early local net designers at Xerox PARC decided that routing overhead should be minimized.

The key to their idea is that many nodes are attached to a single network, and that getting the packet to the proper local network is all that's needed to get it to the destination node. Normally, there are far fewer networks than nodes, so the routers have a much easier task. AppleTalk incorporates this network-oriented routing system.

The basic service provided by DDP is to "try its best" to get a packet from the source to the destination. If there is a problem somewhere, the packet is vaporized. DDP doesn't care about the details of link management or signalling, it only needs some sort of link service to it's neighbors in the net. Application developers rarely use the datagram services directly.

Routing Services: RTMP

The DDP internet routing process requires information as to the topology (interconnect configuration) of the internet. Each router involved in getting a DDP datagram from the source to the destination net must know where to send the datagram next. The routers use a set of routing tables to maintain this information.

The tables consist of a list of net numbers paired with the local node number of the bridge through which the shortest path to that net exists. These tables are dynamically constructed and maintained, with no need for a network manager to describe the topology. Automatic routing table maintenance is done by the routers carrying on a continuous chit-chat, proclaiming themselves as routers and broadcasting routing information for other routers, using the Routing Table Maintenance Protocol (RTMP).

Routing information exchange uses DDP at its communication medium, via socket number 1. Each Mac has a small RTMP-speaking process that keeps track of the nearest router and the network number of the local net. Bridges have a full-function RTMP-speaking process which engages in the prescribed chit-chat to maintain their routing tables. Bridges use this routing table to relay DDP datagrams according to their destination network number.

Transport Layer: ATP

The transport layer protocols are used to control the flow of data between sockets, and for end-to-end error recovery. Clients of the transport layer are offered some sort of "logical link" or "virtual circuit" service between themselves and other network visible entities.

Most networks are fairly similar in the first three layers, up through the network layer. Above that, however, their architectures begin to diverge. The transport layer is usually the first to reflect the main purpose for which the network was designed. AppleTalk is quite unusual in this respect.

Typically, the transport layer supports a two-way link between clients. Some sort of higher level protocol handles the opening of the link, and the transport layer provides error and flow control. The clients at each end can act as though they have an error-free hardwired line between them. AppleTalk does not support this sort of protocol.

Instead, AppleTalk has a transaction-oriented transport protocol, called AppleTalk Transaction Protocol (ATP). Here, one end acts as a requestor and the other acts as a responder. The responder usually sets itself up on a "permanent" socket. Requestors can "pop up" anywhere, at any time, and send requests. The example application at the end of this article is a responder.

The requestor sends a request which may carry with it up to 578 bytes of data in a single segment. The responder may send back up to eight such segments, for 4624 bytes total. If the request arrives in error, it is simply discarded. The requestor keeps trying until it receives a response. Response segments that are damaged are re-transmitted. This selective retransmission is handled by the ATP protocol, invisible to ATP clients.

Sometimes it is important that a request be serviced once and only once. An example of such a request would be to backspace a record in a remote file. Remember that the requestor repeatedly requests until it receives a response.

ATP provides a special class of transaction service called "exactly once". Each request is tagged with a transaction ID. The responder ATP has the logic needed to assure that the request with a given transaction ID is executed only once. The penalty for such service is extra overhead.

Named Entities: NBP

Recall that the only network-visible entities are sockets (socket clients, actually). Communication between processes on AppleTalk takes place between socket clients. A key feature of the network is that most objects are accessible by name rather than by address. Node numbers and dynamic socket numbers are assigned randomly. People prefer names.

The Name Binding Protocol (NBP) defines a set of services that applications can use to register names for their sockets, and to locate named entities. AppleTalk names consist of three fields: the object name, the type name and the zone name. The object name is the "name" as we usually think of it. The type indicates what sort of object it is. The zone field is not currently supported by AppleTalk and is always set to the value "*", meaning "this zone". The format of a name is:

object:type@zone

The object and type fields in a name may contain the wildcard character "=" which stands for "all possible values". Thus the name "=:printer@*" means "all printers in this zone", or simply "all printers" since the zone concept is not yet supported.

Usually, a server will make itself available to the network by opening an ATP-responding socket, then registering itself by name, associating the name with its network address (net/node/socket). Then a client may lookup the server by name, or it may look up all servers of that type (using the "=" wildcard) then choose a particular one for use.

Limitations of AppleTalk

Now that we have an overview of the network architecture, let's look at the limitations of AppleTalk, especially its unusual transport layer protocol, ATP. Understanding these limitations is very important to you, as a developer. Unless Apple faces up to these limitations, you will be saddled with the responsibility of creating your own "session" oriented service, either on top of ATP or in addition to it. Let's see why.

Recall that ATP provides a transaction-oriented service. There is no provision for sequencing or otherwise grouping transactions. There is no "private wire" service between cooperating applications.

Consider a file server, whose ATP responding socket is visible to the whole network. Anyone, at any time, is free to issue an ATP request to the server's socket, and to expect a response. But file service implies a "context" spanning several transactions: an open file with a current file position.

This means that the file server must remember what's going on for each client who has a file open on that server. And a single client may have more than one file open, further complicating matters. The client and server need to set up a conversation which will continue across several transactions.

An open file is typical of a general class of network operations which require a private "session" to be maintained between the client and the server. This is the domain of the ISO session layer. AppleTalk has no session layer support.

You may say, "Well, at least ATP handles error and flow control; I can build sessions myself". But layering a session protocol on top of a "reliable transaction" protocol creates other problems. If we believe in internetworking, systems of interconnected AppleTalk bus networks, then we must face the problem of transport delay.

Suppose we want to set up an internet session, between sockets on nodes which are on different physical networks, separated by several bridges and perhaps a backbone network. The connection between client and server has plenty of speed capacity, but packets may be delayed up to 100 milliseconds in bridges and routers. ATP requires completion of a transaction before another can start. With a 100 mS delay from one end to the other, our transport protocol is capable of one transaction every 200 mS, or 5 transactions per second! Without the transport delay, the Macintosh ATP implementation is capable of hundreds of transactions per second.

It is important to understand that the degradation is not due to speed limits of the transmission medium, but instead due to the transport delay from one end to the other and ATP's need to complete a transaction before the next can be started. In an internetworking environment such as AppleTalk, transport delays are a fact of life. ATP is poorly suited as a transport protocol in such situations.

Another aspect of ATP is its asymmetry. An ATP request may carry up to 578 bytes of data. The response, on the other hand, can carry 8 times that amount of data. The responding socket is more or less permanent, the requesting socket is opened and closed for each request. The responder has no way of delivering an asynchronous message to the requestor. Data flow from the requestor to the responder has a higher overhead than that in the opposite direction.

These facts have caused some developers to set up responding sockets at each end of a client-server connection. This approach uses two sockets at each end (temporary requestor, permanent responder). But there is a limit to the total number of ATP sockets that may be open in the current version of AppleTalk, 6 requestors and 6 responders. So sockets are a precious quantity and this approach wastes sockets unnecessarily.

AppleTalk has no session layer, a severe architectural deficiency which will promote multiple "private" session protocols, some of which may be poorly designed for the internet environment. Session protocols are among the most difficult to design and test. Often, the theoretical behavior of the network used as the basis for protocol design turns out to be inaccurate. Error recovery in the session layer is probably the most complex design issue in networking.

There is another limitation that took me by surprise. AppleTalk does not support transactions between sockets on the same node. At first this might not seem to be too serious but, as any networking veteran will tell you, it is serious. If your node happens to be the one with a server you need, you can't get to it. Keep this in mind when designing AppleTalk applications: your application must handle the case where the server and client are on the same node.

A Sample AppleTalk Server

The rest of this article contains the sources for an example AppleTalk "Dial-A-Fortune" Server. Note that the main program is fairly simple, and that most of the AppleTalk access functions are broken out separately and written for general use. (See fig. 3 on the previous page.)

There is not room for explanation of the details, but much of the information you'll need to understand this program is covered in Alan Wootton's article in this issue. I will explain its operation next month, along with more about AppleTalk.

One last item: You do NOT have a copy of the file ATALK.H, which contains the structure definitions and constant definitions needed for AppleTalk I/O. The items required for this program will be published next month. The full ATALK.H will be available on a MacTutor Source Disk. Also, look for some interesting AppleTalk developer's tools from Consulair soon.

Resource File in RMaker Format
*
* DFServer.R - RMAKER source.
*
Dev:DFServer
APPL????
* Load linker output
Include Dev:DFServer.Rsrc
*
* Define the DIAL-A-FORTUNE SERVER Modal dialog.
*
Type DLOG
   ,128
 No Title
40 96 240 416
Visible
1
0
128

Type DITL
   ,128
6

Button
175 20 195 90
Fortune

Button
175 230 195 300
Quit

StaticText Disabled
5 80 20 310
AppleTalk Dial-A-Fortune

StaticText Disabled
20 72 35 310
^0

StaticText Disabled
45 110 60 310
Confucious Say: 

StaticText Disabled
70 20 170 310
Press FORTUNE to get your Fortune or QUIT to ++ shutdown the AppleTalk 
Dial-A-Fortune Server.

*
* Entity string components
*
Type STR 
   ,128
Confucious

Type STR 
   ,129
Dial-A-Fortune

Type STR 
   ,130
\2A

*
* Number of fortunes and the fortunes themselves.
*
TYPE DATA = GNRL
   ,128
.H
nnnn

Type STR 
   ,131
One of the greatest sources of energy is pride in ++
what you are doing.

Type STR
   ,132
Take a cannibal to lunch.

( more fortune strings ...)

Type STR
   ,150
Every successful person has had failures but repeated failure is no ++
guarantee of eventual success.

END



/*
  *Dial-A-Fortune AppleTalk™ Server Application
  *
  *Written by:   Timothy T. Coad, Alisa Systems, Inc.
  *June, 1985
  *Written for:  Apple Computer MDS Development System and Consulair 
Mac C™
  *This program uses specific features of the MDS system and Mac C
  *and will almost certainly require modifications for other systems.
  *
  *  LINKER COMMAND FILE (uses Mac C minimum library, output is read 
by RMaker)
  *--
  * !Start
  *
  * /Output Dev:DFServer.Rsrc
  * /Type 'RSRC'
  * 
  * MacCLib
  * DFServer
  *
  * $
  *--
  *
  *Copyright (C) 1985, MacTutor Magazine
  *
  *Permission granted to use only for non-commercial purposes.  This 
notice must be
  *included in any copies made hereof.  All rights otherwise reserved.
  *
  *Warning: This code was edited for publication and may possibly contain 
minor errors
  */

#define VERSION  "\032Experimental version 1.0.A"

#include"Lib:MacDefs.H"   /* The usual collection of Mac definitions 
*/
#include"Lib:QuickDraw.H"
#include"Lib:Window.h"
#include  "Lib:TextEdit.H"
#include"Lib:Dialog.h"
#include"Lib:Events.H"
#include  "Lib:PBDefs.H"

#include"Lib:ATalk.H"/* AppleTalk definitions  to be published next month 
*/

#define FALSE    0
#define TRUE1

#define DIALOG_ID128
#define FORTUNE_DI 6 /* Dialog Item number of Fortune item */

#define NUMOFSTRINGS_ID 128 /* Resource ID of fortune string count ('DATA') 
*/
#define FIRSTSTR_ID131  /* Resource ID of first fortune string ('STR') 
*/

/*
  * Resource IDs of the three parts of server's Network Entity Name.
  */
#define OBJECT_ID128 /* Object name (Confucious) */
#define TYPE_ID  129 /* Object type (Dial-A-Fortune) */
#define ZONE_ID  130 /* Our zone ('*' = 'This zone') */

/*
  *Global Variables
  */

NBPElem *ourName;/* -> Our registered name/skt (locked block) */
ATPBlockATPGetReq, ATPResp; /* Statically allocated I/O parameter blocks 
*/
BDSRespBDS; /* Buffer Descriptor Structure for response */
char    ReqPkt[256]; /* Buffer to receive incoming requests */
char    RespPkt[256];/* Buffer for responses (fortune text) */
unsigned short NumOfStrings;/* Number of fortune string resources */
Handle  Fortuneitem; /* Handle to currently selected fortune string */

extern shortatpOpenSkt();
extern shortatpCloseSkt();
extern intGetReqComplete();
extern intFilterGlue();

/*
  * Dial-A-Fortune Main Program
  */
main()
 {
 unsigned short button, i;/* Locals, usage is obvious except as noted 
*/
 Handle handle;
 DialogPtr dlog;
 unsigned short type;
 Rect rect;
 char fortune[256];
 
 InitDialogs (0);/* No restart function */
 InitCursor ();  /* Make arrow cursor */
 SaveA5();/* Save our A5 for async completion routines */

 /*
   * Allocate a non-relocatable NBPElem structure, request for an ephemeral 
responding socket 
   * and register ourselves on the net.
   */
 ourName = (NBPElem *)NewPtr (sizeof(NBPElem));
 ourName->tuple.addr.skt = 0;
 ourName->tuple.addr.net = 0;
 if(atpOpenSkt(&(ourName->tuple.addr.skt)))
 { /* Can't open a socket */
 DisposPtr (ourName);/* Release tuple storage */
 return;/* and exit. */
 }
 /*
   * Get the three parts of the Network Entity Name and register ourselves 
using NBP.
   */
 handle = (Handle)GetResource ('STR ', OBJECT_ID);
 i = pstrcpy(ourName->tuple.entity, *handle);
 ReleaseResource (handle);
 handle = (Handle)GetResource ('STR ', TYPE_ID);
 i += pstrcpy(ourName->tuple.entity + i, *handle);
 ReleaseResource (handle);
 handle = (Handle)GetResource ('STR ', ZONE_ID);
 pstrcpy(ourName->tuple.entity + i, *handle);
 ReleaseResource (handle);
 if(NBPRegister(2, 8, ourName))    /* Registration error? */
 { 
 atpCloseSkt(ourName->tuple.addr.skt); /* Yes, free the socket and ... 
*/
 DisposPtr (ourName);/* ... release tuple storage. */
 return;/* Exit */
 }
 /* 
   * The number of fortunes is stored in a resource to make it possible 
to add new ones.
   */
 handle = (Handle)GetResource ('DATA', NUMOFSTRINGS_ID); 
 NumOfStrings = (unsigned short)(*((unsigned short *)(*handle)));
 ReleaseResource (handle);

 /*
   * Prime the pump with the initial asynchronous ATP Get Request.
   */
 GetATPRequest(&ATPGetReq, ourName->tuple.addr.skt, ReqPkt, 256, GetReqComplete);

 /*
   * Put up our dialog box.  Use a modal dialog filter procedure to handle 
the completion of the
   *  GetATPRequest.  The GetATPRequest completion routine posts an event 
which is filtered
   * and processed by the modaldialog filter procedure.
   */
 dlog = (DialogPtr)GetNewDialog (DIALOG_ID, 0, -1);
 GetDItem (dlog, FORTUNE_DI, &type, &Fortuneitem, &rect);
 ParamText (VERSION, "", "", "");
 button = 0;
 while(button != cancel)
 {
 ModalDialog (FilterGlue, &button);
 if(button == oK)/* Fortune button pressed? */
 { /* Yes, put up a fortune */
 GetFortune(fortune);
 SetIText (Fortuneitem, fortune);
 }
 }
 DisposeDialog (dlog);    /* Dispose of dialog */
 NBPRemove(ourName->tuple.entity); /* Remove us from net */
 atpCloseSkt(ourName->tuple.addr.skt); /* Free the socket */
 }

/*
  * SendFortune
  *
  * Get a random STR resource, display in the server's dialog box, ship 
it back to the 
  * requestor as an ATP response packet and finally re-arm ourselves 
for another request.
  */
SendFortune()
 {
 GetFortune(RespPkt);
 SetIText (Fortuneitem, RespPkt);
 SendATPResp(&ATPResp, &ATPGetReq.csParam.atpGetRequest.addr, 
 ourName->tuple.addr.skt, RespPkt, 256, &RespBDS,              
 ATPGetReq.csParam.atpGetRequest.transID, 0);
 GetATPRequest(&ATPGetReq, ourName->tuple.addr.skt, ReqPkt, 256, GetReqComplete);
 }

/*
  * GetFortune
  *
  * Get a random STR resource, modulo number of strings.  Return pointer 
to string in memory.
  */
GetFortune(fortune)
char *fortune;
 {
 Handle string;
 unsigned short index;
 
 index = FIRSTSTR_ID + ((unsigned short)Random ()) % NumOfStrings;
 string = (Handle)GetResource ('STR ', index);
 pstrcpy(fortune, *string);
 ReleaseResource (string);
 }

/*
  * AppleTalk Name Binding Protocol (NBP) Low Level I/O Routines
  */

/*
  * nbpRegister - Register an element with AppleTalk.
  *
  * Returns the I/O result.
  */
short nbpRegister(interval, count, elem)
unsigned char interval;   /* Retry interval, ticks */
unsigned char count; /* Number of retries */
NBPElem *elem;   /* -> Element with name to register */
 {
 MPPBlock block;
 
 block.ioRefNum = mppRefNum;/* I/O is to the MPP driver */
 block.csCode = _nbpRegister; /* Function is "Register name" */
 block.csParam.nbpRegister.retry.interval = interval;    /* Fill in retry 
interval */
 block.csParam.nbpRegister.retry.count = count;    /* Fill in retry count 
*/
 block.csParam.nbpRegister.verify = 1; /* Enable name clash checking 
*/
 block.csParam.nbpRegister.elem = elem;/* Fill in -> name to register 
*/
 return(PBControl(&block, 0));/* DO IT, return the result */
 }

/*
  * nbpRemove - Remove an entity from AppleTalk Registry.
  *
  * Return the I/O result code.
  */
short nbpRemove(entity)
Entity *entity;  /* -> Entity string for name to remove */
 {
 MPPBlock block; /* I/O parameter block */
 
 block.ioRefNum = mppRefNum;/* I/O to .MPP driver */
 block.csCode = _nbpRemove; /* Function is "Remove name" */
 block.csParam.nbpRemove.entity = entity;          /* Fill in -> to entity 
string */
 return(PBControl(&block, 0));/* DO IT and return result */
 }


/*
  * AppleTalk Transaction Protocol (ATP) Low Level I/O Routines.
  */

/*
  * atpOpenSkt - Open an dynamic ATP responding socket.
  *
  * Socket number set to 0 if it fails.  Returns the I/O result code.
  */
short atpOpenSkt(skt)
unsigned char *skt;/* -> byte to receive assigned socket number */
 {
 ATPBlock block; /* I/O Parameter block */
 
 block.ioRefNum = atpRefNum;/* I/O is for .ATP driver */
 block.csCode = _atpOpenSkt;/* Func is "Open Responding Socket */
 block.csParam.atpOpenSkt.skt = 0; /* Socket=0 for dynamically assigned 
*/
 block.csParam.atpOpenSkt.addr.net = 0;/* Zero internet fields */
 block.csParam.atpOpenSkt.addr.node = 0;
 block.csParam.atpOpenSkt.addr.skt = 0;
 *skt = PBControl(&block, 0) ? 0 : block.csParam.atpOpenSkt.skt; /* OPEN 
IT */
 return(block.ioResult);  /* Return result */
 }

/*
  * atpCloseSkt - Close an ATP responding socket.
  *
  * Returns I/O result code.
  */
short atpCloseSkt(skt)
unsigned char skt; /* Number of ATP socket to close */
 {
 ATPBlock block;
 
 block.ioRefNum = atpRefNum;/* I/O is for .ATP driver */
 block.csCode = _atpCloseSkt; /* Function is "Close Resp. Socket" */
 block.csParam.atpCloseSkt.skt = skt;/* Fill in socket to close */
 return(PBControl(&block, 0));/* DO IT and return result */
 }

/*
  * SendATPResp - Send a single-packet ATP response. 
  *
  * Currently, this routine only supports responses consisting of a single 
ATP packet.
  * The I/O parameter block is allocated statically because the I/O may 
be  asynchronous,
  * thus the block must stay around after this routine exits.  Same goes 
for the BDS,
  * which gets filled in here.
  */
SendATPResp(ATPSendResp, Dest_NetAddr, SourceSkt, Resp, RespSize,
 atpRespBDS, TransID, asynch)
ATPBlock *ATPSendResp;    /* -> Statically allocated I/O parameter block 
*/
AddrBlock *Dest_NetAddr;  /* -> Destination network address for response 
*/
byte SourceSkt;  /* Local responding socket number */
char *Resp; /* -> response data */
unsigned short RespSize;  /* Length in bytes of response data */
BDS *atpRespBDS; /* Statically allocated Buffer Descriptor Scructure 
*/
unsigned short TransID;   /* ID of transcation being replied to */
short asynch;    /* Boolean defining whether or not it is async. */
 {
 unsigned short atpBDS();

 ATPSendResp->ioRefNum = atpRefNum;/* I/O is for .ATP driver */
 ATPSendResp->csCode = _atpSendResponse;     /* Function is "Send Response 
*/
 /*
   * Copy Requestor's net address into parameter block
   */
 bcopy(&((ATPSendResp->csParam).atpSendResponse.addr), Dest_NetAddr, 

 sizeof(AddrBlock));
 (ATPSendResp->csParam).atpSendResponse.skt = SourceSkt;       /* Responding 
Skt. */
 (ATPSendResp->csParam).atpSendResponse.bdsPtr = atpRespBDS;   /* Fill 
in -> BDS */
 (ATPSendResp->csParam).atpSendResponse.bdsSize = 1;           /* 1-packet 
resp. */
 (ATPSendResp->csParam).atpSendResponse.numOfBuffs = 1;        /* (same) 
*/
 (ATPSendResp->csParam).atpSendResponse.flags = atpEOM;        /* 1st 
has EOM */
 (ATPSendResp->csParam).atpSendResponse.transID = TransID;     /* 
 atpBDS(atpRespBDS, Resp, RespSize); /* Fill in the BDS */
 if(asynch) /* Only 1/0 legal in PBControl */
 PBControl(ATPSendResp, 1); /* Do it asynchronously */
 else
 PBControl(ATPSendResp, 0); /* Do it synchronously */
 return(ATPSendResp->ioResult);    /* Return result code */
 }

/*
  * GetATPRequest - Get an ATP Request
  *
  * Issue an ATP "GetRequest".  If a non-NULL completion routine address 
is supplied, issue the
  * request asynchronously.
  */
GetATPRequest(ATPGetReq, skt, ReqPkt, ReqPktSize, ioCompletion)
ATPBlock *ATPGetReq; /* Statically allocated I/O parameter block */
byte skt; /* Local responding socket on which to accept request */
byte *ReqPkt;    /* -> buffer to get filled in with request data */
unsigned short ReqPktSize;/* Size of request buffer, bytes */
ProcPtr ioCompletion;/* -> entry point of completion routine or NULL 
*/
 {
 ATPGetReq->ioRefNum = atpRefNum;  /* I/O is for .ATP driver */
 ATPGetReq->csCode = _atpGetRequest; /* Function is "Get Request" */
 (ATPGetReq->csParam).atpGetRequest.reqPtr = ReqPkt;     /* Fill in buffer 
data */
 (ATPGetReq->csParam).atpGetRequest.reqSize = ReqPktSize;
 (ATPGetReq->csParam).atpGetRequest.skt = skt;     /* Socket on which 
to receive req. */
 /*
   * Fill in completion routine address, and if non-NULL, issue asynch 
I/O otherwise
   * issue it synchronously.
   */
 if((ATPGetReq->ioCompletion = ioCompletion)) != NULL)   
 PBControl(ATPGetReq, 1);
 else
 PBControl(ATPGetReq, 0);
 return(ATPGetReq->ioResult); /* Return I/O result code */
 }

/*
  * Miscellaneous Low-Level Routines
 */

/*
  * GetReqComplete
  *
  * ATP Get Request Completion Routine simply posts an event with a unique 
event/message pair.
  * When the event is identified by the modal dialog filter procedure, 
a fortune is returned to the
  * requestor and another GetRequest is issued.  Registers must be preserved 
because this routine
  * runs asynchronously, and may interrupt some other process, including 
a local fortune fetch.
  * It's written in assembler 
  */
GetReqComplete()
 {
 #asm
 Movem.La0-a6/d0-d7,-(sp) ; Save registers
 Move.L _SavedA5,a5; Restore A5 context
 Move.W #MouseDown,-(sp)  ; Event type = Mouse Down
 Pea    ATPGetReq; Event message is pointer to GetReq block
 _PostEvent ; Post it
 Movem.L(sp)+,a0-a6/d0-d7 ; Restore registers
 #endasm
 }

/*
  * FilterGlue - Interface for ModalDialog Filter Proc. Callback
  *
  * This is a glue routine to get back into C.  It is called back from 
ModalDialog() with 
  * (naturally) Pascal-flavored arguments on the stack.  See the C Workshop 
in MacTutor
  * Vol. 1, No. 7 (June, 1985) and Inside Macintosh for more information 
on ModalDialog
  * event filter procedures.
  */
FilterGlue()
 {
 #asm
 ;
 ; Inputs (Pascal callfrom ModalDialog):
 ;      4(SP)      Address of word to fill in with item number
 ;      8(SP)      Address of the event record
 ;     12(SP)      Dialog (window) pointer
 ;
 Link   a6,#0    ; no local automatics
 Movem.Ld1-d7/a1-a4,-(sp) ; Save regs
 Move.L 8(a6),d0 ; D0 -> Item number word
 Move.L 12(a6),d1; D1 -> Event record
 Move.L 16(a6),d2; D2 -> Window record
 Jsr    filter   ; Call C for dirty work
 Movem.L(sp)+,d1-d7/a1-a4 ; Restore regs
 Unlk   a6; "standard" Pascal routine exit
 Move.l (sp)+,a0 ; A0 -> return point
 Addq.L #6,sp    ; Pop args
 Addq.L #6,sp
 Move.B d0,(sp)  ; Copy C result to Pascal return
 Jmp    (a0); Return
 #endasm
 }

/*
  * filter - "Real" ModalDialog filter function
  *
  * If there is a "phoney" mouse down event (with message = address of 
our GetReq block)
  * then we have received a fortune request.  In that case, send a fortune 
back to the requestor.
  */
filter(ip, ep, wp)
short *ip;/* -> Word to receive dialog item code */
EventRecord *ep; /* -> Event record */
WindowPtr wp;    /* -> Window record for modal dialog */
 {
 if(ep->what == mouseDown && ep->message == (long)&ATPGetReq)
 {
 SendFortune();  /* Send a responding fortune */
 *ip = 0; /* No item was hit */
 return(TRUE);   /* Indicate that we handled the event */
 }
 return(FALSE);  /* We didn't handle this event */
 }

/*
  * atpBDS- Setup an ATP Buffer Descriptor Structure.
  *
  * Given a buffer-load of data to send, fill in a BDS which describes 
the buffer as possibly 
  * several ATP packets.  Return the number of ATP packets required to 
send the data as
  * a response.
  */
unsigned short atpBDS(bds, buf, size)
BDS *bds; /* -> Buffer Descriptor Structure to fill in */
unsigned char *buf;/* -> Response data buffer */
short size; /* Size (bytes) of response data */
 {
 unsigned short i; /* Counts number of segments */
 
 i = 0;
 while(size > 0) /* Loop till enough packets set up */
 {
 bds->buffSize = (size > atpMaxData) ? atpMaxData : size;      /* Size 
of this packet */
 bds->buffPtr = buf; /* Fill in -> to this segment/packet */
 buf += atpMaxData;/* Advance segment pointer */
 size -= atpMaxData; /* Count down segment size */
 bds++; /* Advance BDS pointer to next seg. */
 i++;   /* Count a segment */ }
 return(i); /* Return segment count */
 }

/*
  * pstrcpy - Pascal String Copy routine.
  *
  * Returns number of bytes copied, including count byte.
  */
pstrcpy(d, s)
char *d;/* -> Destination string */
char *s;/* -> Source string */
 {
 bcopy(d, s, *s + 1);
 return(*s + 1);
 }

/*
  * bcopy -  General purpose byte copy routine.
  */
bcopy(d, s, n)
char *d;/* Destination address */
char *s;/* Source address */
short n;/* Number of bytes to copy */
 {
 #asm
 Move.L d0,a0    ; A0 -> Destination
 Move.L d1,a1    ; A1 -> Source 
 Bra.S  @1; Jump past to correct for dumb DBRA inst.
@0 Move.B (a1)+,(a0)+; Copy a byte
@1 Dbra.W d2,@0  ; Loop till done
 #endasm
 }

/*
  * SaveA5
  */
SaveA5()
{
#asm
 Lea    _SavedA5,a0  ; A0 -> Save cell 
 Move.l a5,(a0)     ; Save A5 
 Rts       ; Return
 
_SavedA5Dc.l0  ; Storage area for A5
#endasm
}
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Viber 11.9.1 - Send messages and make fr...
Viber lets you send free messages and make free calls to other Viber users, on any device and network, in any country! Viber syncs your contacts, messages and call history with your mobile device, so... Read more
Vallum 3.3.2 - $15.00
Vallum is a little tool that helps you monitor and block apps connections and throttle apps bandwidth. It is able to intercept connections at the application layer, and hold them while you decide... Read more
Microsoft OneNote 16.31 - Free digital n...
OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that's too important to forget. Whether you're at... Read more
Apple Pages 8.2.1 - Apple's word pr...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 6.2.1 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
f.lux 39.9873 - Adjusts the color of you...
f.lux makes the color of your computer's display adapt to the time of day, warm at night and like sunlight during the day. Ever notice how people texting at night have that eerie blue glow? Or wake... Read more
Deeper 2.5.0 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
NTFS 15.5.71 - Provides full read and wr...
NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on NTFS... Read more
MTR 5.3.0.0 - The Mac's oldest and...
MTR (was MacTheRipper)--the Mac's oldest and smartest DVD-backup app. MTR - the complete toolbox, not a one-trick, point-and-click extractor. MTR is intended for making fair-use, backup copies of... Read more
Keynote 9.2.1 - Apple's presentatio...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more

Latest Forum Discussions

See All

Black Desert Mobile gets an official rel...
Pearl Abyss has just announced that its highly-anticipated MMO, Black Desert Mobile, will launch globally for iOS and Android on December 11th. [Read more] | Read more »
Another Eden receives new a episode, cha...
Another Eden, WFS' popular RPG, has received another update that brings new story content to the game alongside a few new heroes to discover. [Read more] | Read more »
Overdox guide - Tips and tricks for begi...
Overdox is a clever battle royale that changes things up by adding MOBA mechanics and melee combat to the mix. This new hybrid game can be quite a bit to take in at first, so we’ve put together a list of tips to help you get a leg up on the... | Read more »
Roterra Extreme - Great Escape is a pers...
Roterra Extreme – Great Escape has been described by developers Dig-It Games as a mini-sequel to their acclaimed title Roterra: Flip the Fairytale. It continues that game's tradition of messing with which way is up, tasking you with solving... | Read more »
Hearthstone: Battlegrounds open beta lau...
Remember earlier this year when auto battlers were the latest hotness? We had Auto Chess, DOTA Underlords, Chess Rush, and more all gunning for our attention. They all had their own reasons to play, but, at least from where I'm standing, most... | Read more »
The House of Da Vinci 2 gets a new gamep...
The House of Da Vinci launched all the way back in 2017. Now, developer Blue Brain Games is gearing up to deliver a second dose of The Room-inspired puzzling. Some fresh details have now emerged, alongside the game's first official trailer. [Read... | Read more »
Shoot 'em up action awaits in Battl...
BattleBrew Productions has just introduced another entry into its award winning, barrelpunk inspired, BattleSky Brigade series. Whilst its previous title BattleSky Brigade TapTap provided fans with idle town building gameplay, this time the... | Read more »
Arcade classic R-Type Dimensions EX blas...
If you're a long time fan of shmups and have been looking for something to play lately, Tozai Games may have just released an ideal game for you on iOS. R-Type Dimensions EX brings the first R-Type and its sequel to iOS devices. [Read more] | Read more »
Intense VR first-person shooter Colonicl...
Our latest VR obsession is Colonicle, an intense VR FPS, recently released on Oculus and Google Play, courtesy of From Fake Eyes and Goboogie Games. It's a pulse-pounding multiplayer shooter which should appeal to genre fanatics and newcomers alike... | Read more »
PUBG Mobile's incoming update bring...
PUGB Mobile's newest Royale Pass season they're calling Fury of the Wasteland arrives tomorrow and with it comes a fair chunk of new content to the game. We'll be seeing a new map, weapon and even a companion system. [Read more] | Read more »

Price Scanner via MacPrices.net

New 2019 16″ MacBook Pros on sale for $100 of...
Apple Authorized Reseller Adorama has new 2019 16″ MacBook Pros on sale today for $100 off Apple’s MSRP, each including free shipping. In addition, Adorama charges sales tax for NY & NJ residents... Read more
Apple Watch Series 3 GPS models on sale for l...
Amazon has Apple Watch Series 3 GPS models on sale starting at only $179. There prices are the lowest we’ve ever seen for these models from any Apple reseller. Choose Amazon as the seller rather than... Read more
iOS Bug In Facebook News Feed Lets Device Ca...
NEWS: 11.15.19- Users of the Facebook social media platform’s mobile app running on iOS devices won’t, like, this piece of news one bit in where a bug in the News Feed gave access to the camera... Read more
16″ MacBook Pros on sale! Preorder at Amazon...
Apple’s new 16″ MacBook Pros were only introduced yesterday, but Amazon is already offering a $100 discount on preorders. Prices for the base 6-Core 16″ MacBook Pros start at $2299: – 2019 16″ 2.6GHz... Read more
Use our exclusive MacBook Price Trackers to f...
Our Apple award-winning MacBook price trackers are the best place to look for the best sales & lowest prices on new and clearance MacBook Airs and MacBook Pros–including Apple’s new 16″ MacBook... Read more
New November Verizon iPhone deal: Get an iPho...
Verizon has the 64GB iPhone Xr on sale for 50% off for a limited time, plus they will include a free $200 prepaid MasterCard and a free Amazon Echo Dot. That reduces their price for the 64GB iPhone... Read more
Apple cuts prices on clearance, refurbished 2...
Apple has clearance 2018 15″ 6-Core Touch Bar MacBook Pros, Certified Refurbished, now available starting at only $1829. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Up to $450 price drop on clearance 15″ MacBoo...
B&H Photo has dropped prices Apple’s 2019 15″ 6-Core and 8-Core MacBook Pros by $400-$450 off original MSRP, starting at $1999, with free overnight shipping available to many addresses in the US... Read more
Here’s how to save $200 on Apple’s new 16″ Ma...
Apple has released details of their Education discount associated with the new 2019 16″ 6-Core and 8-Core MacBook Pros. Take $200 off the price of the new 8-Core model (now $2599) and $200 off the 16... Read more
Price drop! 2019 15″ 2.6GHz 6-Core MacBook Pr...
Focus Camera has dropped their price for clearance 2019 15″ 2.6GHz 6-Core Space Gray MacBook Pros by $400 to $1999 shipped. Apple’s original MSRP for this model was $2399. Focus charges sales tax for... Read more

Jobs Board

Best Buy *Apple* Computing Master - Best Bu...
**746655BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Store NUmber or Department:** 002518-Atlantic Center-Store **Job Description:** Read more
*Apple* Mobility Pro - Best Buy (United Stat...
**744973BR** **Job Title:** Apple Mobility Pro **Job Category:** Store Associates **Store NUmber or Department:** 000949-Rochester Hills-Store **Job Description:** Read more
AV Systems Engineer at *Apple* - Theorem, L...
Job Summary Apple Retail Technology is looking for an Audio Visual Systems Engineer to design and implement scalable, next-generation A/V solutions for Apple ?s Read more
Nurse Practitioner - Field Based (San Bernard...
Nurse Practitioner - Field Based (San Bernardino, CA, Apple Valley, Hesperia) **Location:** **United States** **New** **Requisition #:** PS30312 **Post Date:** 3 Read more
Best Buy *Apple* Computing Master - Best Bu...
**746510BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Store Associates **Store NUmber or Department:** 001407-Milford-Store **Job Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.