User Services
Security (Locks & Keys)
As explained in Sysop’s Guide, security on the Major BBS is controlled at the foundation level by Locks and Keys.
Keys are simply strings of from 3 to 15 ASCII characters, in most cases Sysop-editable. Each user has a class keyring and an individual keyring. Keyrings record the list of keys which the Sysop has assigned to that user, either by assigning the user to a particular class or by assigning the user a key on an individual basis.
Locks, meanwhile, are decision points written into the code. A lock examines each user who encounters it, testing to see if the user carries the key which it has been assigned to look for. If the user carries that key, the lock allows him to pass. If the user does not carry that key, the lock keeps the user from accessing whatever feature it is guarding. A feature can have one or zero locks.
Locks can be built into modules such as File Libraries and Forums, but most locks appear as CNF options located in Security & Accounting (choice 3 on the Introductory Menu).
Here is the most versatile routine for testing whether an online user has a specific key or not:
ok=gen_haskey(lock,unum,uptr);
Does this user have the key to this lock?
int ok; 1=yes, let him in 0=no, deny access
char *lock; Name of lock on feature / key required
int unum; User number of online user
struct user *uptr; User structure pointer of online user
What follows are some handy variations and alternatives to gen_haskey() that you’ll probably use more often:
ok=hasmkey(msgnum); Does the user have the key specified in this Security & Accounting CNF option?
int ok; 1=yes, let him in 0=no, deny access
int msgnum; Number of the CNF option
This routine checks whether the current user has a key specified by the Sysop in a Security & Accounting CNF option. See page 79 for creating CNF options. You could make a Security & Accounting CNF option that looks something like this key:
SAMPKY Key required to log on to reserved channels NORMAL
Now the Sysop can change this option so that another key is required. All you have to do is:
if (hasmkey(SAMPKY)) {
welcomemyfriend();
}
else {
sorrynotachance();
}By convention, all security-related CNF options are stored in level 3 — Security & Accounting. If you specify any locks of your own here, we recommend that you use one of the four pre-defined lock names for the default values of your option when you can:
DEMO Everybody gets this key, it’s the only one new sign-ups get
NORMAL Approved users
SUPER Supervisors or trusted assistants
SYSOP Top-level access to the Major BBS server
This routine checks if the current user has the specified key.
ok=haskey(lock); Does the user have this key?
int ok; 1=yes, let him in 0=no, deny access
char *lock; Name of lock on feature / key required
For quicker response, store the string in memory with stgopt() and use haskey() instead of reading it each time you need it with hasmkey().
ok=othkey(lock); Does the other user have this key?
int ok; 1=yes, let him in 0=no, deny access
char *lock; Name of lock on feature / key required
This routine checks if the user specified by othusn (user number) and othusp (pointer to user data structure) has a certain key. You can call this routine right after you call instat(), onsys(), or onsysn() (see page 112).
ok=uidkey(uid,lock); Does the (offline) user have this key?
int ok; 1=yes, let him in 0=no, deny access
char *uid; User-ID
char *lock; Name of lock on feature / key required
This routine checks on the access capabilities of a user who is not online at the time.
ok=uhskey(uid,lock); Does the user have this key?
int ok; 1=yes, let him in 0=no, deny access
char *uid; User-ID
char *lock; Name of lock on feature / key required
This routine is universal — it will tell you if the user has this key, and it will work whether the user is online or not.
Registerable Pseudo-Keys
You can create your own pseudo-keys for users. Say you want to give users access to some feature based upon something. The standard method of locks and keys allows Sysops to make up key names and issue keys either directly to individual users, or to classes of users via the class keyring. But some situations require more flexibility. For example, the _PORT#xx pseudo-key implicitly gives each user a special key based upon the channel number he uses for his current session.
Here’s the corresponding pseudo-key routine from MAJORBBS.C:
STATIC int
prtpsk(unum,lock) /* validate the _PORT# pseudo-key */
int unum; /* user number, 0 to nterms-1 */
char *lock; /* lock name that the key is for */
{
int chn;
sscanf(lock,"_PORT#%x",&chn);
return(channel[unum] == chn);
}Applies to: WG3.x
Header check:
STATICis not defined in WG3.2 (WG2GCOMM.H:257); writestatic(chapter 2 note).
And here’s how it gets registered:
register_pseudok(prefix,rouputr);
Register a pseudo-key routine
char *prefix; prefix of the pseudo-key
int (*rouptr)(unum,lock); pointer to handler routine
Editor's note (not part of Fountain's text): The parameter list in the heading line above,
register_pseudok(prefix,rouputr), is a typo in the original guide: the declaration below it names the handlerrouptr. In the actual engine header the declaration isregister_pseudok(char *pskbeg, int (*pskrou)(int unum,char *lock)). (Source: analysis/wg1/FINDINGS.md.)
int unum; user number being checked
char *lock; full name of the key required
For example:
register_pseudok("_PORT#",prtpsk);The registration call says in effect “If anyone asks about users having a key that starts with _PORT#, then let me make the determination”. Now suppose there’s some code somewhere like this:
haskey("_PORT#2C");Then prtpsk() swings into action and determines whether this user happens to be on channel 2C hexadecimal or not.
See MAJORBBS.C for the other pseudo-key routines for channel group number, spoken language, and terminal protocol.
By convention, and for Sysop sanity, all pseudo-keys start with the under_score character, but nothing enforces this.
Accounting (Credits)
User connect time can be controlled or measured with the system commodity called “credits”. Credits typically refer to seconds of privileged connect time: If an “approved” user is online for an hour he consumes 3600 credits. A new user doesn’t consume credits and can’t access many of the features of the system.
There are many other ways credits are used. Certain actions “cost” the user a fixed amount of credits. And credit consumption can vary depending on what service the user is in.
Charging Users
To charge a user credits, you can make use of the dedcrd() and tstcrd() routines in ACCOUNT.C:
| Credit testing and charging routines | Actually deducts credits? | Subtract credits if user is exempt from credit charges? | Automatically borrow credits if user can go into debt? | User |
| dedcrd() | Yes | No | Yes | Current |
| rdedcrd() | Yes | Yes | No | Current |
| odedcrd() | Yes | Optional | Optional | Any Online |
| ndedcrd() | Yes | Optional | Optional | Any Offline |
| ldedcrd() | Yes | Optional | Optional | Any |
| gdedcrd() | Yes | Optional | Optional | Any |
| tstcrd() | No | No | Yes | Current |
| rtstcrd() | No | Yes | No | Current |
| otstcrd() | No | Optional | Optional | Any Online |
| ntstcrd() | No | Optional | Optional | Any Offline |
| ltstcrd() | No | Optional | Optional | Any |
| gtstcrd() | No | Optional | Optional | Any |
The bolded routines are those you’ll likely put to the most use.
All of the dedcrd() routines return 1 if sufficient credits were available, or 0 if there weren’t enough. The last parameter, asmuch, decides what to do if there weren’t enough: 1=take whatever the user has, reducing his balance to the minimum, or 0=don’t take anything.
The tstcrd() routines act just like the corresponding dedcrd() routines, except that no credits are actually deducted. Use the tstcrd() routines if you need to specially handle the case of insufficient credits before any are deducted (for example by exiting a service or issuing a warning).
enuf=dedcrd(amount,asmuch);
Deduct credits from current user’s account
int enuf; 1=had enough, 0=didn’t
long amount; number of credits to deduct
int asmuch; if not enough: 1=take all, 0=none
enuf=rdedcrd(amount,asmuch);
Deduct real credits from online account
int enuf; 1=had enough, 0=didn’t
long amount; number of credits to deduct
int asmuch; if not enough: 1=take all, 0=none
enuf=odedcrd(unum,amount,real,asmuch);
Deduct credits from an online account
int enuf; 1=had enough, 0=didn’t
int unum; user number
long amount; number of credits to deduct
int real; 1=don’t put into debt
int asmuch; if not enough: 1=take all, 0=none
enuf=ndedcrd(userid,amount,real,asmuch);
Deduct credits from an offline account
int enuf; 1=had enough, 0=didn’t
char *userid; User-ID
long amount; number of credits to deduct
int real; 1=don’t put into debt
int asmuch; if not enough: 1=take all, 0=none
enuf=ldedcrd(uptr,amount,real,asmuch);
Deduct credits from an “active” user account structure residing in memory
int enuf; 1=had enough, 0=didn’t
struct usracc *uptr; pointer to active user structure
long amount; number of credits to deduct
int real; 1=don’t put into debt
int asmuch; if not enough: 1=take all, 0=none
enuf=gdedcrd(userid,amount,real,asmuch);
Deduct credits from any user’s account
int enuf; 1=had enough, 0=didn’t
char *userid; User-ID
long amount; number of credits to deduct
int real; 1=don’t put into debt
int asmuch; if not enough: 1=take all, 0=none
enuf=tstcrd(amount);
Test if user has enough credits
int enuf; 1=had enough, 0=didn’t
long amount; number of credits (don’t deduct)
enuf=rtstcrd(amount);
Test if user has enough real credits
int enuf; 1=had enough, 0=didn’t
long amount; number of credits (don’t deduct)
(won’t take debt or exemptions into account)
enuf=otstcrd(unum,amount,real);
Test if user has enough credits
int enuf; 1=had enough, 0=didn’t
int unum; user number
long amount; number of credits (don’t deduct)
int real; 1=don’t take debt or exemptions into account
enuf=ntstcrd(userid,amount,real);
Test if offline user has enough credits
int enuf; 1=had enough, 0=didn’t
char *userid; User-ID
long amount; number of credits (don’t deduct)
int real; 1=don’t take debt or exemptions into account
enuf=ltstcrd(uptr,amount,real);
Test if user account structure has enough credits
int enuf; 1=had enough, 0=didn’t
struct usracc *uptr; pointer to active user structure
long amount; number of credits (don’t deduct)
int real; 1=don’t take debt or exemptions into account
enuf=gtstcrd(userid,amount,real);
Test if any user has enough credits
int enuf; 1=had enough, 0=didn’t
char *userid; User-ID
long amount; number of credits (don’t deduct)
int real; 1=don’t take debt or exemptions into account
Credit Consumption Rate
To change a user’s credit consumption rate, you can set usrptr->crdrat to the credits to consume per minute. For example:
usrptr->crdrat=120; /* consume credits at twice the normal rate */
Whenever a user exits a module of the Major BBS, his credit consumption rate is restored to the default value (as specified by the Sysop in the MMUCRR CNF option located in Security & Accounting).
Global Commands
Global commands are commands that users can enter from almost any prompt on the Major BBS. One exception: you can’t use global commands while inside the Full Screen Editor. Making your own global command means two things: making a handler routine, and registering the routine. The handler routine intercepts every line of user input and, if it recognizes your special global command, responds to it and returns true (otherwise returns false). Registering the routine allows the mainline program to call it with each line of user input.
The handler routine has at its disposal all the global variables associated with line input, including margc, margv, input, and so on (see page 103), in addition to global variables for user session information such as usrptr->, and usaptr-> fields (see USRACC.H and MAJORBBS.H).
Important: The global command should be coded efficiently. It must very quickly reject user input (return false) when it doesn’t recognize the command. For example, the global command handler should probably never access a database in the quiescent (return false) case.
Here’s an example of a global command called /now to tell the time of day:
int
glotime(void) /* global command for telling the time of day */
{
if (margc == 1 && sameas(margv[0],"/now")) {
prf("At the tone, the time will be %s\7\r",nctime(now()));
outprf(usrnum);
return(1);
}
return(0);
}Applies to: WG3.x
const CHAR * vs CHAR * hazard.
ncdate()andnctime()returnconst CHAR *in WG3.2 (DNTAPI.H:209,217; WG2 returnedchar *). Passing them toprf()/prfmsg()as%sarguments, as here, is fine. Assigning the result to a plainCHAR *, writing through it, or returning it from aregister_textvar()routine is not: declare the receiverconst CHAR *or copy it out first. The result points into a library-local buffer that the next call overwrites.
Some check like margc == 1 is necessary because margv[0] is undefined when margc == 0. More generally, margv[n] is undefined when margc <= n. The sameas() check is case insensitive so users can also type /NOW. The routine returns a 1 if it recognizes the user’s input as the global command it’s looking for, or a 0 if it does not.
Here are all the possible return values for the global command handler:
0 Command not recognized. Executive will pass entire command on to some module’s input handler (sttrou(), lonrou(), or lofrou(), as appropriate). Important: You must always return 0 when you don’t recognize the incoming command, and especially when margc == 0*.*
1 Command recognized and processed. Executive will ask the module in effect to reprompt by simulating a cr from the user, calling the module’s sttrou(), lonrou(), or lofrou() routine with margc == 0. The (usrptr->flags&INJOIP) flag will be set so the routine can recognize this condition. If you have any prf() or prfmsg() output, you must do an outprf(usrnum) before you return the 1 (as in the glotime() routine, above).
-1 Command recognized and processed — don’t reprompt. Executive will not reprompt the user. This is also a return value where no outprf() is likely to take place unless you do it yourself.
-2 Command recognized and processed — don’t reprompt, but do prf() or prfmsg(). Executive will not ask the module to reprompt, but it will assume you have something in the prfbuf and will do an outprf() for you.
You can look at the hdlinp() routine in MAJORBBS.C for exactly how these return values are used.
The next step is registering the global command as part of your initialization routine (page 42):
int glotime(void); /* this is the prototype */
:
:
void EXPORT
init__myroutine() /* the module initialization routine */
{
:
globalcmd(glotime);
:
}Tip: The global command feature has possible utility beyond defining global commands for users. For example, you could make a routine to intercept all user input for diagnostic or management purposes.
You can define up to 50 global command handler routines using this function:
globalcmd(rouptr) define global command handler routine
int (*rouptr)(); pointer to routine
All global command handlers can be temporarily disabled for a channel by setting the special NOGLOB flag, as in:
usrptr->flags¦=NOGLOB;and later cleared with:
usrptr->flags&=~NOGLOB;This is done during teleconference chat modes, for example.
Here are a few examples of global commands and where they’re coded:
| Command | Purpose | Source code |
| /R <userid> | registry report | REGISTRY.C |
| /P <userid> <message> | page | MJRTLC.C or ENTTLC.C |
| /# | who’s online | MAJORBBS.C or ENTTLC.C |
| /L <userid> | lookup user account | MAJORBBS.C |
| /INVIS | invisible Sysop | MAJORBBS.C |
| /GO <page-name> | global Menu Tree “GO” | MAJORBBS.C and MENUING.C |
| /RECENT | recent logoffs | MAJORBBS.C |
The following commands are not registered global commands. These are special commands available from all menu pages:
| Command | Purpose | Source code |
| FIND | Search menu pages | MENUING.C and MAJORBBS.C |
| DISABLE (Sysop only) | Disable a page | MENUING.C and MAJORBBS.C |
| ENABLE (Sysop only) | Enable a page | MENUING.C and MAJORBBS.C |
Full Screen Editor
The Full Screen Editor is a sub-service used by Electronic Mail and Forums for message editing. It allows a user to edit a block of text of a certain number of 80-column lines. See Sysop’s Guide for instructions on using the editor from the user’s point of view.
There are actually two editors, the Full Screen Editor and the Line Editor that depend on whether the user’s terminal has ANSI capability or not. Fortunately for developers, this distinction is transparent. The bgnedt() routine will make use of what the Major BBS server already knows about the user’s terminal, and fire up the appropriate editor.
bgnedt(siz,buf,tsiz,topic,whndun,flags);
begin editing a message
int siz; max size of text
char *buf; buffer for text
int tsiz; max size of topic (including nul)
char *topic; buffer for topic (NULL if no topic)
int (*whndun)(int quitex);
routine to call when done editing
int flags; special editor option bits
An excerpt from MAJORBBS.H, defining the bits of the last parameter:
/* flags that can be passed to bgnedt() */
#define ED_READON 2 /* "read only" mode */
#define ED_CLRTOP 4 /* clear topic buffer upon entry */
#define ED_CLRTXT 8 /* clear text buffer upon entry */
#define ED_FILESD 16 /* use "file" flavor of editor */
#define ED_LINEMO 32 /* force use of the line editor */
#define ED_FIXTOP 64 /* don't allow changing of the topic field */Note: the ED_FILIMP flag that appears in MAJORBBS.H is not supported.
Call bgnedt() to allow the user to begin entering text. Make the siz parameter a multiple of 80 bytes plus 1: only an integral number of 80-column lines will be available to the user. The buffer should be somewhere that will stay active and available throughout the editing process. A subset of the Volatile Data Area is ideal for this — just make sure you’ve allowed enough room with dclvda(). If you want a topic field, allocate another buffer for it (up to 51 bytes long) that has the same durability (for example, another portion of the VDA).
After you call bgnedt(), the editor will usurp your state and substate code for the entire editing session. That means, for example, that your module’s hang-up entry point, huprou(), will get called with the editor’s state in effect in the event that the user hangs up while still in the editor.
If you want to detect that condition (and the editor is active on the channel due to your module’s invocation, of course), you need to set it up somehow. Remember that your huprou() entry point will be called regardless of what state or module the user is in. You can detect that the user was editing on your behalf by setting a flag when you call bgnedt() and clearing it when your (*whndun)() routine gets called.
edtimr(imradr); specify import message routine
int (*imradr)(); address of import message routine
got=(*imradr)(msgno); call to import routine (“New” command)
int got; 1=message imported 0=error
long msgno; number of message to import (user typed this in)
The editor may be set up to allow users to import other messages into the message that they are editing. This is done by calling the edtimr() routine immediately after calling bgnedt(). Then when a user presses ctrl+N for New in the editor, he can import another message. The imradr routine is passed the message number specified by the user, and is expected to do the actual import by filling the editor buffer, and possibly setting the topic and other items.
Your (*whndun)() routine must restore your state and substate (usrptr->state and usrptr->substt) to values for your own module, and prompt the user for the next action (the next question after the editor is over).
The (*whndun)() routine is passed one of these values:
0 user wants to save the editing he’s done
ED_QUITEX user wants to quit and abandon the results of his editing
You should check this flag to see if your code should save the buffer or discard it. You must remember where the buffer is, it’s what you passed to bgnedt() in the buf parameter.
The return value of (*whndun)() can be one of these:
1 Ok, exiting the editor
(I’ve restored my state and substate and prompted the user).
0 Exit the editor, and exit this module too (your sttrou() should return 0, and we should exit to the parent menu).
An example of a Sysop Feedback Forum using the Full Screen Editor:
/***************************************************************************
* GALFBK.C *
* *
* Copyright (C) 1989-1995 GALACTICOMM, Inc. All Rights Reserved. *
* *
* Feedback to Sysop (sample module discussed in the *
* Developer's Guide for the Major BBS) *
* - RNStein *
* *
***************************************************************************/
#include "gcomm.h"
#include "majorbbs.h"
#include "galfbk.h"
STATIC int fbkinp(void);
STATIC int fbkdun(int flags);
STATIC void fbkfin(void);
int fbkstt; /* Feedback module state number */
FILE *fbkmb; /* feedback configuration variables */
FILE *fbkfp; /* feedback text file */
struct module fbkmodule={ /* module interface block */
"", /* name used to refer to this module */
NULL, /* user logon supplemental routine */
fbkinp, /* input routine if selected */
dfsthn, /* status-input routine if selected */
NULL, /* "injoth" routine for this module */
NULL, /* user logoff supplemental routine */
NULL, /* hangup (lost carrier) routine */
NULL, /* midnight cleanup routine */
NULL, /* delete-account routine */
fbkfin /* finish-up (sys shutdown) routine */
};
#define TPCSIZ 40 /* maximum characters in topic */
#define FBKSIZ 1921 /* maxchars in feedback(for 24 lines)*/
struct fbkusr { /* feedback to Sysop user data block */
char text[FBKSIZ]; /* text buffer */
char topic[TPCSIZ]; /* topic buffer */
};
#define fbkptr ((struct fbkusr *)vdaptr)Applies to: v10
TPCSIZhere is this sample's own define (40). The engine'sTPCSIZis 51 (GME.H:48, unchanged from WG3.2). The 41 of the old C teleconference header (ENTTLC.H:32) is not a v10 symbol: that header is not shipped. Do not#define TPCSIZyourself in a module that includesGME.H. See chapter 29, section 29.8.
Applies to: WG3.x
Header check:
opnmsg()returnsHMCVFILE, notFILE *(MCVAPI.H:54); declarefbkmbasHMCVFILE(see chapter 3).
void EXPORT
init__feedback() /* initialize feedback stuff */
{
stzcpy(fbkmodule.descrp,gmdnam("GALFBK.MDF"),MNMSIZ);
fbkstt=register_module(&fbkmodule);
fbkmb=opnmsg("GALFBK.MCV");
dclvda(sizeof(struct fbkusr));
}
STATIC int
fbkinp(void) /* feedback handler */
{
setmbk(fbkmb);
if (margc == 1 && sameas(margv[0],"X")) {
return(0);
}
do {
bgncnc();
switch(usrptr->substt) {
case 0:
cncchr();
prfmsg(HELLO);
outprf(usrnum);
bgnedt(FBKSIZ,fbkptr->text,
TPCSIZ,fbkptr->topic,fbkdun,ED_CLRTOP+ED_CLRTXT);
break;
}
} while (!endcnc());
outprf(usrnum);
return(1);
}
STATIC int
fbkdun( /* feedback editing when-done */
int quitex)
{
char *cp;
usrptr->state=fbkstt;
setmbk(fbkmb);
if (quitex == 0) {
for (cp=fbkptr->text ; *cp != '\0' ; cp++) {
if (*cp == '\r') {
*cp='\n';
}
}
if ((fbkfp=fopen("GALFBK.TXT",FOPAA)) == NULL) {
catastro("Cannot open GALFBK.TXT for append!");
}
fprintf(fbkfp,"*** From %s on %s at %-5.5s %s\n%s\n\n\n",
usaptr->userid,ncdate(today()),nctime(now()),
fbkptr->topic,fbkptr->text);
fclose(fbkfp);
prfmsg(THANKS,usaptr->userid);
outprf(usrnum);
}
return(0);
}STATIC void
fbkfin(void) /* feedback shutdown */
{
clsmsg(fbkmb);
}Here are the Text Block CNF options which go with this example:
esc represents the Escape character, ASCII 27.
LEVEL6 {}
HELLO {esc[0;1;32m
Hello, and welcome to the Sysop Feedback Forum. This service is
provided to encourage your comments and criticisms.
When you are done typing, you can hit esc[37m<Ctrl-G>esc[32m to
save your comments.
} T Feedback welcome message
THANKS {esc[0;1;32m
Thank you for taking the time to leave your comments,
esc[33m%sesc[32m!
} T Feedback thanks for commentsThis source code and all support files are available on the Galacticomm Demo System, (305) 583-7808, in a file named GALFBK.ZIP.
When a user selects this service, he is introduced to it with the HELLO{} message, and a (N)onstop, (Q)uit or (C)ontinue? choice. Then he enters the Full Screen Editing mode, where he types in a topic and a message. When the user presses ctrl+G, the topic and message (along with other information) are appended onto the end of the text file GALFBK.TXT. The Sysop can periodically read this file and delete it.
struct module fbkmodule
This module structure defines the text-line input entry point fbkinp(), the standard system default status handler dfsthn(), and a shutdown routine fbkfin().
struct fbkusr
This is the structure template for this module’s use of the Volatile Data Area. The body and topic of the feedback will be stored here. The fbkptr macro casts vdaptr into a pointer to an fbkusr structure, for convenient coding.
init__feedback()
This initialization routine registers the feedback module and opens the GALFBK.MCV file with the text blocks for the module. The call to dclvda() declares this module’s requirements for the size of the Volatile Data Area.
fbkinp()
This is the input text line handler for the module. It is coded with the standard command concatenation and X-to-exit features, although neither of them are actually used. They’re in there to make it easier for you to edit this source code into a module of your own. But the only action happening in fbkinp() is that when the user enters the module, he’s greeted and then shuffled straight off to the Full Screen Editor.
fbkdun()
This function is the when-done routine associated with the module’s invocation of bgnedt(). Notice that it’s identified in the bgnedt() call. If the user did not ctrl+O quit the editing, then the text is written to disk. First the \r line-terminators that the FSE uses are translated into the \n line-terminators that fprintf() likes. Then the file GALFBK.TXT is opened in append-ASCII mode. Then the User-ID, date, time, topic and message body are written to the file. Finally the user is thanked for his efforts. Returning 0 means to return to the parent menu page, as opposed to staying in this module.
Full Screen Data Entry
FSD can perform the following functions:
Display dataEnter data, full-screen modeEnter data, linear modeFull-screen entry mode requires ANSI capability and a large enough user screen to hold the entire template. Data displaying, or linear entry, can take place whether the user has ANSI capability or not. To use FSD with the Major BBS, you’ll need to create these:
Template (in .MSG file, level 99)Field specification string (usually in memory)Memory for the session’s variable-length data structuresDefault answer string (usually created on the fly)Field-verification routine (optional)When-done routine (process answers, restore state/substate)Calls to FSDBBS.C routinesProcedure:
1. Create a Template in an .MSG file. (See UEDANSI{} in BBSSUP.MSG for an example. See FSD.H for a complete definition of the template format. FSDBBS will automatically translate to \r\n terminators.) You will probably have a different template for ANSI users than for non-ANSI users.
2. Make a permanent copy of a Field Specification String in memory. See uinfsp[] in UINFED.C for an example. See FSD.H for the complete specifications of this format also.
3. Find out how much memory to allocate. Make a call like this if the template is for an entry session
nbytes=fsdroom(tmpmsg,fldspc,0);but make a call like this if the template is for displaying:
nbytes=fsdroom(tmpmsg,fldspc,-1);Make a call like this from your init__routine() and identify the above Template and Field Specification strings (after opening the appropriate .MCV file of course). This will tell you the size of the region you must provide to support data entry or display. Call fsdroom() for all templates/field specification combinations you will be using to make sure you’ll have enough room for all of them.
4. Allocate the space fsdroom() requires. You can use dclvda() to put it in the Volatile Data Area. By the way, fsdroom() will need to be called again, immediately before the display or entry session begins.
5. Format your default or original answers into an Answer String or use "" to default to all blank. See the use of uinfmt[] in UINFED.C for an example. See FSD.H for the specifications of an answer string. The answer string can come from getmsg(), but it cannot be in the prfbuf. vdatmp is a good candidate, making sure it’s big enough. Be sure to use only legal values in your default answer string (per your own field specifications string and validation routine).
Applies to: WG3.x
Header check:
getmsg()remains available as a macro forgetMsgBlk()(GCOMM.H:195).
6a. To display data call:
fsdroom(tmpmsg,fldspc,-1);
fsdapr(sesbuf,seslen,answers);
fsddsp(fsdrft());6b. To begin a full-screen entry session, call:
fsdroom(tmpmsg,fldspc,1);
fsdapr(sesbuf,seslen,answers);
fsdrhd(title);
fsdbkg(fsdrft());
fsdego(fldvfy,whndun);6c. To begin a linear entry session, call:
fsdroom(tmpmsg,fldspc,0);
fsdapr(sesbuf,seslen,answers);
fsdego(fldvfy,whndun);Notes:
Fields are numbered 0 to N-1. How do you tell FSD what N is? N is computed from the field specs by fsdroom() and stored in fsdscb->numfld. The number of fields that are also represented in the template is fsdscb->numtpl, which usually equals but never exceeds N. You can’t display or enter a field outside the range 0 to fsdscb->numtpl-1.
tmpmsg is the code for the template stored in the level 99 option in the .MSG file.
For entry sessions, you can supply a custom field-verification routine. Remember that fsdroom() in step 6 outputs a bunch of stuff to the prfbuf. This stuff must be untouched between the fsdroom() and fsdapr() calls.
The results of fsdapr() are all in the sesbuf. The seslen parameter is the size of sesbuf. This means that after calling fsdroom() and fsdapr(), you can call the other routines (fsddsp(), fsdrft(), fsdrhd(), fsdbkg(), fsdego()) any time later and in any order as long as you maintain the sesbuf passed to fsdapr().
If you have any prf’ing you want to show up immediately before the entry/display, be sure and do it after the call to fsdapr(), which leaves the prfbuf empty.
vdaptr, or a subset of vdaptr, is a good thing to use for sesbuf.
The (*whndun)() routine must restore your usrptr->state and usrptr->substt codes, as well as handle the end of the session.
The title in fsdrhd() is only for smooth operation for RIPscrip users — this should simply be a character string title for viewing above the entry screen. For example, Contact Database.
Avoiding Fields
If your program needs to conditionally blank out some fields in the display, you need to (1) modify the template, and (2) flag the appropriate fields as avoid. For (1), use the tpwipe() routine on the results of fsdrft() (before passed to fsddsp()) to modify the supporting text for the appropriate fields of the template. For (2), set the FFFAVD flag for the fields to be avoided (see FSD.H) after calling fsdapr().
For example, to display all data but blank out field 5 and some of the supporting text surrounding field 5, you could code something like:
char *tp; fsdroom(tmpmsg,fldspc,0);
fsdapr(sesbuf,seslen,answers);
tp=fsdrft();
tpwipe(tp,5,1,1);
fsdscb->flddat[5].flags¦=FFFAVD;
fsddsp(tp);This works almost identically for avoiding fields in a full screen entry mode, except you need to intercept things before fsdbkg() is called (instead of before fsddsp()). On the other hand, to show a protected field that the user can see but can’t change, the FFFAVD flag should be set after fsdbkg() is called, but before fsdego(), and don’t call tpwipe() at all.
In linear entry mode, you just need to set the FFFAVD flag for the appropriate fields after calling fsdapr().
Getting Answers After a Session
After an entry session is over there are a few ways to get the answers. See FSD.H for more details.
stg=fsdnan(fldno); Get a field’s answer
char *stg; pointer to answer
int fldno; field number 0 to N-1
fsdfxt(fldno,buffer,maxlen);
Store answer for field into buffer
int fldno; field number 0 to N-1
char *buffer; store the answer here
int maxlen; don’t use more than this many bytes
index=fsdord(fldno); Find index of multiple choice answer. Returns -1 if the answer was not one of the alt=’s.
int index; the index, 0 to N-1, for the answer according to the N possible alt= alternate values for the field
int fldno; field number 0 to N-1
Handling Answers at Other Times
After a session, the data structures allocated by fsdapr() allow quick access to pieces of the answer string. But at other times, the following routines from FSD.C can be used to deal with answer strings (see FSD.H for more details):
length=stranslen(answers);
Find length of an answer string
int length; length including final double \0.
char *answers; answer string
value=fsdxan(answers,name);
Get the value of a field in an answer string, returning "" if not found.
char *value; pointer to answer string value
char *answers; answer string
char *name; name of field
fsdpan(answers,name,value);
Put a new field and/or value into an answer string.
char *answers; answer string
char *name; name of field
char *value; pointer to answer string’s new value
fsddan(); Delete the answer just found by fsdxan()
Here’s an example of creating an answer string from scratch using sprintf():
sprintf(answers,"NAME=%s%cRANK=%s%cSERIALNO=%s%c",name,'\0',
rank,'\0',
serno,'\0');For an example of a simple module that uses Full Screen Data Entry, download the file GALCTX.ZIP from the Galacticomm Demo System at (305) 583-7808.
File Transfer
Uploads
Assuming that you’ve already taken care of all interactive aspects of your application (if you haven’t, see about creating interactive modules on page 42), then here are the steps to add file uploading capability:
1. In your source code, include the following special-purpose header file:
#include "filexfer.h"2. Code your own upload handler routine. The upload handler routine includes all the ways that the file transfer service will be asking you for assistance after you’ve turned control over to it. This is most of the work, and it’s discussed in detail below.
3. Call fileup() when you want to begin an upload, or to present the user with his protocol choices.
fileup(filnam,prot,fuphdl);
File upload
char *filnam; name of file (""=multi)
char *prot; protocol code
int (*fuphdl)(int fupcod));
upload handler routine
The filnam parameter is only used for indicating single file ("FILENAME.EXT") or multiple files (""), and for inclusion in some user prompts. Your upload handler routine will have to come up with the full file path in the FUPPTH, FUPBEG, and FUPEND cases. If you do get a filename in ftfscb->fname, it came from the protocol, otherwise you’ll get "". Invalid values for prot are handled appropriately, so you can pass unedited user input in the protocol parameter. The last parameter to fileup() is the address of your upload handler routine.
Calling fileup() usurps your state and substate (usrptr->state and usrptr->substt). It’s up to your FUPFIN exit point to restore them (more on this subject later).
Upload Protocol Codes
single-file: A M C 1 V
single-file or multi-file: B G Z K
to log off after uploading: append ! to any of the above
menu of upload protocols: ? or ""
To validate an upload protocol code, you could use valupc():
ok=valupc(prot); Is this a valid upload protocol?
int ok; 1=valid, 0=invalid
char *prot; protocol code string
Upload Handler Routine
This routine is a collection of what we call exit points. After your special-purpose module hands control over to the general-purpose file transfer service, FTF, there are several cases when FTF is going to need to consult back with your application.
Imagine you hire a decorator to remodel your house and you move out temporarily so you’re not in his way. He’ll still need to get back in touch with you to go over the pool plans, verify the wallpaper, get your plumber’s phone number, and most importantly, to tell you when you can move back in. This handler routine is the means for the FTF to get back in touch with your application, for all kinds of specific reasons.
For example there are three occasions when your application needs to come up with the file’s full DOS path name:
case: FTF service needs the DOS path in order to:
FUPBEG create the file
FUPEND update the file’s time and date
FUPPTH check if there’s an existing file that’s older or smaller (for ZMODEM features)
Other exit points are cues for your application to verify that the filename is valid, check if the user has authorization to upload it, handle a completed upload, handle an aborted upload, to import a file that’s already available on disk and, most important of all, when the file upload session is over for your application to prompt the user and resume control of his channel.
Here’s an informal pseudo-code template for an upload handler routine. This is mostly in C code, but it’s liberally laced with English descriptions where appropriate.
int
fupxxx( /* Handle the application-specific */
int fupcod) /* aspects of your uploads */
{ /* (fupcod=code for each aspect) */
int rc=0;
setmbk(whatever your application uses);
(be sure to set any other appropriate globals)
switch(fupcod) {
case FUPPTH: /* Where would we put this file? */
sprintf(ftfbuf,"<DOS path for the file>",ftfscb->fname);
rc=<resume upload> ? 2 : 1;
break;
case FUPBEG: /* Begin uploading this file */
if (user can't upload this file) {
sprintf(ftfbuf,"He can't upload this file because.");
}
else {
sprintf(ftfbuf,"<DOS path for the file>",ftfscb->fname);
reserve file
rc=1;
}
break;
case FUPREF: /* Refer to file, don't upload it */
strcpy(<somewhere>,ftfbuf);
break;
case FUPEND: /* This file uploaded successfully */
unreserve file
record a completed upload
sprintf(ftfbuf,"<DOS path for the file>",ftfscb->fname);
break;
case FUPSKP: /* This file upload aborted */
unreserve file
record an aborted upload
break;
case FUPFIN: /* End of uploading session */
usrptr->state=your state
usrptr->substt=your substate
prompt(whatever comes next);/* (don't call outprf()) */
rc=1;
break;
case FUPHUP: /* Channel hanging up */
the FUPFIN exit point never got called, clean up as req'd
break;
}
return(rc);
}You might find it handy to download FUPXXX.C from the Galacticomm Demo System, (305) 583-7808, which contains the above pseudo-code, and then edit it line-by-line into what your upload handler will need.
In addition to the fupcod input to your upload handler routine, there are several global variables that you can always assume will be available: usrnum, usrptr, usaptr, and vdaptr. In addition, these FTF variables are available:
struct ftfscb *ftfscb; Session Control Block (see FTF.H) for the current file transfer session
struct ftfpsp *ftfpsp; protocol specifications (see FTF.H) for the current file transfer session
char *ftfbuf; multi-purpose buffer (context dependent)
If you need any other global variables, be sure to set them up in your routine. The meaning of your routine’s return value depends on the type of exit point (which is coded in fupcod). These will be discussed individually for each exit point. In some cases, no return value is expected. You should return 0 in each of those cases to allow for future expansion.
Now we’ll go into each of the exit points in detail. To simplify things, we’ll pretend that FTF is a person telling your application what it needs:
I,me,my = FTF file transfer service
You,your = application software
From the remodeling analogy, this is like the decorator talking to the homeowner.
FUPPTH - Where would we put this file?
Tell me what DOS path you plan to use for this file coming up, and store that path in ftfbuf. If the protocol was capable of telling us a filename, I’ve put it in ftfscb->fname, otherwise ftfscb->fname is "". Usually you’ll return 1 in this case.
On the other hand, if you have a file fragment left behind from an earlier aborted upload of the same file, then give me the path for that file fragment and return 2. I may try to resume the upload if the protocol is capable (e.g. ZMODEM). You should only return 2 if you’re reasonably confident that the existing file is the result of an aborted upload. Otherwise, a useless mix of two different files might end up on the disk.
You could also just return 0 (and skip putting the path in ftfbuf) if you don’t plan on supporting file upload resume after abort, and don’t plan on supporting the upload-if-exists/newer/bigger options that ZMODEM is capable of.
FUPBEG - Begin uploading this file
Verify whether the user is allowed to upload this file. See ftfscb->fname and ftfscb->estbyt for the filename and size, if the protocol has supplied them. The file time and date may be in one of three forms:
| Protocol provides: | ftfscb->dosdat,dostim | ftfscb->unxtim |
| No information about date & time | 0,0 | 0L |
| DOS time and date formats | date,time | 0L |
| UNIX seconds since 1/1/70 | 0,0 | UNIX time |
See page 318 about time and date formats and handling routines. See page 322 for routines to read and set file time and date. After the file is uploaded I’ll stamp this time and date on the file (if any), as long as you provide me with the proper path in the FUPEND exit point.
The main reason for the FUPBEG exit point is for you to check this user’s upload permission and any other possible restrictions. Here are some things you might check for:
Does the filename have the proper syntax?Does the filename conflict with a reserved name? (For example, CON.TXT is an alias for the main console.Does this user have permission to upload this file?Does this user have permission to overwrite an existing file?Are too many users opening files at once (thereby using up all file handles)?Will users be able to use up all available disk space?Will users be able to upload a very large number of small files, making directory access very slow?If charges are associated with upload, can the user afford to pay?Could this filename possibly conflict with one of the other online users who are also using your application?Will other users online be able to see/download/modify this file while this user is in the process of uploading it?If it’s not ok to upload, return 0 and put an explanation of some kind in ftfbuf. The explanation should be a complete sentence (beginning with a capital letter and ending with a period), for example You don't have access rights to that file. The explanation can be up to 79 characters long, not including the terminating nul \0.
If it’s ok to upload, return 1 and tell me what DOS path to use for the file (store it in ftfbuf). Specify the maximum allowable size for this file, in bytes, in ftfscb->maxbyt. If there truly is no maximum size limit, then just leave ftfscb->maxbyt at the default value MAXLONG (about 2 gigabytes, see FTF.H).
You can check ftfscb->estbyt yourself if you like, and call things off if the file’s going to be too big, or you can leave this work to me. Either way, you should put some kind of size restriction in ftfscb->maxbyt. Hacked terminal software could theoretically claim to be uploading a 1000-byte file then proceed to upload a 1,000,000,000-byte file.
Setting ftfscb->maxbyt does two things for you. I’ll immediately make sure that ftfscb->estbyt doesn’t exceed your limit (and abort the transfer if it does). And I’ll also keep tabs on the size of the file while it’s being uploaded, and abort if the limit is exceeded.
An important feature of the file uploading service is that you can count on the fact that for every FUPBEG call, there will be exactly one call to either FUPSKP (upload of this file aborted) or FUPEND (upload of this file was successful), except in extreme cases such as power loss.
FUPREF - Refer to file, don't upload it
You’ll never get this case if you haven’t willingly and knowingly set the ftuptr->flags¦=FTFREF flag after you called fileup(). This all has to do with uploading a file by reference. Electronic Mail and the Forums have this ability. The Sysop can upload a file that already exists on the Major BBS server’s disk using the F file-import protocol. The file may stay where it is, and the e-mail or forum message that it’s attached to just refers to the real location of the file.
You identify your application’s capacity for upload-by-reference by setting the ftuptr->flags¦=FTFREF flag immediately after you call fileup(). By the way, that’s all you identify by setting FTFREF — your capacity for upload by reference. You don’t have to be concerned with the user’s authority to use file importing. I’ll only allow this if he has the key specified by CNF option FIMLOCK located in Security & Accounting, which requires the SYSOP key by default.
Here’s the situation if I ever happen to get around to calling the FUPREF exit point: The user chose the F protocol, and either the path he specified had no colon in it (in which case I assumed upload by reference was desired), or I confirmed with him that it would be ok to import this file by reference instead of actually making a copy of it.
I’m not going to use the return value from your FUPREF exit point, but you should still return 0 to allow for future features. If I call FUPREF at all, I’ll only call it after a FUPBEG where you returned 1, and immediately before I call FUPEND. When FUPREF is called, ftfbuf contains the path just as your FUPBEG handler left it. This is your baby now — you asked for it — so do whatever you have to do to keep track of this uploaded-by-reference file.
In your scheme for referencing a file where it stands, you’ll have to decide what you want to do about the standard upload file. The standard upload file is where you would have stored the file’s contents if it had been uploaded by more conventional means, such as ZMODEM. When referencing a file where it stands, the contents are really stored somewhere else on disk. You may or may not want to store something in the standard upload file. For example, when e-mail attachments are by reference, the special FILIND flag is set in the message record (see GME.H), and the path of the referenced file is stored in the standard upload file.
So your FUPBEG exit point will always specify the file path name for the standard upload file (whether the file is uploaded conventionally or referenced where it stands), and that exit point must return 1 for the upload to complete. I will create the standard upload file and leave it open while I call your FUPREF exit point.
If you have a use for the standard upload file in your file-reference scheme, your FUPREF exit point is a good time to write to it: it’s already open and you don’t have to close it (you can use ftfrwr()). If you don’t want this file, then unlink() it in your FUPEND exit point. Don’t unlink() it in the FUPREF() exit point because the file is still open at that time, and will be closed later.
FUPEND - This file uploaded successfully
The file was uploaded successfully. The actual size of the final file is available to you in ftfscb->actbyt. If the upload was resumed using ZMODEM’s resume-after-abort feature, ftfscb->actbyt is the total bytes in the file, not just the portion stuck on in this session. There’s no way to find out whether a resume took place or not, or to figure the size of the portion.
I need to know the DOS path for this file one more time (again, store it in ftfbuf) so I can set its time and date. If you don’t want me to store the time and date, just put an empty string in ftfbuf.
If you’re in the habit of checking against conflicts or collisions with other users, now’s the time to recognize that this user is all done with this file. So you can unreserve it if you did any reserving in the FUPBEG exit point.
I’m not expecting any return value from either your FUPEND or FUPSKP exit points, so you should return 0.
FUPSKP - This file upload aborted
The current file upload has been aborted for some reason. The size of the fragment is available to you in ftfscb->actbyt. If you don’t want fragments of aborted uploads lying around you need to delete the file now. You can do this by coming up with the file path name and passing it to unlink().
Here also, if you’ve been reserving the filename or a file handle since FUPBEG, now’s the time to unreserve it.
FUPFIN - End of uploading session
This step winds up the upload session and returns control to your regularly scheduled program. This is distinguished from FUPEND which only winds up from the upload of a single file. So for multiple file uploads there could be several FUPBEG/FUPEND pairs (or FUPBEG/FUPSKP if things didn’t work out).
In ftfscb->actfil you’ll find a count of the total number of files successfully uploaded. In ftfscb->tryfil is the total files that we tried to upload. Of course it’s always the case that actfil <= tryfil. When actfil < tryfil, not all the files made it. I’ve already told the user all about this, including why the last transfer aborted, or why the last of possibly several files were skipped.
Since you’re taking back control of this channel, it’s up to you to set things straight for what’s up next for this user. Here are two alternatives:
| You want control back | You want to return to the parent menu |
| Restore your usrptr->state | Restore your usrptr->state |
| Restore your usrptr->substt | Say bye to the user if you wish (you don’t need to call outprf()) |
| Prompt the user (you don’t need to call outprf()) | Return 0 |
| Return 1 |
Either way, if you’re prompting or saying goodbye using prfmsg(), you need to be sure to set your message block pointer using setmbk().
The pseudo-code for FUPFIN handling on page 150 assumes you want to take control back. Here’s an alternative pseudo-coding of the FUPFIN exit point to allow you to exit to your module’s parent menu page:
case FUPFIN: /* End of uploading session */
usrptr->state=your state
prompt(exiting); /* (don't call outprf()) */
rc=0;
break;This may be appropriate if your module really doesn’t want to regain control of the channel when the upload is done. In this case you only need to restore the user’s state code (module number), not the substate. Your module never actually regains control of the user’s channel. You can prompt him with some parting words, but you don’t need to. For consistency you should do whatever you normally do when the user exits from your module to the parent menu.
In the case where you’re supposedly retaking control, you may have to call condex(), and possibly wind up returning control to your parent Menu Tree menu after all. This would be the case if you were about to return to your module’s own internal main menu, and you found out you had gotten where you are through command concatenation. See page 109 about this whole condex() business.
Another handy feature of the file transfer service is that each fileup() invocation is followed (eventually) by exactly one FUPFIN or FUPHUP exit point invocation, except in dire cases (power loss for example).
FUPHUP - Channel hanging up
This is the alternative to FUPFIN that occurs when the user or the channel is hanging up for some reason in the middle of the upload session. No return value is expected, so you should return 0. You don’t need to worry about termination of the individual file upload, if one had been in progress, because FUPSKP will have been called already. But if there’s any session-level (as opposed to file-level) cleanup to be done, now’s your chance.
This brings up a tricky point that you may want to be aware of. When a user disconnects in the middle of one of your uploads, your module’s own hang-up entry point (see page 54) will be called eventually, as it always is at logoff. But you may not be able to recognize that the user was “in” your module because his usrptr->state will be that of the file transfer’s state code. One way out of this is your FUPHUP exit point. When the file transfer service’s own huprou() gets called, it will call your FUPHUP exit point in your upload handler routine. That’s when you can do your module’s last minute housekeeping on this channel.
Uploading Example #1
Here’s a very simple example of a module that uploads files onto a Major BBS server. Many shortcuts have been taken in this code for the sake of brevity. It uses a minimum of features, has few conveniences, and has none of the security precautions that should be in place before putting software online for users to access. Its sole purpose is to introduce you to the components of file uploading. You can download the source code and other files relevant to this example from the Galacticomm Demo System at (305) 583-7808. Look for GALUPX.ZIP in the File Libraries:
/***************************************************************************
* GALUPX.C *
* *
* Copyright (C) 1995 GALACTICOMM, Inc. All Rights Reserved. *
* *
* Uploading example. *
* *
* - R. Stein *
* *
***************************************************************************/
#include "gcomm.h"
#include "majorbbs.h"
#include "filexfer.h"
STATIC int uplinp(void);
STATIC int fupupl(int fupcod);
int uplstt; /* Uploading module state number */
struct module uplmodule={"",NULL,uplinp,dfsthn};void EXPORT
init__uploader(void) /* Uploader initialization */
{
stzcpy(uplmodule.descrp,gmdnam("GALUPX.MDF"),MNMSIZ);
uplstt=register_module(&uplmodule);
mkdir("UPLDIR");
}STATIC int
uplinp(void) /* Uploader input handler */
{
switch (usrptr->substt) {
case 0:
prf("Name of file to upload: ");
usrptr->substt=1;
break;
case 1:
if (margc == 0) {
return(0);
}
fileup(strcpy(vdaptr,margv[0]),"?",fupupl);
}
outprf(usrnum);
return(1);
}
int
fupupl( /* Handle the application-specific */
int fupcod) /* aspects of the upload example */
{ /* (fupcod=code for each aspect) */
int rc=0;
switch(fupcod) {
case FUPBEG: /* Begin uploading this file */
case FUPEND: /* This file uploaded successfully */
sprintf(ftfbuf,"UPLDIR\\%s",vdaptr);
rc=1;
break;
case FUPFIN: /* End of uploading session */
usrptr->state=uplstt;
}
return(rc);
}This module allows users to upload files into the UPLDIR subdirectory of the Major BBS server computer. As is the case with most modules, Sysops need to create a module page somewhere in their Menu Tree that uses it, normally the child page of some menu. When users are online and choose this service they are asked to type in a filename. When they do, control is turned over to the upload service and the user chooses a protocol. After the upload is complete, the user is returned to the parent menu page. Here is a discussion of the major components of this program.
struct module uplmodule
This module identifies only one custom entry point: uplinp() for the sttrou() text line input handler. The default status handler, dfsthn() is the stsrou() entry point for unusual status conditions.
init__uploader()
The initialization routine for this module registers the module using the description in the corresponding module definition file. It also creates the UPLDIR subdirectory to store the uploaded files, if one doesn’t exist already.
uplinp()
This routine handles text line input from the user after he selects this upload service. Upon entry, the user is prompted to enter a filename. If the user just presses enter, he is returned to the parent menu without uploading. If he types in a filename, that name is stored in his Volatile Data Area, and then he is handed over to the file transfer service. The middle parameter to fileup() is ? to give the user a list of available upload protocols.
fupupl()
This is the upload handler routine as described starting on page 150. The FUPBEG and FUPEND exit points are used by FTF to get the file’s full path name for opening the file, and for setting its time and date. The FUPFIN exit point merely restores the upload service’s state code and returns 0, which requests that the user be returned to the parent menu page. All other exit points simply return 0.
Potential Improvements to Upload Example #1
Here are some of the features left out of this brief example that you should consider if you are using uploads in your application:
Limits on file size and quantity in the upload directoryChecking for conflicts between the filename and DOS devicesDeleting the fragment left behind from an aborted uploadMultiple-file uploadsSysop-configurable prompts in an .MSG fileSysop-configurable upload directoryFormal declaration and limitation on VDA usageCommand concatenationAutomatic reprompt after /p page command, etc.Full module structure in source code, with commentsAll of these features are included in upload example #2.
Uploading Example #2
/******************************************************************************
* GALUPX2.C *
* *
* Copyright (C) 1995 GALACTICOMM, Inc. All Rights Reserved. *
* *
* Uploading example II *
* *
* - R. Stein *
* *
******************************************************************************/
#include "gcomm.h"
#include "majorbbs.h"
#include "filexfer.h"
#include "galupx2.h"
STATIC int uplinp(void);
STATIC void uplfil(char *filnam,char *protoc);
STATIC int fupupl(int fupcod);
STATIC void uplfin(void);
int uplstt; /* Enhanded uploader module state number */
static FILE *uplmb; /* file pointer for GALUPX2.MCV */
char *upldir; /* UPLDIR upload directory */
long uplbmax; /* max bytes allowed in UPLDIR */
long uplfmax; /* max files allowed in UPLDIR */
struct module uplmodule={ /* module interface block */
"", /* name used to refer to this module */
NULL, /* user logon supplemental routine */
uplinp, /* input routine if selected */
dfsthn, /* status-input routine if selected */
NULL, /* "injoth" routine for this module */
NULL, /* user logoff supplemental routine */
NULL, /* hangup (lost carrier) routine */
NULL, /* midnight cleanup routine */
NULL, /* delete-account routine */
uplfin /* finish-up (sys shutdown) routine */
};void EXPORT
init__uploader(void) /* Uploader initialization */
{
stzcpy(uplmodule.descrp,gmdnam("GALUPX2.MDF"),MNMSIZ);
uplstt=register_module(&uplmodule);
uplmb=opnmsg("GALUPX2.MCV");
mkdir(spr("%s.",upldir=stgopt(UPLDIR)));
uplbmax=lngopt(UPLBMAX,0,2147483647L);
uplfmax=numopt(UPLFMAX,0,32767);
dclvda(8+1+3+1);
}STATIC int
uplinp(void) /* Uploader input handler */
{
setmbk(uplmb);
if (margc == 1 && sameas(margv[0],"X")) {
return(0);
}
do {
bgncnc();
switch (usrptr->substt) {
case 0:
cncchr();
prfmsg(usrptr->substt=UPLNAME);
break;
case UPLNAME:
if (usrptr->flags&INJOIP) {
prfmsg(UPLNAME);
break;
}
cncall();
parsin();
switch (margc) {
case 0:
uplfil("","?");
break;
case 1:
uplfil(margv[0],"?");
break;
default:
uplfil(margv[0],margv[1]);
}
break;
}
} while (!endcnc());
outprf(usrnum);y
return(1);
}
STATIC void
uplfil( /* upload file(s) */
char *filnam, /* filename, or "" for multi-file */
char *protoc) /* protocol, or "?" for list */
{
if (sameas(filnam,"*")) {
filnam="";
}
if (rsvnam(filnam)
¦¦ strchr(filnam,':') != NULL
¦¦ strchr(filnam,'\\') != NULL
¦¦ strstr(filnam,"..") != NULL) {
prfmsg(UPLRSV);
prfmsg(UPLNAME);
}
else {
stzcpy(vdaptr,filnam,8+1+3+1);
fileup(filnam,protoc,fupupl);
}
}int
fupupl( /* Upload handling routine */
int fupcod)
{
int rc=0;
setmbk(uplmb);
switch(fupcod) {
case FUPBEG: /* Begin upload, check permission, reserve */
if (vdaptr[0] == '\0' && rsvnam(ftfscb->fname)) {
strcpy(ftfbuf,"Filename is a reserved DOS device name.");
break;
}
cntdir(spr("%s*.*",upldir));
if (numfils >= uplfmax) {
strcpy(ftfbuf,"Upload directory is full.");
break;
}
ftfscb->maxbyt=uplbmax-numbyts;
sprintf(ftfbuf,"%s%s",upldir,vdaptr[0] == '\0' ? ftfscb->fname
: vdaptr);
rc=1;
break;
case FUPEND: /* End complete upload of a file, unreserve */
sprintf(ftfbuf,"%s%s",upldir,vdaptr[0] == '\0' ? ftfscb->fname
: vdaptr);
break;
case FUPSKP: /* Skip incomplete upload of a file */
unlink(spr("%s%s",upldir,vdaptr[0] == '\0' ? ftfscb->fname
: vdaptr);
break;
case FUPFIN: /* Finish file upload session */
usrptr->state=uplstt;
if (ftfscb->actfil >= 1) {
prfmsg(UPLTHX);
}
break; /* rc == 0, so we exit to parent menu page */
}
return(rc);
}STATIC void
uplfin(void) /* Finalize uploading example */
{
clsmsg(uplmb);
}Here are the CNF options for upload example #2:
LEVEL4 {}
This is the directory where the files will go.
Be sure to specify a proper path PREFIX (e.g.
ending with a backslash, or whatever)
UPLDIR {UPLDIR\ S 0 Upload directory:
This is the maximum number of files allowed in the
upload directory.
UPLFMAX {Maximum files allowed in upload directory: 1000} N 0 32767
This is the maximum number of bytes (the total of all
files) allowed in the upload directory.
UPLBMAX {Maximum bytes allowed in upload directory: 1000000} L 0 2147483647
LEVEL6 {}
esc represents the Escape character, ASCII 27.
UPLNAME {esc[0;1;36m
Name of file to upload (or "*" for multiple files): } T Upload example II file
name
UPLRSV {esc[0;1;35m
That's a reserved or invalid DOS filename, please choose another name.
} T Upload example II filename collides with device list
UPLFUL {esc[0;1;35m
The upload directory is full.
} T Upload example II too many files
UPLTHX {esc[0;1;32m
Thanks for uploading.
} T Upload example II finished
This code, plus support files, is available for download on the Galacticomm Demo system in the file GALUPX2.ZIP.
Here’s what the module would look like online:
TOP (TOP)
Make your selection (T,I,F,E,L,A,P,R,D,O,W,U,N,S,? for help, or X to exit): U
Name of file to upload (or "*" for multiple files): COLDEMO.EXE
To start uploading COLDEMO.EXE, type:
A ... ASCII B ... YMODEM Batch
M ... XMODEM-Checksum G ... YMODEM-g
C ... XMODEM-CRC Z ... ZMODEM
1 ... XMODEM-1K K ... Kermit / Super Kermit
(Add '!' to automatically log off when done)
Your choice (or 'X' to exit): Z
(Hit Ctrl-X a few times to abort)
Beginning ZMODEM upload of the file COLDEMO.EXE
**B0100000023be50
(uploading takes place)
*** UPLOAD COMPLETE ***
Thanks for uploading.
TOP (TOP)
Make your selection (T,I,F,E,L,A,P,R,D,O,W,U,N,S,? for help, or X to exit): _
Assuming that the menu selection to invoke the uploading service is U, the user can enter any of the following concatenated commands from that menu:
U Enter the upload service
U <filename> Upload a specific file, prompt for protocol
U <filename> <protocol> Upload a file using a protocol
U * Upload multiple files, prompt for protocol
U * <protocol> Upload multiple files using a protocol
struct module uplmodule
In this example, the module structure is fleshed out with a helpful comment for each field. An uplfin() routine has been added to clean up before shutdown.
init__uploader()
The initialization routine does the same work as does the one in the first example, plus it also supports a Sysop-configurable directory for uploads, and reads in Sysop-configurable byte and file limits. The dclvda() call formally declares the need for enough space in the VDA to store a filename.
uplinp()
Some immediately obvious renovations are the checking for X to exit, and the use of command concatenation routines (bgncnc(), cncxxx(), endcnc()). When first entering this module, the cncchr() call helps with concatenated commands the user could have entered from the parent menu page. The user is prompted to enter a name for the uploaded file.
The UPLNAME substate handles the reaction to the upload filename prompt. The user can respond by pressing * or enter to signify that multiple files will be uploaded. But the first special case we handle is when the INJOIP flag is set, meaning we need to reprompt after a /p page message or other unexpected event. After that, parsin() reparses the input into separate margv[] words (see about how bgncnc() unparses on page 105). These are passed to an internal function, uplfil(), with default values for protocol and filename as appropriate.
uplfil()
This function translates * for filename into the "" that the first parameter of fileup() needs to signify multiple file uploads. It then proceeds to check the filename for dangerous characters like colon (:), backslash (\) and twin periods (..). There are many other (less dangerous) illegal characters for filenames, but most of these are caught eventually when FTF tries to create the file. If the filename is safe, it’s stored in the VDA and fileup() is called. Notice that the filename is checked for size limitations before writing to the VDA. Avoiding buffer overruns is a wonderful habit to get into, although we’re not exactly at high risk here.
fupupl()
In the FUPBEG exit point, we recheck for reserved names. This is necessary for multi-file uploads when we don’t know the names until this point. We also need to check file size and quantity limits since these too are dynamic. This may be a little impolite to the user to bring up this file quantity limitation so late in the game, but it must be checked for each file in a multi-file upload, so it needs to be in FUPBEG anyway.
Even this check is not completely air-tight: if two users started uploading 5 meg files at the same time, and the UPLBMAX setting is 6 meg, they will probably both be allowed to complete their uploads. That’s because the directory contents are measured only at the beginning of each upload without taking into account uploads that are already underway.
uplfin()
This routine politely closes the GALUPX2.MCV file when the Major BBS server shuts down.
ASCII Downloads
To dump an ASCII file to the user’s terminal, you can use:
listing(path,whndun); list an ASCII text file to the user’s terminal
char *path; DOS path of the file (must be a permanent storage location)
void (*whndun)(all); restore state & substate, prompt the user for what to do next
int all; 1=all of file was output, 0=aborted
The path parameter must point to a location where the file’s full path specification will reside throughout the listing. For example, a region of the Volatile Data Area, a private malloc()’d region, a literal filename, etc. Do not use spr(), a portion of input[], an automatic (stack) buffer, or any other location where the contents will change before the (*whndun)() routine gets called.
The listing() routine will usurp the channel’s state and substate (usrptr->state and usrptr->substt). It’s up to the (*whndun)() routine to restore your state (return value from register_module()) and substate. The (*whndun)() routine gets passed a single parameter which is 1=all of the file was downloaded, or 0=file was aborted by the user.
The listing() function will not be able to operate if the user has tagged too many files for download (see about ftgnew() on page 169).
An example initiation of an ASCII download:
listing("E:\DOC93\SATNAV.HLP",lstback);An example (*whndun)() routine:
void
lstback(int all)
{
usrptr->state=snstate;
prfmsg(usrptr->substt=all ? FULLPMT : SHORTPMT);
}Note that the (*whndun)() routine does not need to call outprf(). If it does call outprf() for any reason, it should then call clrprf() to avoid double prompting.
Downloads
Assuming that you’ve already taken care of all interactive aspects of your application, then here are the steps to take to add file downloading capability:
1. In your source code, include the following special-purpose header file:
#include "filexfer.h"- Define your own tagspec data structure. This can be up to 17 bytes of data for storing information on your file, in any format you choose. A tagspec may refer to a single file or to multiple files (for example you could store "FILE.TXT" or "*.TXT"). To allow your files to be tagged for later download, you’ll need to store enough information in this 17-byte structure to later reconstruct the file’s DOS path, and any security and accounting information. We’ll talk more about tagspecs below.
3. Code your own download handler routine. This routine will be called by the file transfer service to perform application-specific tasks throughout the download session. This is usually where your most work is, and it will be discussed in detail below.
4. Call ftgnew() to reserve an entry in the tag table.
navail=ftgnew(); Reserve space in the tag table
int navail; Number of spaces available
struct ftg *ftgptr; tag table entry
Each user has his own row of entries in the 2D tag table, the length of each row being specified by the CNF option MAXTAGS in Configuration Options. All downloads, whether explicitly tagged or not, are handled via an entry in the tag table. If ftgnew() returns 0, there is no room. If it returns nonzero, then that’s the number of spaces available, and ftgptr will point to your spot in the user’s tag table.
5. Now fill in the tag table entry. Store your tagspec in ftgptr->tagspc, a 17-byte character array. Again, you know the format of what’s stored here, the file transfer service doesn’t care. Set ftgptr->flags according to the flags: FTGWLD (multi-file), and FTGABL (whether possible to tag or not). And set ftgptr->tshndl to point to your tagspec handler routine.
- Call the ftgsbm(prot) routine to submit the tagspec:
usurp=ftgsbm(prot); Submit the tagspec for download
int usurp; 1=FTF has usurped control of session 0=you still have control of session
char *prot; protocol code
Download Protocol Codes
single-file for immediate download: M C 1 V
single-file or multi-file for immediate download: L A B G Z ZR K
to log off after downloading: append ! to any of the above
tag for later download: T
tag (quietly) for later download: TQ
for compressed file viewing: V
menu of download protocols: ? or ""
You can use the TQ protocol internally to tag a file without notifying the user. It’s otherwise an invalid protocol though: users are not able to specify it.
To validate a download protocol code, you can use valdpc():
ok=valdpc(prot); Is this a valid download protocol?
int ok; 1=valid, 0=invalid
char *prot; protocol code string
The return value of ftgsbm() tells you whether or not FTF has taken control of your session.
ftgsbm() returns 0 in these cases:
ftgsbm(anything) after ftgnew() has returned 0, outputs a warning
ftgsbm("T") tags a file for download & notifies the user
ftgsbm("TQ") silently tags a file for download
ftgsbm(protocol) when your TSHVIS routine reports that your file is invisible (in this case, ftgsbm() calls your TSHFIN exit point)
ftgsbm() returns 1, and changes usrptr->state,substt in these cases:
ftgsbm("?") changes state/substt to prompt for protocol/options
ftgsbm(protocol) changes state/substt to proceed with download
ftgsbm(trash) rebuffs, and then does the same as ftgsbm("?")
Here’s what you can count on:
If ftgsbm() returns 1, then it has changed the usrptr->state, and either TSHFIN or TSHHUP will get invoked exactly once eventually. If ftgsbm() returns 0, then usrptr->state and usrptr->substt have either not been changed, or already restored by the TSHFIN exit point of your download handler routine.
Tagspecs
A tagspec is a 17-byte application-specific structure for keeping track of each file downloaded. Its main purpose is to allow file tagging, where a user identifies a file for download at some later time. But all files that are downloaded use tagspecs, even if they aren’t explicitly tagged.
These 17-byte tagspecs were designed as small as possible so that users could have room to tag numerous files without wasting large amounts of memory. There’s just enough room for a 4-byte pointer and a 12-character filename plus its nul terminator. The 4-byte pointer could be used to refer to some directory, forum, library, category, or other structure somehow. For example, you could store a 32-bit absolute database pointer here. You can use any format you need for the 17 bytes, as long as you keep in mind the asynchronous nature of file tagging (identifying the file now, downloading it later).
You must take special care that your application can handle file tagging before you set the FTGABL (tagable) flag in ftgptr->flags (see step 5 above). For one example of a disaster waiting to happen, suppose you store the 12-character filename in the tagspec, and a 60-character path prefix in your Volatile Data Area. In some of your download handler exit points (TSHVIS, TSHBEG and possibly TSHSCN and others) you assemble these two things together to get the DOS path for the file. This will work just dandy if the user never tags these files.
But if you set ftgptr->flags¦=FTGABL and the user picks T to tag a file in your module, you’re probably in for big trouble. For one thing, if he tags two files from different directories, and then downloads them both, they will both use the path prefix meant for the second file. For another, the user may be off in some other module, with entirely different data stored in the Volatile Data Area, when he gets around to downloading his tagged files. Then when your download handler routine gets called, and goes to the Volatile Data Area for that 60-character prefix, something rather unexpected may be there in its place. This is the worst kind of bug to have on your hands — intermittent cause and unpredictable effect.
Possible corrections to this kind of bug are either to find somewhere else to store the path prefix, or to rethink the strategy. You could store the path prefix in a database and store a database pointer in the tagspec.
Or perhaps you could restrict your application to using the same path prefix for all files. If you were desperate to give users the ability to tag up to MAXTAGS number of files, each with an arbitrary path prefix, then your application could allocate a monster 3D array, 61 bytes by MAXTAGS by nterms, and store all the path prefixes there.
Download Handler Routine
This routine is a collection of exit points for all the application-specific tasks that need to be done during the general-purpose downloading session. See page 150 for a discussion of the concept of exit points as regards the upload handler routine.
This pseudo-code template roughly outlines the tasks expected at each of the exit points.
int
tshxxx( /* Handle the application-specific */
int tshcod) /* aspects of your downloads */
{ /* (tshcod=code for each aspect) */
int rc=0;
setmbk(whatever your application uses);
(be sure to set any other appropriate globals)
switch(tshcod) {
case TSHDSC: /* Describe the file(s) in English */
sprintf(tshmsg,"app-specific description of file",ftgptr->tagspc);
break;
case TSHVIS: /* Visible to this user? */
if (file exists, or user is allowed to know it doesn't) {
open & read first TSHLEN bytes into tshmsg, as in:
if ((fp=fopen("<DOS path for the file>",FOPRB)) != NULL) {
fread(tshmsg,1,TSHLEN,fp);
rc=1;
}
}
break;
case TSHSCN: /* Break down multiple filespec */
if (there's at least one file in this multi-file tagspec) {
store tagspec for the individual file in tshmsg
rc=1;
}
break;
case TSHNXT: /* Next file in multi-file spec */
if (there are more subfiles) {
store tagspec for the individual file in tshmsg
rc=1;
}
break; case TSHBEG: /* Begin downloading this file */
if (file can't be downloaded by this user) {
sprintf(tshmsg,"You can't download the file because...");
}
else {
reserve it
sprintf(tshmsg,"<DOS path for file>",ftgptr->tagspc);
strcpy(ftfscb->fname,"<filename for the protocol>");
rc=1;
}
break;
case TSHEND: /* File download was successful */
unreserve it
record a completed download
break;
case TSHSKP: /* This file download aborted */
unreserve it
record an aborted download
break;
case TSHFIN: /* End of downloading session */
usrptr->state=your state
usrptr->substt=your substate
prompt (you don't need to call outprf here)
rc=1;
break;
case TSHHUP: /* Channel hanging up */
the TSHFIN exit point never got called, clean up as req'd
break;
}
return(rc);
}This code is available in file TSHXXX.C on the Galacticomm Demo System, (305) 583-7808. You may want to download it and use it as a template to write your own download handler routine.
The global variables usrnum, usrptr, usaptr, and vdaptr are available for all exit points of the download handler routine. In addition, these FTF variables are available:
struct ftfscb *ftfscb; Session Control Block (see FTF.H) for the current file transfer session
struct ftfpsp *ftfpsp; protocol specifications (see FTF.H) for the current file transfer session
struct ftg *ftgptr; current tag table entry
ftgptr->tagspc current tagspec
char *tshmsg; multi-purpose buffer (context-dependent)
If you need any other global variables, be sure to set them up in your routine. The meaning of your routine’s return value depends on the type of exit point (which is coded in tshcod). These will be discussed individually for each exit point. In some cases, no return value is expected. You should return 0 in each of those cases to allow for future expansion.
TSHDSC - Describe the file(s) in English
Format a description for the single file or multiple files in the tshmsg buffer. You should word the description so that it looks right when following the word the, as in Do you want to download the %s (y/n)? (see CNF option SRETRYV in Edit Text Blocks).
The tagspec you originally submitted is in ftgptr->tagspc. This exit point must work with a multi-file tagspec, as well as the single-file tagspecs that you’ll be breaking it down into. The return value doesn’t matter, but it’s a good practice to return 0 for future expansion.
TSHVIS - Visible to this user?
Is this file visible? Return 1=visible to user, or 0=not visible.
This exit point should handle multi-file tagspecs (which are not now checked for visibility, but may be in future versions) as well as single-file tagspecs. Return 1 if the user is allowed to know whether this file exists.
The purpose of this exit point is to allow you to decide to totally restrict access to a given file, to the point where certain users don’t even know it exists. It also allows you to break-down multi-file tagspecs in TSHSCN and TSHNXT without doing any security checks.
If the file is visible, read the first TSHLEN bytes (80 bytes) into the tshmsg buffer. This will allow tests for a compressed file, such as a .ZIP file, to know whether or not to present the user with the V protocol choice. If you don’t read in the first TSHLEN bytes of this file, then the V protocol will never be available.
TSHSCN - Break down multiple filespec
If you submit a multi-file tagspec (by setting ftgptr->flags¦=FTGWLD), then you’ll be asked to break it down into single-file tagspecs when the time comes for downloading.
If the multi-file tagspec refers to one or more files, then return 1 and store the tagspec for the first file in the tshmsg buffer. Return 0 if the multi-file tagspec ends up referring to no files at all. You can also return 2 to indicate that there may be files available, but that you aren’t supplying a tagspec in tshmsg yet — you’ll do that in TSHNXT.
TSHNXT - Next file in multi-file spec
This continues the work that TSHSCN started. Return 1 if there are more single-file tagspecs, and store the next one in tshmsg. Return 0 if there are no more files. Return 2 if there may be more files, but you want to be called again to make a tagspec out of them. This may help simplify certain multi-file breaking-down schemes.
See the example module source code starting on page 182 for a way to do TSHSCN and TSHNXT with fnd1st() and fndnxt(). See page 325 about the routines themselves. For your convenience, ftuptr->fb is a user-specific fndblk structure that you can use with fnd1st() and fndnxt() in this context.
TSHBEG - Begin downloading this file
Verify that the user is allowed to download this file. If not, put a reason in tshmsg (a complete sentence, as in You don't have access rights to that file.) and return 0.
Here are some things you might check for:
Does the filename have the proper syntax?Does the filename conflict with a reserved name?Does the user have permission to download this file?Are too many users opening files at once (thereby using up all file handles)?Can this user afford the download charges, if any?Is another user currently modifying/uploading/deleting this file?If downloading is ok, store the DOS path for the file in tshmsg and return 1. In case this protocol can communicate filenames, put the filename into ftfscb->fname. For example, if downloading with ZMODEM, this filename will be the one used on the user’s terminal. It doesn’t have to be the same as the one used on the Major BBS server, but it usually is.
There is another special option in the TSHBEG exit point. You can return -1 to indicate that the file is not yet available for download, but it will be later. The file won’t be downloaded during this download session, but it will remain tagged for download, and can be downloaded later. This is used to accommodate files that are not instantly available such as those on a multi-disk CD ROM drive (as opposed to those that are, such as on your hard disk).
TSHEND - File download was successful
You may wish to record the download, or charge the user for it at this point. Use this exit point to cancel whatever reserving was done in the TSHBEG entry point. For example, if you had some scheme for preventing the Sysop from deleting this file while this user was downloading it, now’s the time to recognize that it’s ok to delete the file. The return value doesn’t matter, but it’s a good practice to return 0 for future expansion.
You can count on the fact that for every TSHBEG call there will be exactly one TSHEND or TSHSKP call. The only exception would be a very abrupt termination like a power loss.
TSHSKP - This file download aborted
Here you’ll need to do the same unreserving that is done in the TSHEND exit point. You may also wish to make some record of the aborted download.
TSHFIN - End of downloading session
This is the most important exit point: the one where FTF turns control back over to your application. Be sure to restore your usrptr->state and usrptr->substt, and prompt the user for what comes next.
If your application supports file tagging, you should recognize that TSHFIN only means that the file transfer service is done controlling this user’s session for the moment. The user may still cause your download handler to get called for this same tagspec later, with any of the cases except TSHFIN and TSHHUP. This could happen for example when the user tries to log off, and is given a chance to download all files that he has tagged.
In ftfscb->actfil you’ll find a count of the total number of files successfully downloaded. In ftfscb->tryfil is the total files that we tried to download. Of course it’s always the case that actfil <= tryfil. When actfil < tryfil, not all the files made it. The user has already seen a report about this, including why the last transfer aborted, or why the last of possibly several files were skipped.
Since you’re taking back control of this channel, it’s up to you to set things straight for what’s up next for this user. Two alternatives:
| You want control back | You want to return to the parent menu |
| Restore your usrptr->state | Restore your usrptr->state |
| Restore your usrptr->substt | Say goodbye to the user if you wish (you don’t need to call outprf()) |
| Prompt the user (you don’t need to call outprf()) | Return 0 |
| Return 1 |
Either way, if you’re prompting or saying goodbye using prfmsg(), you need to be sure to set your message block pointer using setmbk().
The pseudo-code for TSHFIN handling on page 173 assumes you want to take control back. Here’s an alternative of the TSHFIN exit point to allow you to exit to your module’s parent menu page:
case TSHFIN: /* End of downloading session */
usrptr->state=your state
prompt(exiting); /* (don't call outprf()) */
rc=0;
break;This may be appropriate if your module really doesn’t want to regain control of the channel when the download is done. In this case you only need to restore the user’s state code (module number), not the substate. Your module never actually regains control of the user’s channel. You can prompt him with some parting words, but you don’t need to. For consistency you should do whatever you normally do when the user exits from your module to the parent menu.
In the case where you’re supposedly retaking control, you may have to call condex(), and possibly wind up returning control to your parent Menu Tree menu after all. This would be the case if you were about to return to your module’s own internal main menu, and you found out you had gotten where you are through command concatenation. See page 109 about this whole condex() business.
Another handy feature of the file transfer service is that each ftgsbm() invocation that returns 1 is followed (eventually) by exactly one TSHFIN or TSHHUP exit point invocation, except in dire cases (power loss for example).
TSHHUP - Channel hanging up
Use this exit point to clean up your affairs in case the user hangs up or the channel disconnects while the user is in the download session. This only occurs in place of a TSHFIN, and will probably not be called if one of your files is tagged for download and the actual download is interrupted by a disconnect. In that case, TSHFIN had long since been called, after the user tagged the file.
If a disconnect occurs in the middle of downloading a file the user didn’t tag for download (he asked to download it immediately), then a TSHSKP exit point will be called first, to properly terminate the download, before TSHHUP is called.
See the discussion on the upload handler exit point FUPHUP on page 158 about making sure your module’s cleanup code executes exactly once for users in your module.
Downloading Example #1
/***************************************************************************
* *
* GALDNX.C *
* *
* Copyright (C) 1995 GALACTICOMM, Inc. All Rights Reserved. *
* *
* Downloading example. *
* *
* - R. Stein 12/6/93 *
* *
***************************************************************************/
#include "gcomm.h"
#include "majorbbs.h"
#include "filexfer.h"
STATIC int dnlinp(void);
STATIC int tshdnl(int tshcod);
int dnlstt; /* Downloading module state number */
struct module dnlmodule={"",NULL,dnlinp,dfsthn,NULL,NULL,NULL,NULL,NULL,NULL};void EXPORT
init__downloader(void) /* Downloader initialization */
{
stzcpy(dnlmodule.descrp,gmdnam("GALDNX.MDF"),MNMSIZ);
dnlstt=register_module(&dnlmodule);
}STATIC int
dnlinp(void) /* Downloader input handler */
{
int rc=1;
switch (usrptr->substt) {case 0:
prf("Name of file to download: ");
usrptr->substt=1;
break;case 1:
if (margc == 0) {
rc=0;
}
else if (ftgnew() == 0) {
ftgsbm(""); /* use warning feature of ftgsbm() */
rc=0;
}
else {
stzcpy(ftgptr->tagspc,margv[0],TSLENG);
ftgptr->tshndl=tshdnl;
ftgsbm("?");
}
}
outprf(usrnum);
return(rc);
}
```c
```c
int
tshdnl( /* Handle the application-specific */
int tshcod) /* aspects of your downloads */
{ /* (tshcod=code for each aspect) */
int rc=0;
switch(tshcod) {
case TSHVIS: /* Visible to this user? */
rc=1;
break;
case TSHDSC: /* Describe the file(s) in English */
sprintf(tshmsg,"file %s",ftgptr->tagspc);
break;
case TSHBEG: /* Begin downloading this file */
sprintf(tshmsg,"DNLDIR\\%s",ftgptr->tagspc);
strcpy(ftfscb->fname,ftgptr->tagspc);
rc=1;
break;
case TSHFIN: /* End of downloading session */
usrptr->state=dnlstt;
}
return(rc);
}
This module lets users download files from subdirectory DNLDIR on the Worldgroup server computer. Users of this service type in a filename (that they must know somehow), and choose a protocol to download it.
###### init\_\_downloader()
This routine registers the downloading module using the description in the GALDNX.MDF file.
###### dnlinp()
This routine handles text line input from the user after he selects this download service. Upon entry, the user is prompted for the filename. If he presses enter, he’s returned to the parent menu page without any downloading. If there is no room to download any more files because the user’s tag table is completely full, then the user is notified (ftgsbm() does this) and he’s also returned to the parent menu.
Otherwise, the tagspec structure is simply the filename, and it’s copied to the tagspec in the current tag table entry that ftgnew() identified for us. Neither the FTGWLD nor FTGABL flags are set, indicating that these will be single-file non-taggable downloads. The call to ftgsbm() turns control over to the file transfer service and a list of protocols is presented to the user.
###### tshdnl()
The TSHVIS exit point declares that all files are visible if they exist. The description for the file will be file \<filename\>. In the TSHBEG exit point the path and protocol names are passed to FTF. There are no TSHEND, TSHSKP, or TSHHUP exit points coded because they only need to return 0 and do nothing else. TSHFIN restores the usrptr-\>state and returns 0, telling FTF to return control to the parent menu.
###### Potential Improvements to Download Example \#1
Here are some of the features left out of this brief example that you should consider if you are using downloads in your application:
-
-
-
-
-
-
-
-
-
-
-
Viewing the contents of compressed files, such as .ZIP filesMultiple-file downloadsChecking for conflicts between the filename and DOS devicesChecking for attempts to download files like DNLLIB\\.\WG.BATFile taggingConcatenated commandsAllowing X to exitTelling the user what files are available in the directorySysop-configurable prompts an .MSG fileSysop-configurable download directoryFull module structure in source code, with commentsAll of these features are included in download example \#2.
###### Downloading Example \#2
/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
\* \*
\* GALDNX2.C \*
\* \*
\* Copyright (C) 1995 GALACTICOMM, Inc. All Rights Reserved. \*
\* \*
\* Downloading example. \*
\* \*
\* - R. Stein 12/6/93 \*
\* \*
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/
\#include "gcomm.h"
\#include "majorbbs.h"
\#include "filexfer.h"
\#include "galdnx2.h"
```c
```c
STATIC int dnlinp(void);
STATIC int fllist(void);
STATIC int tshdnl(int tshcod);
STATIC void dnlfin(void);
int dnlstt; /* Downloading module state number */
static FILE *dnlmb; /* file pointer for GALDNX2.MCV */
char *dnldir; /* DNLDIR download directory */
struct module dnlmodule={ /* module interface block */
"", /* name used to refer to this module */
NULL, /* user logon supplemental routine */
dnlinp, /* input routine if selected */
dfsthn, /* status-input routine if selected */
NULL, /* "injoth" routine for this module */
NULL, /* user logoff supplemental routine */
NULL, /* hangup (lost carrier) routine */
NULL, /* midnight cleanup routine */
NULL, /* delete-account routine */
dnlfin /* finish-up (sys shutdown) routine */
};
void EXPORT
init__downloader(void) /* Downloader initialization */
{
stzcpy(dnlmodule.descrp,gmdnam("GALDNX2.MDF"),MNMSIZ);
dnlstt=register_module(&dnlmodule);
dnlmb=opnmsg("GALDNX2.MCV");
dnldir=stgopt(DNLDIR);
}
STATIC int
dnlinp(void) /* Downloader input handler */
{
int rc=1;
setmbk(dnlmb);
if (margc == 1 && sameas(margv[0],"X")) {
return(0);
}
do {
bgncnc();
switch (usrptr->substt) {
case 0:
cncchr();
if (!fllist()) {
cncall();
rc=0;
}
prfmsg(usrptr->substt=FLNAME);
break;
case FLNAME:
cncall();
parsin();
if (margc == 0 || sameas(margv[0],"?")) {
fllist();
prfmsg(FLNAME);
}
else if (rsvnam(margv[0])
|| strchr(margv[0],':') != NULL
|| strchr(margv[0],'\\') != NULL
|| strstr(margv[0],"..") != NULL) {
prfmsg(FLRSV);
prfmsg(FLNAME);
}
else if (ftgnew() == 0) {
ftgsbm(""); /* use ftgsbm() to say out-of-tags */
rc=0;
}
else {
stzcpy(ftgptr->tagspc,margv[0],TSLENG);
ftgptr->tshndl=tshdnl;
ftgptr->flags=FTGABL;
if (strchr(margv[0],'?') != NULL
|| strchr(margv[0],'*') != NULL) {
ftgptr->flags|=FTGWLD;
}
rc=ftgsbm(margc > 1 ? margv[1] : "?");
}
}
} while (!endcnc());
outprf(usrnum);
return(rc);
}
STATIC int
fllist(void) /* Display listing of files */
{
struct fndblk fb;
if (!fnd1st(&fb,spr("%s*.*",dnldir),0)) {
prfmsg(FLNONE);
return(0);
}
prfmsg(FLHEAD);
do {
prfmsg(FLLINE,fb.name,l2as(fb.size),ncdate(fb.date),nctime(fb.time));
} while (fndnxt(&fb));
return(1);
}Applies to: WG3.x
Header check:
struct fndblkisstruct ffblkin WG3.2 (FIOAPI.H:37-44;FIOAPI.H:125,FILEXFER.H:41), with different member names and widths:ff_reserved,ff_fsize,ff_attrib,ff_ftime,ff_fdateandff_name[256]. The sample'sfb.name,fb.size,fb.date,fb.timebecomefb.ff_name,fb.ff_fsize,fb.ff_fdate,fb.ff_ftime.GBOOL fnd1st(struct ffblk *fbptr, const CHAR *filspc, INT attr)andfndnxt(struct ffblk *fbptr)areFIOAPI.H:229-236;filspcisconst. (In v10,ff_namegrows to 260 andxffblkis added:analysis/deltas/SUMMARY.md.)
Applies to: v10
v10:
char ff_name[260](FIOAPI.H:44; 256 in WG3.2), sosizeof(struct ffblk)changed;findfirst(const char *filspc, struct ffblk *fbptr, UINT attr)andfindnext(struct ffblk *fbptr)were added for_MSC_VERbuilds (FIOAPI.H:257-269), andstruct xffblk(holding aHANDLE) is new (FIOAPI.H:50-55).fnd1st()/fndnxt()remain (FIOAPI.H:254).
int
tshdnl( /* Handle the application-specific */
int tshcod) /* aspects of your downloads */
{ /* (tshcod=code for each aspect) */
int rc=0;
FILE *fp;
setmbk(dnlmb);
switch(tshcod) {
case TSHDSC: /* Describe the file(s) in English */
sprintf(tshmsg,"file %s",ftgptr->tagspc);
break;
case TSHVIS: /* Visible to this user? */
if (ftgptr->flags&FTGWLD) {
rc=fnd1st(&ftuptr->fb,ftgptr->tagspc,0);
break;
}
if ((fp=fopen(spr("%s%s",dnldir,ftgptr->tagspc),FOPRB)) != NULL) {
fread(tshmsg,1,TSHLEN,fp);
rc=1;
}
break;
case TSHSCN: /* Break down multiple filespec */
if (fnd1st(&ftuptr->fb,spr("%s%s",dnldir,ftgptr->tagspc),0)) {
strcpy(tshmsg,ftuptr->fb.name);
rc=1;
}
break;
case TSHNXT: /* Next file in multi-file spec */
if (fndnxt(&ftuptr->fb)) {
strcpy(tshmsg,ftuptr->fb.name);
rc=1;
}
break;
case TSHBEG: /* Begin downloading this file */
sprintf(tshmsg,"%s%s",dnldir,ftgptr->tagspc);
strcpy(ftfscb->fname,ftgptr->tagspc);
rc=1;
break;
case TSHFIN: /* End of downloading session */
usrptr->state=dnlstt;
}
return(rc);
}
STATIC void
dnlfin(void) /* Finalize downloading example */
{
clsmsg(dnlmb);
}Here are the CNF options for download example #2:
LEVEL4 {}
This is the directory for the files to download.
Be sure to specify a proper path PREFIX (e.g.
ending with a backslash, or whatever)
DNLDIR {DNLDIR\ S 0 Download directory:
LEVEL6 {}
esc represents the Escape character, ASCII 27.
FLHEAD {esc[0;1;32m
Files available:
} T Download example II file listing header
FLLINE {esc[0;1;36m%-12.12sesc[33m %10s %8s %-5.5s
} T Download example II file listing line
FLNONE {esc[0;1;35m
No files are available for download.
} T Download example II no files available
FLNAME {esc[0;1;36m
Name of file(s) to download: } T Download example II filename prompt
FLRSV {esc[0;1;35m
That's not a valid filename
} T Download example II filename invalid
This code, plus support files, is available for download on the Galacticomm Demo system in the file GALDNX2.ZIP.
Here’s what the module would look like online:
TOP (TOP)
Make your selection (T,I,F,E,L,A,P,R,D,O,W,U,N,S,? for help, or X to exit): D
Files available:
LOADER.BAT 1524 11/26/93 20:00
DPATCH.ZIP 57001 12/07/93 12:26
GALCONDL.ZIP 4162 12/07/93 16:05
DINSTALL.BAT 237 12/02/93 13:31
Name of file(s) to download: *.ZIP
L ... Listing (a screen at a time) Z ... ZMODEM
A ... ASCII (continuous dump) ZR... ZMODEM (resume after abort)
B ... YMODEM Batch K ... Kermit / Super Kermit
G ... YMODEM-g
T ... Tag file(s) for later download
(Add '!' to automatically log off when done)
Choose a download option (or 'X' to exit): Z
(Hit Ctrl-X a few times to abort)
Beginning ZMODEM download of the file *.BAT
rz
**B0000000000000
(downloading takes place)
*** DOWNLOAD COMPLETE ***
TOP (TOP)
Make your selection (T,I,F,E,L,A,P,R,D,O,W,U,N,S,? for help, or X to exit): _
init__downloader()
This function registers the GALDNX2 module, opens the GALDNX2.MCV file, and reads in the Sysop-configured download directory prefix.
dnlinp()
This text-line input handling function returns to the parent menu if the user enters X and otherwise uses command concatenation routines to parse user input. When a user enters this module he’s given a list of the files available (more on fllist() below), and asked to type in the name of a file, or file specification with wildcards, to download.
If he replies with ? he’s given the list of files again. If the name he gives is reserved, like CON.TXT, then he is warned and reprompted for a filename.
An entry in the tag table is obtained, if available, by ftgnew(). In this example, the use of wildcard characters ? or * in the filename signifies a multi-file download, and the FTGWLD flag is set. The FTGABL flag is always set. If the user concatenated a protocol code after his file specification, that is passed to ftgsbm(). Otherwise, a list of protocols is requested. FTF will handle invalid protocol codes with a warning and a list of the available codes.
fllist()
This function scans through the files in the download directory and lists them on the user’s terminal, with file size, date, and time.
The size of the output buffer (CNF option OUTBSZ in Hardware Setup) effectively limits the number of files that can be put online for download. With OUTBSZ set to 4096, you can probably handle somewhere around 100 files. Much more than that, and the output buffer will overflow.
tshdnl()
Here the description is the same simple file <filename>. Multi-file tagspecs are visible if any matching files exist. Single-file tagspecs are visible if the file can be opened, and if so, the first TSHLEN bytes are read in so the V protocol can be supported.
Exit points TSHSCN and TSHNXT use the classic technique for breaking down multi-file tagspecs into single files: fnd1st() and fndnxt(). In each case a single-file tagspec (the filename) is copied into tshmsg.
There are no security restrictions on the files in the download directory. In the TSHBEG exit point, the path is constructed in tshmsg, and the protocol name is copied to ftfscb->fname.
The TSHFIN exit point just restores the state code and returns 0, indicating that control should return to the download module’s parent menu page when downloading is complete.
Download Manager Support in Agents
Applies to: WG2+
If your agent supports apps getting files from it, apps may use the new Download Manager to get those files. Without you doing anything special, this will appear to work fine. But, examined more closely, things may not be all that fine. You do need to do one simple thing to support the new Download Manager from your agent: support apps getting the status of your file dynapaks with stsdpk(). To do this, you need to pay attention to forreal()’s return value where appropriate in your read handler. Be sure that your read handler doesn’t do anything like charge for files gotten by apps without checking forreal() first.
Applies to: WG2+
Header check (GCSPSRV.H):
BOOL forreal(void); (GCSP.H): the dynapak status length is carried in struct typlen (APTYPLEN) for stsdpk().
File Transfer Protocol
To define a file transfer protocol for the Major BBS, define a file transfer protocol specification structure. Here is an example of the structure for XMODEM-CRC downloads.
Applies to: WG3.x
Header check:
FTFXYMD.H(struct xymdat,ftpxcx; WG2FTFXYMD.H:13,43) is not inWGDEV/INC.struct ftfpspand the protocol flags (FTF.H) are, and their 16-bit members becameushort(byttmo,paktmo,paksiz,retrys,nbytes:analysis/deltas/SUMMARY.mdstruct deltas), so a hand-copied WG2 layout is wrong.
struct ftfpsp ftpxcx={ /* XMODEM-CRC transmitting */
NULL,
"C", /* 1-3 code letters for protocol */
"XMODEM-CRC", /* name of protocol */
FTFXMT+FTFXTD, /* protocol capability flags */
sizeof(struct xymdat), /* total length of session control block */
3*16, /* .byttmo default byte timeout */
10*16, /* .paktmo default packet timeout */
10, /* .retrys default max retries */
1L, /* .window max window size (packets/bytes as appropriate) */
128, /* .paksiz packet size 0=auto-figure */
xyxini, /* .initze() Initialize this protocol (recompute scblen) */
xcxsrt, /* .start() Start a transfer */
xyxctn, /* .contin() Continuously call, 1=more, 0=done */
xyxinc, /* .hdlinc() Handle one incoming byte */
NULL, /* .hdlins() Handle incoming line of text */
ftfabt, /* .term() Initiate graceful termination of transfer */
ftfxca, /* .abort() Immediately unconditionally abort the transfer */
ftfinbc, /* .hdlinb() Handle an array of incoming bytes */
"", /* .secur App-specific security of some kind */
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
};Here are the protocol capability flags:
/* --- File Transfer Protocol Capability and Characteristic Flags --- */
#define FTFXMT 0x01 /* Transmit protocol (versus receive) */
#define FTFASC 0x02 /* ASCII-session (versus binary-session) */
/* where '\r' is the sole line terminator */
/* note: ASCII sessions do not detect errors */
#define FTFMUL 0x04 /* capable of multiple files? */
#define FTF7BT 0x08 /* capable of using 7-bit data path? */
#define FTFASF 0x10 /* ASCII-file (versus binary-file) */
/* where '\n' is the sole line terminator */
#define FTFAFN 0x40 /* abort is final, don't ask "try again?" */
#define FTFXTD 0x80 /* extended ftfpsp structure (flags2 & hdlinb) */See FTF.H for more details. See FTFXYMD.C for the full implementation of XMODEM. See FTF*.C for examples of the implementation of other file transfer protocols. The F file import/export file transfer “protocol” is implemented in FILEXFER.C with lots of cheating.
Next, register the structure in your init__xxx() routine via ftplog():
ftplog(fptr);where fptr is a pointer to the structure from step 1. The new protocol will appear in the appropriate lists with all the other protocols.