about summary refs log tree commit diff stats
path: root/WWW/Library/Implementation/HTFinger.c
blob: e714e0d20f0f000352b9d97dba792ce85ef484e1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
import random, time

class DelValue():
	def a(d):
		return dict((k, v) for k, v in d.items() if v is not 0)

	def b(d):
		for k, v in d.copy().items():
			if v == 0: del d[k]
		return d

	def c(d):
		for k in tuple(d.keys()):
			if d[k] == 0: del d[k]
		return d

	def d(d):
		for k, v in tuple(d.items()):
			if v == 0: del d[k]
		return d


basedict = {}
for i in range(200):
	basedict[i] = random.randint(0, 1)

expected = DelValue.a(basedict.copy())

for algo in ['a', 'b', 'c', 'd']:
	copy = basedict.copy()
	t = time.time()
	for i in range(100):
		assert DelValue.__dict__[algo](copy) == expected
	print("algorithm %s: %f" % (algo, time.time() - t))

# c it is, although b is faster with smaller dictionaries
> 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
/*			FINGER ACCESS				HTFinger.c
**			=============
** Authors:
**  ARB  Andrew Brooks
**
** History:
**	21 Apr 94   First version (ARB, from HTNews.c by TBL)
**	12 Mar 96   Made the URL and command buffering secure from
**		     stack modifications, beautified the HTLoadFinger()
**		     and response() functions, and added support for the
**		     following URL formats for sending a "", "/w",
**		     "username[@host]", or "/w username[@host]" command
**		     to the server:
**			finger://host
**			finger://host/
**			finger://host/%2fw
**			finger://host/%2fw%20username[@host]
**			finger://host/w/username[@host]
**			finger://host/username[@host]
**			finger://host/username[@host]/w
**			finger://username@host
**			finger://username@host/
**			finger://username@host/w
**	15 Mar 96   Added support for port 79 gtype 0 gopher URLs
**		     relayed from HTLoadGopher. - FM
*/

#include "HTUtils.h"
#include "tcp.h"
#include "HTAlert.h"
#include "HTML.h"
#include "HTParse.h"
#include "HTFormat.h"
#include "HTTCP.h"
#include "HTString.h"
#include "HTFinger.h"

#include "LYLeaks.h"

/* #define TRACE 1 */

#define FINGER_PORT 79		/* See rfc742 */
#define BIG 1024		/* Bug */

#define FREE(x) if (x) {free(x); x = NULL;}

#define PUTC(c) (*targetClass.put_character)(target, c)
#define PUTS(s) (*targetClass.put_string)(target, s)
#define START(e) (*targetClass.start_element)(target, e, 0, 0, -1, 0)
#define END(e) (*targetClass.end_element)(target, e, 0)
#define FREE_TARGET (*targetClass._free)(target)
#define NEXT_CHAR HTGetCharacter() 


/*	Module-wide variables
*/
PRIVATE int s;					/* Socket for FingerHost */

struct _HTStructured {
	CONST HTStructuredClass * isa;		/* For gopher streams */
	/* ... */
};

PRIVATE HTStructured * target;			/* The output sink */
PRIVATE HTStructuredClass targetClass;		/* Copy of fn addresses */

/*	Initialisation for this module
**	------------------------------
*/
PRIVATE BOOL initialized = NO;
PRIVATE BOOL initialize NOARGS
{
  s = -1;		/* Disconnected */
  return YES;
}



/*	Start anchor element
**	--------------------
*/
PRIVATE void start_anchor ARGS1(CONST char *,  href)
{
    BOOL		present[HTML_A_ATTRIBUTES];
    CONST char*		value[HTML_A_ATTRIBUTES];
    
    {
    	int i;
    	for(i=0; i<HTML_A_ATTRIBUTES; i++)
	    present[i] = (i==HTML_A_HREF);
    }
    ((CONST char **)value)[HTML_A_HREF] = href;
    (*targetClass.start_element)(target, HTML_A, present,
    				 (CONST char **)value, -1, 0);

}

/*	Send Finger Command line to remote host & Check Response
**	--------------------------------------------------------
**
** On entry,
**	command	points to the command to be sent, including CRLF, or is null
**		pointer if no command to be sent.
** On exit,
**	Negative status indicates transmission error, socket closed.
**	Positive status is a Finger status.
*/


PRIVATE int response ARGS5(
	CONST char *,		command,
	char *,			sitename,
	HTParentAnchor *,	anAnchor,
	HTFormat,		format_out,
	HTStream*,		sink)
{
    int status;
    int length = strlen(command);
    int ch, i;
    char line[BIG], *l, *cmd=NULL;
    char *p = line, *href=NULL;

    if (length == 0)
        return(-1);

    /* Set up buffering.
    */
    HTInitInput(s);

    /* Send the command.
    */
    if (TRACE) 
        fprintf(stderr, "HTFinger command to be sent: %s", command);
    status = NETWRITE(s, (char *)command, length);
    if (status < 0) {
        if (TRACE)
	    fprintf(stderr,
                    "HTFinger: Unable to send command. Disconnecting.\n");
        NETCLOSE(s);
        s = -1;
        return status;
    } /* if bad status */
  
    /* Make a hypertext object with an anchor list.
    */
    target = HTML_new(anAnchor, format_out, sink);
    targetClass = *target->isa;	/* Copy routine entry points */

    /* Create the results report.
    */
    if (TRACE)
	fprintf(stderr,"HTFinger: Reading finger information\n");
    START(HTML_HTML);
    PUTS("\n");
    START(HTML_HEAD);
    PUTS("\n");
    START(HTML_TITLE);
    PUTS("Finger server on ");
    PUTS(sitename);
    END(HTML_TITLE);
    PUTS("\n");
    END(HTML_HEAD);
    PUTS("\n");
    START(HTML_BODY);
    PUTS("\n");
    START(HTML_H1);
    PUTS("Finger server on ");
    START(HTML_EM);
    PUTS(sitename);
    END(HTML_EM);
    PUTS(": ");
    if (command) {
        StrAllocCopy(cmd, command);
    } else {
        StrAllocCopy(cmd, "");
    }
    for (i = (strlen(cmd) - 1); i >= 0; i--) {
        if (cmd[i] == LF || cmd[i] == CR) {
	    cmd[i] = '\0';
	} else {
	    break;
	}
    }
    PUTS(cmd);
    FREE(cmd);
    END(HTML_H1);
    PUTS("\n");
    START(HTML_PRE);

    while ((ch=NEXT_CHAR) != (char)EOF) {

	if (interrupted_in_htgetcharacter) {
	    if (TRACE) {
	        fprintf(stderr,
		  "HTFinger: Interrupted in HTGetCharacter, apparently.\n");
	    }
	    _HTProgress ("Connection interrupted.");
	    goto end_html;
        }

	if (ch != LF) {
	    *p = ch;		/* Put character in line */
	    if (p < &line[BIG-1]) {
	        p++;
	    }
	} else {
	    *p = '\0';		/* Terminate line */
	    /*
	     * OK we now have a line.
	     * Load it as 'l' and parse it.
	     */
	    p = l = line;
	    while (*l) {
		if (strncmp(l, "news:", 5) &&
		    strncmp(l, "snews://", 8) &&
		    strncmp(l, "nntp://", 7) &&
		    strncmp(l, "snewspost:", 10) &&
		    strncmp(l, "snewsreply:", 11) &&
		    strncmp(l, "newspost:", 9) &&
		    strncmp(l, "newsreply:", 10) &&
		    strncmp(l, "ftp://", 6) &&
		    strncmp(l, "file:/", 6) &&
		    strncmp(l, "finger://", 9) &&
		    strncmp(l, "http://", 7) &&
		    strncmp(l, "https://", 8) &&
		    strncmp(l, "wais://", 7) &&
		    strncmp(l, "mailto:", 7) &&
		    strncmp(l, "cso://", 6) &&
		    strncmp(l, "gopher://", 9)) 
		    PUTC(*l++);
		else {
		    StrAllocCopy(href, l);
		    start_anchor(strtok(href, " \r\n\t,>)\""));
		    while (*l && !strchr(" \r\n\t,>)\"", *l))
		        PUTC(*l++);
		    END(HTML_A);
		    FREE(href);
		}
	    }
	    PUTC('\n');
	}
    }
    NETCLOSE(s);
    s = -1;

end_html:
    END(HTML_PRE);
    PUTS("\n");
    END(HTML_BODY);
    PUTS("\n");
    END(HTML_HTML);
    PUTS("\n");
    FREE_TARGET;
    return(0);
}


/*		Load by name					HTLoadFinger
**		============
*/
PUBLIC int HTLoadFinger ARGS4(
	CONST char *,		arg,
	HTParentAnchor *,	anAnchor,
	HTFormat,		format_out,
	HTStream*,		stream)
{
    char *username, *sitename, *colon;	/* Fields extracted from URL */
    char *slash, *at_sign;		/* Fields extracted from URL */
    char *command, *str;		/* Buffers */
    int port;				/* Port number from URL */
    int status;				/* tcp return */
  
    if (TRACE) {
        fprintf(stderr, "HTFinger: Looking for %s\n", (arg ? arg : "NULL"));
    }
  
    if (!(arg && *arg)) {
        HTAlert("Could not load data.");
	return HT_NOT_LOADED;			/* Ignore if no name */
    }
  
    if (!initialized) 
        initialized = initialize();
    if (!initialized) {
        HTAlert ("Could not set up finger connection.");
	return HT_NOT_LOADED;	/* FAIL */
    }
    
  {
    CONST char * p1=arg;
    BOOL IsGopherURL = FALSE;
    
    /*  Set up the host and command fields.
    */        
    if (!strncasecomp(arg, "finger://", 9)) {
        p1 = arg + 9;  /* Skip "finger://" prefix */
    } else if (!strncasecomp(arg, "gopher://", 9)) {
        p1 = arg + 9;  /* Skip "gopher://" prefix */
	IsGopherURL = TRUE;
    }
    sitename = (char *)p1;

    if ((slash = strchr(sitename, '/')) != NULL) {
        *slash++ = '\0';
	HTUnEscape(slash);
	if (IsGopherURL) {
	    if (*slash != '0') {
	        HTAlert("Could not load data.");
		return HT_NOT_LOADED;	/* FAIL */
	    }
	    *slash++ = '\0';
	}
    }
    if ((at_sign = strchr(sitename, '@')) != NULL) {
        if (IsGopherURL) {
            HTAlert("Could not load data.");
	    return HT_NOT_LOADED;	/* FAIL */
	}
        *at_sign++ = '\0';
        username = sitename;
	sitename = at_sign;
	HTUnEscape(username);
    } else if (slash) {
        username = slash;
    } else {
        username = "";
    }
    
    if (*sitename == '\0') {
        HTAlert("Could not load data (no sitename in finger URL)");
	return HT_NOT_LOADED;		/* Ignore if no name */
    }

    if ((colon = strchr(sitename, ':')) != NULL) {
        *colon++ = '\0';
	port = atoi(colon);
	if (port != 79) {
	    HTAlert("Invalid port number - will only use port 79!");
	    return HT_NOT_LOADED;	/* Ignore if wrong port */
	}
    }

    /* Load the string for making a connection/
    */
    str = (char *)calloc(1, (strlen(sitename) + 10));
    if (str == NULL)
        outofmem(__FILE__, "HTLoadFinger");
    sprintf(str, "lose://%s/", sitename);
    
    /* Load the command for the finger server.
    */
    command = (char *)calloc(1, (strlen(username) + 10));
    if (command == NULL)
        outofmem(__FILE__, "HTLoadFinger");
    if (at_sign && slash) {
        if (*slash == 'w' || *slash == 'W') {
	    sprintf(command, "/w %s%c%c", username, CR, LF);
	} else {
	    sprintf(command, "%s%c%c", username, CR, LF);
	}
    } else if (at_sign) {
	sprintf(command, "%s%c%c", username, CR, LF);
    } else if (*username == '/') {
        if ((slash = strchr((username+1), '/')) != NULL) {
	    *slash = ' ';
	}
	sprintf(command, "%s%c%c", username, CR, LF);
    } else if ((*username == 'w' || *username == 'W') &&
    	       *(username+1) == '/') {
	if (*username+2 != '\0') {
	    *(username+1) = ' ';
	} else {
	    *(username+1) = '\0';
	}
	sprintf(command, "/%s%c%c", username, CR, LF);
    } else if ((*username == 'w' || *username == 'W') &&
    	       *(username+1) == '\0') {
	sprintf(command, "/%s%c%c", username, CR, LF);
    } else if ((slash = strchr(username, '/')) != NULL) {
	*slash++ = '\0';
	if (*slash == 'w' || *slash == 'W') {
	    sprintf(command, "/w %s%c%c", username, CR, LF);
	} else {
	    sprintf(command, "%s%c%c", username, CR, LF);
	}
    } else {
	sprintf(command, "%s%c%c", username, CR, LF);
    }
  } /* scope of p1 */
  
    /* Now, let's get a stream setup up from the FingerHost:
    ** CONNECTING to finger host
    */
    if (TRACE)
        fprintf(stderr, "HTFinger: doing HTDoConnect on '%s'\n", str);
    status = HTDoConnect(str, "finger", FINGER_PORT, &s);
    if (TRACE)
        fprintf(stderr, "HTFinger: Done DoConnect; status %d\n", status);

    if (status == HT_INTERRUPTED) {
        /* Interrupt cleanly */
	if (TRACE)
	    fprintf(stderr,
	    	  "HTFinger: Interrupted on connect; recovering cleanly.\n");
	HTProgress ("Connection interrupted.");
	FREE(str);
	FREE(command);
	return HT_NOT_LOADED;
    }
    if (status < 0) {
        NETCLOSE(s);
	s = -1;
	if (TRACE) 
	    fprintf(stderr, "HTFinger: Unable to connect to finger host.\n");
        HTAlert("Could not access finger host.");
	FREE(str);
	FREE(command);
	return HT_NOT_LOADED;	/* FAIL */
    }
    if (TRACE)
        fprintf(stderr, "HTFinger: Connected to finger host '%s'.\n", str);
    FREE(str);

    /* Send the command, and process response if successful.
    */
    if (response(command, sitename, anAnchor, format_out, stream) != 0) {
        HTAlert("No response from finger server.");
	FREE(command);
	return HT_NOT_LOADED;
    }

    FREE(command);
    return HT_LOADED;
}

#ifdef GLOBALDEF_IS_MACRO
#define _HTFINGER_C_1_INIT { "finger", HTLoadFinger, NULL }
GLOBALDEF (HTProtocol, HTFinger, _HTFINGER_C_1_INIT);
#else
GLOBALDEF PUBLIC HTProtocol HTFinger = { "finger", HTLoadFinger, NULL };
#endif /* GLOBALDEF_IS_MACRO */