Exemple #1
0
PUBLIC_KEY *publickey_make_rsa(SSH_SESSION *session, BUFFER *buffer,
    int type) {
  STRING *e = NULL;
  STRING *n = NULL;
  PUBLIC_KEY *key = NULL;

  key = malloc(sizeof(PUBLIC_KEY));
  if (key == NULL) {
    buffer_free(buffer);
    return NULL;
  }

  key->type = type;
  key->type_c = ssh_type_to_char(key->type);

  e = buffer_get_ssh_string(buffer);
  n = buffer_get_ssh_string(buffer);

  buffer_free(buffer); /* we don't need it anymore */

  if(e == NULL || n == NULL) {
    ssh_set_error(session, SSH_FATAL, "Invalid RSA public key");
    goto error;
  }
#ifdef HAVE_LIBGCRYPT
  gcry_sexp_build(&key->rsa_pub, NULL,
      "(public-key(rsa(n %b)(e %b)))",
      string_len(n), n->string,
      string_len(e),e->string);
  if (key->rsa_pub == NULL) {
    goto error;
  }
#elif HAVE_LIBCRYPTO
  key->rsa_pub = RSA_new();
  if (key->rsa_pub == NULL) {
    goto error;
  }

  key->rsa_pub->e = make_string_bn(e);
  key->rsa_pub->n = make_string_bn(n);
  if (key->rsa_pub->e == NULL ||
      key->rsa_pub->n == NULL) {
    goto error;
  }
#endif

#ifdef DEBUG_CRYPTO
  ssh_print_hexa("e", e->string, string_len(e));
  ssh_print_hexa("n", n->string, string_len(n));
#endif

  string_burn(e);
  string_free(e);
  string_burn(n);
  string_free(n);

  return key;
error:
  string_burn(e);
  string_free(e);
  string_burn(n);
  string_free(n);
  publickey_free(key);

  return NULL;
}
Exemple #2
0
/*
 * macro_paramlist
 *
 * Parse a macro or structure parameter list, for declarations.
 *
 * For keyword macros and structure declarations,
 * handles the default value setting.
 *
 * For non-keyword macros, handles simple, conditional, and
 * iterative macro parameter lists.
 *
 * Returns: -1 on error
 * index of closing delimiter in delims[] array on success
 */
int
macro_paramlist (expr_ctx_t ctx, scopectx_t curscope,
                 int assign_allowed, int for_macro,
                 lextype_t delims[], int ndelims,
                 scopectx_t *ptable, namereflist_t *plist)
{
    parse_ctx_t pctx = expr_parse_ctx(ctx);
    namectx_t namectx = scope_namectx(parser_scope_get(pctx));
    lexctx_t lctx = parser_lexmemctx(pctx);
    lexeme_t *lex;
    lextype_t lt;
    name_t *mnp;
    scopectx_t pscope;
    lexseq_t nullseq;
    namedef_t ndef;
    int i, did1;
    lextype_t terms[16];

    // Need a delimiter array that adds ',' to the
    // caller's list
    if (ndelims >= 16) return -1;
    memcpy(terms, delims, sizeof(lextype_t)*ndelims);
    terms[ndelims] = LEXTYPE_DELIM_COMMA;

    if (*ptable == 0) {
        pscope = scope_begin(scope_namectx(curscope), curscope);
    } else {
        pscope = *ptable;
    }

    lexseq_init(&nullseq);
    parser_scope_begin(pctx);
    memset(&ndef, 0, sizeof(ndef));
    ndef.lt = LEXTYPE_NAME_MAC_PARAM;
    did1 = 0;

    while (1) {
        lexseq_t *pseq;
        strdesc_t *namestr;
        textpos_t pos;
        // Look for a parameter name
        if (!parse_decl_name(pctx, &namestr, &pos)) {
            // Null parameter list is OK, but empty parameter
            // after a comma is not
            if (did1) {
                expr_signal(ctx, STC__NAMEEXP);
            }
            lt = parser_next(pctx, QL_NAME, 0);
            break;
        }

        // Declare the parameter in the parameter name table
        did1 = 1;
        ndef.name = namestr->ptr;
        ndef.namelen = namestr->len;
        mnp = name_declare(pscope, &ndef, pos, 0, 0, &pseq);
        string_free(expr_strctx(ctx), namestr);
        if (mnp == 0) {
            expr_signal(ctx, STC__INTCMPERR, "macro_paramlist");
            break;
        }
        namereflist_instail(plist, nameref_alloc(namectx, mnp));
        // If assignment is allowed, parse the '=' and the
        // default value - a lexeme sequence for macros, a CTCE for
        // structures
        lt = parser_next(pctx, QL_NAME, &lex);
        if (assign_allowed && lt == LEXTYPE_OP_ASSIGN) {
            int status;
            lexeme_free(lctx, lex);
            if (for_macro) {
                status = parse_lexeme_seq(pctx, 0, QL_MACRO,
                                          terms, ndelims+1, pseq, &lt);
            } else {
                status = expr_parse_ctce(ctx, &lex, 0);
                if (status) lexseq_instail(pseq, lex);
                lt = parser_next(pctx, QL_NORMAL, 0);
            }
            if (!status) {
                expr_signal(ctx, STC__SYNTAXERR);
                break;
            }
        } else {
            lexeme_free(lctx, lex);
        }
        if (lt != LEXTYPE_DELIM_COMMA) {
            break;
        }
    }
    parser_scope_end(pctx);

    // Check for the closing delimiter
    for (i = 0; i < ndelims && lt != delims[i]; i++);
    if (i >= ndelims) {
        scope_end(pscope);
        parser_skip_to_delim(pctx, delims[0]);
        namereflist_free(namectx, plist);
        i = -1;
    } else if (*ptable == 0) {
        *ptable = pscope;
    }

    return i;

} /* macro_paramlist */
Exemple #3
0
static int tunet_logon_recv_welcome()
{
	BYTE tmpbuf[1024 * 8];
	CHAR  tmp[1024];

	BYTE  btag;
	UINT32  unknowntag;
	UINT32  datalen;

	BYTE *p;

	int len;
	
	const CHAR *WELCOME = "WELCOME TO TUNET";
	//int msglen = 0;

	STRING *str = NULL;

//	BOOL sr, sw, se;
	
	if(!main_socket) return OK;
	
//	os_socket_tcp_status(main_socket, &sr, &sw, &se);

	if(tunet_state != TUNET_STATE_RECV_WELCOME) 
		return OK;


/*	if(se)
	{
		logs_append(g_logs, "TUNET_NETWORK_ERROR", "RECV_WELCOME", NULL, 0);
		return ERR;
	}

	if(!sr) return OK;
*/

	len = os_socket_tcp_recv(main_socket, tmpbuf, sizeof(tmpbuf));
	if(len == -1)
	{
		logs_append(g_logs, "TUNET_NETWORK_ERROR", "RECV_WELCOME", NULL, 0);
		return ERR;
	}
	if(len > 0)
	{
		main_socket_buffer = buffer_append(main_socket_buffer, tmpbuf, len);

		logs_append(g_logs, "TUNET_LOGON_RECV", "WELCOME", tmpbuf, len);

		buf2output(tmpbuf, len, tmp, 16);
		//dprintf("data received(recv welcome):\n%s\n", tmp);

		p = main_socket_buffer->data;
		while(buffer_fetch_BYTE(main_socket_buffer, &p, &btag))
		{
			switch(btag)
			{
				case 0x01:
					if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, strlen(WELCOME)))
						return OK;

					if(strncmp(str->str, WELCOME, strlen(WELCOME)) != 0)
					{
						str = string_free(str);

						//TODO
						//process such error!!!!!!!!!
						logs_append(g_logs, "TUNET_LOGON_WELCOME", str->str, NULL, 0);
						tunet_state = TUNET_STATE_ERROR;
						return OK;
					}
					str = string_free(str);

					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &unknowntag))
						return OK;

					unknowntag = htonl(unknowntag);

					if(!buffer_fetch_bytes(main_socket_buffer, &p, welcome_data, 8))
						return OK;

					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen))
						return OK;
					
					datalen = htonl(datalen);
					//dprintf("欢迎消息长 %d\n", datalen);

					if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, datalen))
						return OK;

					logs_append(g_logs, "TUNET_LOGON_WELCOME", str->str, NULL, 0);

					//dprintf("%s\n", str->str);
					str = string_free(str);

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					tunet_state = TUNET_STATE_REPLY_WELCOME;			

					break;

				case 0x02: 
				case 0x05:
					datalen = htonl(BUF_FETCH_DWORD(p));
					//dprintf("出错消息长 %d\n", datalen);

					str = string_new("");
					str = string_nappend(str, (CHAR *)p, datalen);
					//dprintf("%s\n", str->str);

					tunet_state = TUNET_STATE_ERROR;

					logs_append(g_logs, "TUNET_LOGON_ERROR", str->str, NULL, 0);

					str = string_free(str);

					BUF_ROLL(p, datalen);

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;
				
					break;

			}
		}
		
	}

	return OK;
}
static void free_if_needed(struct url_check* url)
{
	string_free(&url->realLink);
	string_free(&url->displayLink);
	string_free(&url->pre_fixup.pre_displayLink);
}
Exemple #5
0
void
var_defines( char *const* e, int preprocess )
{
    string buf[1];

    string_new( buf );

	for( ; *e; e++ )
	{
	    char *val;

# ifdef OS_MAC
	    /* On the mac (MPW), the var=val is actually var\0val */
	    /* Think different. */
	
	    if( ( val = strchr( *e, '=' ) ) || ( val = *e + strlen( *e ) ) )
# else
	    if( val = strchr( *e, '=' ) )
# endif
	    {
		LIST *l = L0;
		char *pp, *p;
# ifdef OPT_NO_EXTERNAL_VARIABLE_SPLIT
                char split = '\0';
# else
# ifdef OS_MAC
		char split = ',';
# else
		char split = ' ';
# endif
# endif
                size_t len = strlen(val + 1);

                int quoted = val[1] == '"' && val[len] == '"';
                
                if ( quoted && preprocess )
                {
                    string_append_range( buf, val + 2, val + len );
                    l = list_new( l, newstr( buf->value ) );
                    string_truncate( buf, 0 );
                }
                else
                {
                    /* Split *PATH at :'s, not spaces */

                    if( val - 4 >= *e )
                    {
                        if( !strncmp( val - 4, "PATH", 4 ) ||
                            !strncmp( val - 4, "Path", 4 ) ||
                            !strncmp( val - 4, "path", 4 ) )
			    split = SPLITPATH;
                    }

                    /* Do the split */

                    for(
                        pp = val + 1;
                        preprocess && (p = strchr( pp, split )) != 0;
                        pp = p + 1 )
                    {
                        string_append_range( buf, pp, p );
                        l = list_new( l, newstr( buf->value ) );
                        string_truncate( buf, 0 );
                    }

                    l = list_new( l, newstr( pp ) );
                }

		/* Get name */
                string_append_range( buf, *e, val );
		var_set( buf->value, l, VAR_SET );
                string_truncate( buf, 0 );
	    }
	}
        string_free( buf );
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{	
		case WM_FOO_GET_ACTIVE_PLAYLIST_COUNT:
			if(plist_api) return activeplaylist_get_item_count(&plist_api);
			return P_ERROR;

		case WM_FOO_GET_PLAYLIST_ITEM:
		{
			char title[512];
			wchar_t w_title[512];
			if(!ptcomp_api || !plist_api || !pback_api) return P_ERROR;
			if(wParam == -1 && !is_playing(&pback_api)) return P_ERROR;
			int tracknumb = (wParam==-1)?(int)get_playing_item_location(&plist_api):wParam;
			PTITLEFORMAT_OBJECT *t_obj=0;	// Must be 0!!!
			if(!GetWindowText(p_hWnd, title, 512)) return P_ERROR;

			if(compile(&ptcomp_api, &t_obj, title))
			{
				string_free();
				playlist_item_format_title(&plist_api, get_active_playlist(&plist_api), tracknumb, 0, &str,
								&t_obj, 0, display_level_all);
				MultiByteToWideChar(CP_UTF8, 0, str.data, -1, w_title, 512);
				SetWindowTextW(p_hWnd, w_title);
				service_release((PSERVICE_BASE*)t_obj);
				return 0;
			}
			return P_ERROR;
		}

		case WM_FOO_GET_CURRENT_TRACK:
			if(plist_api) return get_playing_item_location(&plist_api);
			return P_ERROR;

		case WM_FOO_ORDER:
			if(plist_api) {playback_order_set_active(&plist_api, wParam); return 0;}
			return P_ERROR;

		case WM_FOO_OPEN:	return main_open(&g_api);
		case WM_FOO_ADD:	return main_add_files(&g_api);
		case WM_FOO_ADDDIR:	return main_add_directory(&g_api);

		case WM_FOO_PLAY:
			if(pback_api) {start_resume(&pback_api); return 0;}
			return P_ERROR;

		case WM_FOO_STOP:
			if(pback_api) {stop(&pback_api); return 0;}
			return P_ERROR;

		case WM_FOO_PLAY_NEXT:
			if(pback_api) {start(&pback_api, track_command_next); return 0;}
			return P_ERROR;

		case WM_FOO_PLAY_PREV:
			if(pback_api) {start(&pback_api, track_command_prev); return 0;}
			return P_ERROR;

		case WM_FOO_PLAY_RANDOM:
			if(pback_api) {start(&pback_api, track_command_rand); return 0;}
			return P_ERROR;

		case WM_FOO_PAUSE:
			if(pback_api) {pause(&pback_api, true); return 0;}
			return P_ERROR;

		case WM_FOO_PLAY_PAUSE:
			if(pback_api) {play_pause(&pback_api); return 0;}
			return P_ERROR;

		case WM_FOO_VOLUME_UP:
			if(pback_api) {volume_up(&pback_api); return 0;}
			return P_ERROR;

		case WM_FOO_VOLUME_DOWN:
			if(pback_api) {volume_down(&pback_api); return 0;}
			return P_ERROR;

		case WM_FOO_GET_VOLUME:
			if(pback_api) return get_volume(&pback_api);
			return P_ERROR;

		case WM_FOO_SET_VOLUME:
			if(pback_api) {set_volume(&pback_api, wParam); return 0;}
			return P_ERROR;

		case WM_FOO_MUTE:
			if(pback_api) {mute(&pback_api); return 0;}
			return P_ERROR;

		case WM_FOO_IS_PLAYING:
			if(pback_api) return (is_playing(&pback_api) && !is_paused(&pback_api));
			return P_ERROR;

		case WM_FOOL_IS_PAUSED:
			if(pback_api) return is_paused(&pback_api);
			return P_ERROR;

		case WM_FOO_GET_STOP_AFTER_CURRENT:
			if(pback_api) return get_stop_after_current(&pback_api);
			return P_ERROR;

		case WM_FOO_SET_STOP_AFTER_CURRENT:
			if(pback_api) {set_stop_after_current(&pback_api, wParam); return 0;}
			return P_ERROR;

		case WM_FOO_PLAYBACK_CAN_SEEK:
			if(pback_api) return playback_can_seek(&pback_api);
			return P_ERROR;

		case WM_FOO_PLAYBACK_SEEK:
			if(pback_api) {playback_seek(&pback_api, wParam); return 0;}
			return P_ERROR;

		case WM_FOO_PLAYBACK_SEEK_DELTA:
			if(pback_api) {playback_seek_delta(&pback_api, wParam); return 0;}
			return P_ERROR;

		case WM_FOO_GET_POSITION:
			if(pback_api) return playback_get_position(&pback_api);
			return P_ERROR;

		case WM_FOO_GET_LENGTH:
			if(pback_api) return playback_get_length(&pback_api);
			return P_ERROR;

		case WM_FOO_EXIT:	return main_exit(&g_api);
		case WM_FOO_ACTIVATE:	return main_activate(&g_api);
		case WM_FOO_HIDE:	return main_hide(&g_api);

		case WM_FOO_PLAY_TRACK:
			if(plist_api) {playlist_execute_default_action(&plist_api, get_active_playlist(&plist_api), wParam); return 0;}
			return P_ERROR;

		case WM_FOO_REGISTER_CALLBACK:
			if(wParam & PLAYBACK_START)			AddCallback((PFCALLBACK)&callbacks, CSTARTING, (HWND)lParam, 0);
			if(wParam & PLAYBACK_DYNAMIC_INFO) 		AddCallback((PFCALLBACK)&callbacks, CDYNAMIC_INFO, (HWND)lParam, 0);
			if(wParam & PLAYBACK_DYNAMIC_INFO_TRACK)	AddCallback((PFCALLBACK)&callbacks, CDYNAMIC_INFO_TRACK, (HWND)lParam, 0);
			if(wParam & PLAYBACK_TIME)			AddCallback((PFCALLBACK)&callbacks, CTIME, (HWND)lParam, 0);
			if(wParam & PLAYBACK_VOLUME_CHANGE)		AddCallback((PFCALLBACK)&callbacks, CVOLUME_CHANGE, (HWND)lParam, 0);
			if(wParam & PLAYBACK_STOP)			AddCallback((PFCALLBACK)&callbacks, CSTOP, (HWND)lParam, 0);
			if(wParam & PLAYBACK_SEEK)			AddCallback((PFCALLBACK)&callbacks, CSEEK, (HWND)lParam, 0);
			if(wParam & PLAYBACK_PAUSE)			AddCallback((PFCALLBACK)&callbacks, CPAUSE, (HWND)lParam, 0);
			if(wParam & PLAYBACK_NEW_TRACK)
			{
				char caption[512];
				if(GetWindowText(p_hWnd, caption, 512))	AddCallback((PFCALLBACK)&callbacks, CNEW_TRACK, (HWND)lParam, caption);
			}
			
			if(wParam & PLAYBACK_EDITED)
			{
				char caption[512];
				if(GetWindowText(p_hWnd, caption, 512))	AddCallback((PFCALLBACK)&callbacks, CEDITED, (HWND)lParam, caption);
			}
			return 0;

		case WM_FOO_UNREGISTER_CALLBACK:
			if(wParam & PLAYBACK_START)			RemoveCallback((PFCALLBACK)&callbacks, CSTARTING, (HWND)lParam);
			if(wParam & PLAYBACK_NEW_TRACK) 		RemoveCallback((PFCALLBACK)&callbacks, CNEW_TRACK, (HWND)lParam);
			if(wParam & PLAYBACK_STOP)			RemoveCallback((PFCALLBACK)&callbacks, CSTOP, (HWND)lParam);
			if(wParam & PLAYBACK_SEEK)			RemoveCallback((PFCALLBACK)&callbacks, CSEEK, (HWND)lParam);
			if(wParam & PLAYBACK_PAUSE)			RemoveCallback((PFCALLBACK)&callbacks, CPAUSE, (HWND)lParam);
			if(wParam & PLAYBACK_EDITED)			RemoveCallback((PFCALLBACK)&callbacks, CEDITED, (HWND)lParam);
			if(wParam & PLAYBACK_DYNAMIC_INFO) 		RemoveCallback((PFCALLBACK)&callbacks, CDYNAMIC_INFO, (HWND)lParam);
			if(wParam & PLAYBACK_DYNAMIC_INFO_TRACK)	RemoveCallback((PFCALLBACK)&callbacks, CDYNAMIC_INFO_TRACK, (HWND)lParam);
			if(wParam & PLAYBACK_TIME)			RemoveCallback((PFCALLBACK)&callbacks, CTIME, (HWND)lParam);
			if(wParam & PLAYBACK_VOLUME_CHANGE)		RemoveCallback((PFCALLBACK)&callbacks, CVOLUME_CHANGE, (HWND)lParam);
			return 0;

		default:		return DefWindowProc(hWnd, message, wParam, lParam);
	}
}
void var_string_to_file( const char * in, int insize, const char * out, LOL * lol )
{
    const char * ine = in+insize;
    FILE * out_file = 0;
    if ( strcmp( out, "STDOUT" ) == 0 )
    {
        out_file = stdout;
    }
    else if ( strcmp( out, "STDERR" ) == 0 )
    {
        out_file = stderr;
    }
    else
    {
        /* Handle "path to file" filenames. */
        string out_name;
        if ( out[0] == '"' && out[strlen(out) - 1] == '"' )
        {
            string_copy(&out_name,out+1);
            string_truncate(&out_name,out_name.size-1);
        }
        else
        {
            string_copy(&out_name,out);
        }
        out_file = fopen( out_name.value, "w" );
        if (!out_file)
        {
            printf( "failed to write output file '%s'!\n", out_name.value );
            exit( EXITBAD );
        }
        string_free(&out_name);
    }

    while( *in && in < ine )
    {
        int dollar = 0;
        const char * output_0 = in;
        const char * output_1 = in;

        /* Copy white space */

        while ( output_1 < ine && *output_1 && isspace( *output_1 ) )
        {
            ++output_1;
        }
        if ( output_0 < output_1 )
        {
            fwrite(output_0,output_1-output_0,1,out_file);
        }
        output_0 = output_1;

        /* Copy non-white space, watching for variables */

        while( output_1 < ine && *output_1 && !isspace( *output_1 ) )
        {
            if( output_1[0] == '$' && output_1[1] && output_1[1] == '(' )
            {
                dollar++;
            }
            ++output_1;
        }

        /* If a variable encountered, expand it and and embed the */
        /* space-separated members of the list in the output. */

        if( dollar )
        {
            LIST *l;

            l = var_expand( L0, (char*)output_0, (char*)output_1, lol, 0 );

            while ( l )
            {
                fputs( l->string, out_file );
                l = list_next( l );
                if ( l ) fputc( ' ', out_file );
            }

            list_free( l );
        }
        else if ( output_0 < output_1 )
        {
            fwrite(output_0,output_1-output_0,1,out_file);
        }

        in = output_1;
    }

    if ( out_file != stdout && out_file != stderr )
    {
        fflush( out_file );
        fclose( out_file );
    }
}
Exemple #8
0
/* TODO : split this function in two so it becomes smaller */
SIGNATURE *signature_from_string(SSH_SESSION *session, STRING *signature,
    PUBLIC_KEY *pubkey, int needed_type) {
  SIGNATURE *sign = NULL;
  BUFFER *tmpbuf = NULL;
  STRING *rs = NULL;
  STRING *type_s = NULL;
  STRING *e = NULL;
  char *type_c = NULL;
  int type;
  int len;
  int rsalen;
#ifdef HAVE_LIBGCRYPT
  gcry_sexp_t sig;
#elif defined HAVE_LIBCRYPTO
  DSA_SIG *sig = NULL;
  STRING *r = NULL;
  STRING *s = NULL;
#endif

  sign = malloc(sizeof(SIGNATURE));
  if (sign == NULL) {
    ssh_set_error(session, SSH_FATAL, "Not enough space");
    return NULL;
  }

  tmpbuf = buffer_new();
  if (tmpbuf == NULL) {
    ssh_set_error(session, SSH_FATAL, "Not enough space");
    signature_free(sign);
    return NULL;
  }

  if (buffer_add_data(tmpbuf, signature->string, string_len(signature)) < 0) {
    signature_free(sign);
    buffer_free(tmpbuf);
    return NULL;
  }

  type_s = buffer_get_ssh_string(tmpbuf);
  if (type_s == NULL) {
    ssh_set_error(session, SSH_FATAL, "Invalid signature packet");
    signature_free(sign);
    buffer_free(tmpbuf);
    return NULL;
  }

  type_c = string_to_char(type_s);
  string_free(type_s);
  if (type_c == NULL) {
    signature_free(sign);
    buffer_free(tmpbuf);
    return NULL;
  }
  type = ssh_type_from_name(type_c);
  SAFE_FREE(type_c);

  if (needed_type != type) {
    ssh_set_error(session, SSH_FATAL, "Invalid signature type: %s",
        ssh_type_to_char(type));
    signature_free(sign);
    buffer_free(tmpbuf);
    return NULL;
  }

  switch(needed_type) {
    case TYPE_DSS:
      rs = buffer_get_ssh_string(tmpbuf);
      buffer_free(tmpbuf);

      /* 40 is the dual signature blob len. */
      if (rs == NULL || string_len(rs) != 40) {
        string_free(rs);
        signature_free(sign);
        return NULL;
      }

      /* we make use of strings (because we have all-made functions to convert
       * them to bignums (ou pas ;) */
#ifdef HAVE_LIBGCRYPT
      if (gcry_sexp_build(&sig, NULL, "(sig-val(dsa(r %b)(s %b)))",
            20 ,rs->string, 20, rs->string + 20)) {
        string_free(rs);
        signature_free(sign);
        return NULL;
      }
#elif defined HAVE_LIBCRYPTO
      r = string_new(20);
      s = string_new(20);
      if (r == NULL || s == NULL) {
        string_free(r);
        string_free(s);
        string_free(rs);
        signature_free(sign);
        return NULL;
      }

      string_fill(r, rs->string, 20);
      string_fill(s, rs->string + 20, 20);

      sig = DSA_SIG_new();
      if (sig == NULL) {
        string_free(r);
        string_free(s);
        string_free(rs);
        signature_free(sign);
        return NULL;
      }
      sig->r = make_string_bn(r); /* is that really portable ? Openssh's hack isn't better */
      sig->s = make_string_bn(s);
      string_free(r);
      string_free(s);

      if (sig->r == NULL || sig->s == NULL) {
        string_free(rs);
        DSA_SIG_free(sig);
        signature_free(sign);
        return NULL;
      }
#endif

#ifdef DEBUG_CRYPTO
      ssh_print_hexa("r", rs->string, 20);
      ssh_print_hexa("s", rs->string + 20, 20);
#endif
      string_free(rs);

      sign->type = TYPE_DSS;
      sign->dsa_sign = sig;

      return sign;
    case TYPE_RSA:
      e = buffer_get_ssh_string(tmpbuf);
      buffer_free(tmpbuf);
      if (e == NULL) {
        signature_free(sign);
        return NULL;
      }
      len = string_len(e);
#ifdef HAVE_LIBGCRYPT
      rsalen = (gcry_pk_get_nbits(pubkey->rsa_pub) + 7) / 8;
#elif defined HAVE_LIBCRYPTO
      rsalen = RSA_size(pubkey->rsa_pub);
#endif
      if (len > rsalen) {
        string_free(e);
        signature_free(sign);
        ssh_set_error(session, SSH_FATAL, "Signature too big! %d instead of %d",
            len, rsalen);
        return NULL;
      }

      if (len < rsalen) {
        ssh_log(session, SSH_LOG_RARE, "RSA signature len %d < %d",
            len, rsalen);
      }
      sign->type = TYPE_RSA;
#ifdef HAVE_LIBGCRYPT
      if (gcry_sexp_build(&sig, NULL, "(sig-val(rsa(s %b)))",
          string_len(e), e->string)) {
        signature_free(sign);
        string_free(e);
        return NULL;
      }

      sign->rsa_sign = sig;
#elif defined HAVE_LIBCRYPTO
      sign->rsa_sign = e;
#endif

#ifdef DEBUG_CRYPTO
      ssh_log(session, SSH_LOG_FUNCTIONS, "len e: %d", len);
      ssh_print_hexa("RSA signature", e->string, len);
#endif

#ifdef HAVE_LIBGCRYPT
      string_free(e);
#endif

      return sign;
    default:
      return NULL;
  }

  return NULL;
}
Exemple #9
0
void exec_cmd
(
    string const * cmd_orig,
    int flags,
    ExecCmdCallback func,
    void * closure,
    LIST * shell
)
{
    int const slot = get_free_cmdtab_slot();
    int const is_raw_cmd = is_raw_command_request( shell );
    string cmd_local[ 1 ];

    /* Initialize default shell - anything more than /Q/C is non-portable. */
    static LIST * default_shell;
    if ( !default_shell )
        default_shell = list_new( object_new( "cmd.exe /Q/C" ) );

    /* Specifying no shell means requesting the default shell. */
    if ( list_empty( shell ) )
        shell = default_shell;

    if ( DEBUG_EXECCMD )
        if ( is_raw_cmd )
            out_printf( "Executing raw command directly\n" );
        else
        {
            out_printf( "Executing using a command file and the shell: " );
            list_print( shell );
            out_printf( "\n" );
        }

    /* If we are running a raw command directly - trim its leading whitespaces
     * as well as any trailing all-whitespace lines but keep any trailing
     * whitespace in the final/only line containing something other than
     * whitespace).
     */
    if ( is_raw_cmd )
    {
        char const * start = cmd_orig->value;
        char const * p = cmd_orig->value + cmd_orig->size;
        char const * end = p;
        while ( isspace( *start ) ) ++start;
        while ( p > start && isspace( p[ -1 ] ) )
            if ( *--p == '\n' )
                end = p;
        string_new( cmd_local );
        string_append_range( cmd_local, start, end );
        assert( cmd_local->size == raw_command_length( cmd_orig->value ) );
    }
    /* If we are not running a raw command directly, prepare a command file to
     * be executed using an external shell and the actual command string using
     * that command file.
     */
    else
    {
        char const * const cmd_file = prepare_command_file( cmd_orig, slot );
        char const * argv[ MAXARGC + 1 ];  /* +1 for NULL */
        argv_from_shell( argv, shell, cmd_file, slot );
        string_new_from_argv( cmd_local, argv );
    }

    /* Catch interrupts whenever commands are running. */
    if ( !intr_installed )
    {
        intr_installed = 1;
        signal( SIGINT, onintr );
    }

    cmdtab[ slot ].flags = flags;

    /* Save input data into the selected running commands table slot. */
    cmdtab[ slot ].func = func;
    cmdtab[ slot ].closure = closure;

    /* Invoke the actual external process using the constructed command line. */
    invoke_cmd( cmd_local->value, slot );

    /* Free our local command string copy. */
    string_free( cmd_local );
}
Exemple #10
0
PUBLIC_KEY *publickey_make_dss(SSH_SESSION *session, BUFFER *buffer) {
  STRING *p = NULL;
  STRING *q = NULL;
  STRING *g = NULL;
  STRING *pubkey = NULL;
  PUBLIC_KEY *key = NULL;

  key = malloc(sizeof(PUBLIC_KEY));
  if (key == NULL) {
    buffer_free(buffer);
    return NULL;
  }

  key->type = TYPE_DSS;
  key->type_c = ssh_type_to_char(key->type);

  p = buffer_get_ssh_string(buffer);
  q = buffer_get_ssh_string(buffer);
  g = buffer_get_ssh_string(buffer);
  pubkey = buffer_get_ssh_string(buffer);

  buffer_free(buffer); /* we don't need it anymore */

  if (p == NULL || q == NULL || g == NULL || pubkey == NULL) {
    ssh_set_error(session, SSH_FATAL, "Invalid DSA public key");
    goto error;
  }

#ifdef HAVE_LIBGCRYPT
  gcry_sexp_build(&key->dsa_pub, NULL,
      "(public-key(dsa(p %b)(q %b)(g %b)(y %b)))",
      string_len(p), p->string,
      string_len(q), q->string,
      string_len(g), g->string,
      string_len(pubkey), pubkey->string);
  if (key->dsa_pub == NULL) {
    goto error;
  }
#elif defined HAVE_LIBCRYPTO

  key->dsa_pub = DSA_new();
  if (key->dsa_pub == NULL) {
    goto error;
  }
  key->dsa_pub->p = make_string_bn(p);
  key->dsa_pub->q = make_string_bn(q);
  key->dsa_pub->g = make_string_bn(g);
  key->dsa_pub->pub_key = make_string_bn(pubkey);
  if (key->dsa_pub->p == NULL ||
      key->dsa_pub->q == NULL ||
      key->dsa_pub->g == NULL ||
      key->dsa_pub->pub_key == NULL) {
    goto error;
  }
#endif /* HAVE_LIBCRYPTO */

#ifdef DEBUG_CRYPTO
  ssh_print_hexa("p", p->string, string_len(p));
  ssh_print_hexa("q", q->string, string_len(q));
  ssh_print_hexa("g", g->string, string_len(g));
#endif

  string_burn(p);
  string_free(p);
  string_burn(q);
  string_free(q);
  string_burn(g);
  string_free(g);
  string_burn(pubkey);
  string_free(pubkey);

  return key;
error:
  string_burn(p);
  string_free(p);
  string_burn(q);
  string_free(q);
  string_burn(g);
  string_free(g);
  string_burn(pubkey);
  string_free(pubkey);
  publickey_free(key);

  return NULL;
}
Exemple #11
0
/* Signature decoding functions */
static STRING *signature_to_string(SIGNATURE *sign) {
  unsigned char buffer[40] = {0};
  BUFFER *tmpbuf = NULL;
  STRING *str = NULL;
  STRING *tmp = NULL;
  STRING *rs = NULL;
  int rc = -1;
#ifdef HAVE_LIBGCRYPT
  const char *r = NULL;
  const char *s = NULL;
  gcry_sexp_t sexp;
  size_t size = 0;
#elif defined HAVE_LIBCRYPTO
  STRING *r = NULL;
  STRING *s = NULL;
#endif

  tmpbuf = buffer_new();
  if (tmpbuf == NULL) {
    return NULL;
  }

  tmp = string_from_char(ssh_type_to_char(sign->type));
  if (tmp == NULL) {
    buffer_free(tmpbuf);
    return NULL;
  }
  if (buffer_add_ssh_string(tmpbuf, tmp) < 0) {
    buffer_free(tmpbuf);
    string_free(tmp);
    return NULL;
  }
  string_free(tmp);

  switch(sign->type) {
    case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
      sexp = gcry_sexp_find_token(sign->dsa_sign, "r", 0);
      if (sexp == NULL) {
        buffer_free(tmpbuf);
        return NULL;
      }
      r = gcry_sexp_nth_data(sexp, 1, &size);
      if (*r == 0) {      /* libgcrypt put 0 when first bit is set */
        size--;
        r++;
      }
      memcpy(buffer, r + size - 20, 20);
      gcry_sexp_release(sexp);

      sexp = gcry_sexp_find_token(sign->dsa_sign, "s", 0);
      if (sexp == NULL) {
        buffer_free(tmpbuf);
        return NULL;
      }
      s = gcry_sexp_nth_data(sexp,1,&size);
      if (*s == 0) {
        size--;
        s++;
      }
      memcpy(buffer+ 20, s + size - 20, 20);
      gcry_sexp_release(sexp);
#elif defined HAVE_LIBCRYPTO
      r = make_bignum_string(sign->dsa_sign->r);
      if (r == NULL) {
        buffer_free(tmpbuf);
        return NULL;
      }
      s = make_bignum_string(sign->dsa_sign->s);
      if (s == NULL) {
        buffer_free(tmpbuf);
        string_free(r);
        return NULL;
      }

      memcpy(buffer, r->string + string_len(r) - 20, 20);
      memcpy(buffer + 20, s->string + string_len(s) - 20, 20);

      string_free(r);
      string_free(s);
#endif /* HAVE_LIBCRYPTO */
      rs = string_new(40);
      if (rs == NULL) {
        buffer_free(tmpbuf);
        return NULL;
      }

      string_fill(rs, buffer, 40);
      rc = buffer_add_ssh_string(tmpbuf, rs);
      string_free(rs);
      if (rc < 0) {
        buffer_free(tmpbuf);
        return NULL;
      }

      break;
    case TYPE_RSA:
    case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
      sexp = gcry_sexp_find_token(sign->rsa_sign, "s", 0);
      if (sexp == NULL) {
        buffer_free(tmpbuf);
        return NULL;
      }
      s = gcry_sexp_nth_data(sexp,1,&size);
      if (*s == 0) {
        size--;
        s++;
      }
      rs = string_new(size);
      if (rs == NULL) {
        buffer_free(tmpbuf);
        return NULL;
      }

      string_fill(rs, (char *) s, size);
      rc = buffer_add_ssh_string(tmpbuf, rs);
      gcry_sexp_release(sexp);
      string_free(rs);
      if (rc < 0) {
        buffer_free(tmpbuf);
        return NULL;
      }
#elif defined HAVE_LIBCRYPTO
      if (buffer_add_ssh_string(tmpbuf,sign->rsa_sign) < 0) {
        buffer_free(tmpbuf);
        return NULL;
      }
#endif
      break;
  }

  str = string_new(buffer_get_len(tmpbuf));
  if (str == NULL) {
    buffer_free(tmpbuf);
    return NULL;
  }
  string_fill(str, buffer_get(tmpbuf), buffer_get_len(tmpbuf));
  buffer_free(tmpbuf);

  return str;
}
Exemple #12
0
static int rsa_public_to_string(gcry_sexp_t key, BUFFER *buffer) {
#elif defined HAVE_LIBCRYPTO
static int rsa_public_to_string(RSA *key, BUFFER *buffer) {
#endif

  STRING *e = NULL;
  STRING *n = NULL;

  int rc = -1;

#ifdef HAVE_LIBGCRYPT
  const char *tmp;
  size_t size;
  gcry_sexp_t sexp;

  sexp = gcry_sexp_find_token(key, "n", 0);
  if (sexp == NULL) {
    goto error;
  }
  tmp = gcry_sexp_nth_data(sexp, 1, &size);
  n = string_new(size);
  if (n == NULL) {
    goto error;
  }
  string_fill(n, (char *) tmp, size);
  gcry_sexp_release(sexp);

  sexp = gcry_sexp_find_token(key, "e", 0);
  if (sexp == NULL) {
    goto error;
  }
  tmp = gcry_sexp_nth_data(sexp, 1, &size);
  e = string_new(size);
  if (e == NULL) {
    goto error;
  }
  string_fill(e, (char *) tmp, size);

#elif defined HAVE_LIBCRYPTO
  e = make_bignum_string(key->e);
  n = make_bignum_string(key->n);
  if (e == NULL || n == NULL) {
    goto error;
  }
#endif

  if (buffer_add_ssh_string(buffer, e) < 0) {
    goto error;
  }
  if (buffer_add_ssh_string(buffer, n) < 0) {
    goto error;
  }

  rc = 0;
error:
#ifdef HAVE_LIBGCRYPT
  gcry_sexp_release(sexp);
#endif

  string_burn(e);
  string_free(e);
  string_burn(n);
  string_free(n);

  return rc;
}
Exemple #13
0
static int dsa_public_to_string(gcry_sexp_t key, BUFFER *buffer) {
#elif defined HAVE_LIBCRYPTO
static int dsa_public_to_string(DSA *key, BUFFER *buffer) {
#endif
  STRING *p = NULL;
  STRING *q = NULL;
  STRING *g = NULL;
  STRING *n = NULL;

  int rc = -1;

#ifdef HAVE_LIBGCRYPT
  const char *tmp = NULL;
  size_t size;
  gcry_sexp_t sexp;

  sexp = gcry_sexp_find_token(key, "p", 0);
  if (sexp == NULL) {
    goto error;
  }
  tmp = gcry_sexp_nth_data(sexp, 1, &size);
  p = string_new(size);
  if (p == NULL) {
    goto error;
  }
  string_fill(p, (char *) tmp, size);
  gcry_sexp_release(sexp);

  sexp = gcry_sexp_find_token(key, "q", 0);
  if (sexp == NULL) {
    goto error;
  }
  tmp = gcry_sexp_nth_data(sexp, 1, &size);
  q = string_new(size);
  if (q == NULL) {
    goto error;
  }
  string_fill(q, (char *) tmp, size);
  gcry_sexp_release(sexp);

  sexp = gcry_sexp_find_token(key, "g", 0);
  if (sexp == NULL) {
    goto error;
  }
  tmp = gcry_sexp_nth_data(sexp, 1, &size);
  g = string_new(size);
  if (g == NULL) {
    goto error;
  }
  string_fill(g, (char *) tmp, size);
  gcry_sexp_release(sexp);

  sexp = gcry_sexp_find_token(key, "y", 0);
  if (sexp == NULL) {
    goto error;
  }
  tmp = gcry_sexp_nth_data(sexp, 1, &size);
  n = string_new(size);
  if (n == NULL) {
    goto error;
  }
  string_fill(n, (char *) tmp, size);
  gcry_sexp_release(sexp);

#elif defined HAVE_LIBCRYPTO
  p = make_bignum_string(key->p);
  q = make_bignum_string(key->q);
  g = make_bignum_string(key->g);
  n = make_bignum_string(key->pub_key);
  if (p == NULL || q == NULL || g == NULL || n == NULL) {
    goto error;
  }
#endif /* HAVE_LIBCRYPTO */
  if (buffer_add_ssh_string(buffer, p) < 0) {
    goto error;
  }
  if (buffer_add_ssh_string(buffer, q) < 0) {
    goto error;
  }
  if (buffer_add_ssh_string(buffer, g) < 0) {
    goto error;
  }
  if (buffer_add_ssh_string(buffer, n) < 0) {
    goto error;
  }

  rc = 0;
error:
#ifdef HAVE_LIBGCRYPT
  gcry_sexp_release(sexp);
#endif

  string_burn(p);
  string_free(p);
  string_burn(q);
  string_free(q);
  string_burn(g);
  string_free(g);
  string_burn(n);
  string_free(n);

  return rc;
}
Exemple #14
0
/** \brief Makes a PUBLIC_KEY object out of a PRIVATE_KEY object
 * \param prv the Private key
 * \returns the public key
 * \see publickey_to_string()
 */
PUBLIC_KEY *publickey_from_privatekey(PRIVATE_KEY *prv) {
  PUBLIC_KEY *key = NULL;
#ifdef HAVE_LIBGCRYPT
  gcry_sexp_t sexp;
  const char *tmp = NULL;
  size_t size;
  STRING *p = NULL;
  STRING *q = NULL;
  STRING *g = NULL;
  STRING *y = NULL;
  STRING *e = NULL;
  STRING *n = NULL;
#endif /* HAVE_LIBGCRYPT */

  key = malloc(sizeof(PUBLIC_KEY));
  if (key == NULL) {
    return NULL;
  }

  key->type = prv->type;
  switch(key->type) {
    case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
      sexp = gcry_sexp_find_token(prv->dsa_priv, "p", 0);
      if (sexp == NULL) {
        goto error;
      }
      tmp = gcry_sexp_nth_data(sexp, 1, &size);
      p = string_new(size);
      if (p == NULL) {
        goto error;
      }
      string_fill(p,(char *) tmp, size);
      gcry_sexp_release(sexp);

      sexp = gcry_sexp_find_token(prv->dsa_priv,"q",0);
      if (sexp == NULL) {
        goto error;
      }
      tmp = gcry_sexp_nth_data(sexp,1,&size);
      q = string_new(size);
      if (q == NULL) {
        goto error;
      }
      string_fill(q,(char *) tmp,size);
      gcry_sexp_release(sexp);

      sexp = gcry_sexp_find_token(prv->dsa_priv, "g", 0);
      if (sexp == NULL) {
        goto error;
      }
      tmp = gcry_sexp_nth_data(sexp,1,&size);
      g = string_new(size);
      if (g == NULL) {
        goto error;
      }
      string_fill(g,(char *) tmp,size);
      gcry_sexp_release(sexp);

      sexp = gcry_sexp_find_token(prv->dsa_priv,"y",0);
      if (sexp == NULL) {
        goto error;
      }
      tmp = gcry_sexp_nth_data(sexp,1,&size);
      y = string_new(size);
      if (y == NULL) {
        goto error;
      }
      string_fill(y,(char *) tmp,size);
      gcry_sexp_release(sexp);

      gcry_sexp_build(&key->dsa_pub, NULL,
          "(public-key(dsa(p %b)(q %b)(g %b)(y %b)))",
          string_len(p), p->string,
          string_len(q), q->string,
          string_len(g), g->string,
          string_len(y), y->string);

      string_burn(p);
      string_free(p);
      string_burn(q);
      string_free(q);
      string_burn(g);
      string_free(g);
      string_burn(y);
      string_free(y);
#elif defined HAVE_LIBCRYPTO
      key->dsa_pub = DSA_new();
      if (key->dsa_pub == NULL) {
        goto error;
      }
      key->dsa_pub->p = BN_dup(prv->dsa_priv->p);
      key->dsa_pub->q = BN_dup(prv->dsa_priv->q);
      key->dsa_pub->g = BN_dup(prv->dsa_priv->g);
      key->dsa_pub->pub_key = BN_dup(prv->dsa_priv->pub_key);
      if (key->dsa_pub->p == NULL ||
          key->dsa_pub->q == NULL ||
          key->dsa_pub->g == NULL ||
          key->dsa_pub->pub_key == NULL) {
        goto error;
      }
#endif /* HAVE_LIBCRYPTO */
      break;
    case TYPE_RSA:
    case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
      sexp = gcry_sexp_find_token(prv->rsa_priv, "n", 0);
      if (sexp == NULL) {
        goto error;
      }
      tmp = gcry_sexp_nth_data(sexp, 1, &size);
      n = string_new(size);
      if (n == NULL) {
        goto error;
      }
      string_fill(n, (char *) tmp, size);
      gcry_sexp_release(sexp);

      sexp = gcry_sexp_find_token(prv->rsa_priv, "e", 0);
      if (sexp == NULL) {
        goto error;
      }
      tmp = gcry_sexp_nth_data(sexp, 1, &size);
      e = string_new(size);
      if (e == NULL) {
        goto error;
      }
      string_fill(e, (char *) tmp, size);
      gcry_sexp_release(sexp);

      gcry_sexp_build(&key->rsa_pub, NULL,
          "(public-key(rsa(n %b)(e %b)))",
          string_len(n), n->string,
          string_len(e), e->string);
      if (key->rsa_pub == NULL) {
        goto error;
      }

      string_burn(e);
      string_free(e);
      string_burn(n);
      string_free(n);
#elif defined HAVE_LIBCRYPTO
      key->rsa_pub = RSA_new();
      if (key->rsa_pub == NULL) {
        goto error;
      }
      key->rsa_pub->e = BN_dup(prv->rsa_priv->e);
      key->rsa_pub->n = BN_dup(prv->rsa_priv->n);
      if (key->rsa_pub->e == NULL ||
          key->rsa_pub->n == NULL) {
        goto error;
      }
#endif
      break;
  }
  key->type_c = ssh_type_to_char(prv->type);

  return key;
error:
#ifdef HAVE_LIBGCRYPT
  gcry_sexp_release(sexp);
  string_burn(p);
  string_free(p);
  string_burn(q);
  string_free(q);
  string_burn(g);
  string_free(g);
  string_burn(y);
  string_free(y);

  string_burn(e);
  string_free(e);
  string_burn(n);
  string_free(n);
#endif
  publickey_free(key);

  return NULL;
}
Exemple #15
0
/*
 * This function concats in a buffer the values needed to do a signature
 * verification.
 */
static ssh_buffer ssh_msg_userauth_build_digest(ssh_session session,
                                                ssh_message msg,
                                                const char *service)
{
    struct ssh_crypto_struct *crypto =
        session->current_crypto ? session->current_crypto :
                                  session->next_crypto;
    ssh_buffer buffer;
    ssh_string str;
    int rc;

    buffer = ssh_buffer_new();
    if (buffer == NULL) {
        return NULL;
    }

    /* Add session id */
    str  = ssh_string_new(crypto->digest_len);
    if (str == NULL) {
        ssh_buffer_free(buffer);
        return NULL;
    }
    ssh_string_fill(str, crypto->session_id, crypto->digest_len);

    rc = buffer_add_ssh_string(buffer, str);
    string_free(str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Add the type */
    rc = buffer_add_u8(buffer, SSH2_MSG_USERAUTH_REQUEST);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Add the username */
    str = ssh_string_from_char(msg->auth_request.username);
    if (str == NULL) {
        ssh_buffer_free(buffer);
        return NULL;
    }
    rc = buffer_add_ssh_string(buffer, str);
    string_free(str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Add the service name */
    str = ssh_string_from_char(service);
    if (str == NULL) {
        ssh_buffer_free(buffer);
        return NULL;
    }
    rc = buffer_add_ssh_string(buffer, str);
    string_free(str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Add the method (publickey) */
    str = ssh_string_from_char("publickey");
    if (str == NULL) {
        ssh_buffer_free(buffer);
        return NULL;
    }
    rc = buffer_add_ssh_string(buffer, str);
    string_free(str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Has been signed (TRUE) */
    rc = buffer_add_u8(buffer, 1);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Add the public key algorithm */
    str = ssh_string_from_char(msg->auth_request.pubkey->type_c);
    if (str == NULL) {
        ssh_buffer_free(buffer);
        return NULL;
    }
    rc = buffer_add_ssh_string(buffer, str);
    string_free(str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    /* Add the publickey as blob */
    rc = ssh_pki_export_pubkey_blob(msg->auth_request.pubkey, &str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }
    rc = buffer_add_ssh_string(buffer, str);
    string_free(str);
    if (rc < 0) {
        ssh_buffer_free(buffer);
        return NULL;
    }

    return buffer;
}
Exemple #16
0
static void string_renew( string * const s )
{
    string_free( s );
    string_new( s );
}
Exemple #17
0
/* begin implementations */
static void rest_free_inner(t_rest *const rest) {
	ctw_free((struct _ctw *)rest);
	string_free(rest->cookie.login_path, &rest->cookie.login_path_len);
	string_free(rest->cookie.username, &rest->cookie.username_len);
	string_free(rest->cookie.password, &rest->cookie.password_len);
}
Exemple #18
0
int msg_queue_read() {
	struct dirent *d;
	DIR *dir;

	if (!(dir = opendir(prepare_pathf("queue"))))		/* opendir() ~/.ekg2/[PROFILE/]/queue */
		return -1;

	while ((d = readdir(dir))) {
		const char *fn;

		msg_queue_t m;
		struct stat st;
		string_t msg;
		char *buf;
		FILE *f;
		int filever = 0;

		if (!(fn = prepare_pathf("queue/%s", d->d_name)))
			continue;

		if (stat(fn, &st) || !S_ISREG(st.st_mode))
			continue;

		if (!(f = fopen(fn, "r")))
			continue;

		memset(&m, 0, sizeof(m));

		buf = read_file(f, 0);
		
		if (buf && *buf == 'v')
			filever = atoi(buf+1);
		if (!filever || filever > 2) {
			fclose(f);
			continue;
		}

		if (!(m.session = read_file(f, 1))) {
			fclose(f);
			continue;
		}
	
		if (!(m.rcpts = read_file(f, 1))) {
			xfree(m.session);
			fclose(f);
			continue;
		}

		if (!(buf = read_file(f, 0))) {
			xfree(m.session);
			xfree(m.rcpts);
			fclose(f);
			continue;
		}

		m.time = atoi(buf);

		if (!(m.seq = read_file(f, 1))) {
			xfree(m.session);
			xfree(m.rcpts);
			fclose(f);
			continue;
		}
	
		if (filever == 2) {
			if (!(buf = read_file(f, 0))) {
				xfree(m.session);
				xfree(m.rcpts);
				fclose(f);
				continue;
			}

			m.mclass = atoi(buf);
		} else
			m.mclass = EKG_MSGCLASS_SENT;

		msg = string_init(NULL);

		buf = read_file(f, 0);

		while (buf) {
			string_append(msg, buf);
			buf = read_file(f, 0);
			if (buf)
				string_append(msg, "\r\n");
		}

		m.message = string_free(msg, 0);

		msgs_queue_add(xmemdup(&m, sizeof(m)));

		fclose(f);
		unlink(fn);
	}

	closedir(dir);

	return 0;
}
Exemple #19
0
int
var_string(
	char	*in,
	char	*out,
	int	outsize,
	LOL	*lol )
{
	char 	*out0 = out;
	char	*oute = out + outsize - 1;

	while( *in )
	{
	    char	*lastword;
	    int		dollar = 0;

	    /* Copy white space */

	    while( isspace( *in ) )
	    {
		if( out >= oute )
		    return -1;

		*out++ = *in++;
	    }

	    lastword = out;

	    /* Copy non-white space, watching for variables */

	    while( *in && !isspace( *in ) )
	    {
	        if( out >= oute )
		    return -1;

		if( in[0] == '$' && in[1] == '(' )
		    dollar++;
                #ifdef OPT_AT_FILES
                else if ( in[0] == '@' && in[1] == '(' )
                {
                    int depth = 1;
                    char *ine = in + 2;
                    char *split = 0;

                    /* Scan the content of the response file @() section. */

                    while( *ine && depth > 0 )
                    {
                        switch( *ine )
                        {
                        case '(':
                            ++depth;
                            break;
                        case ')':
                            --depth;
                            break;
                        case ':':
                            if( depth == 1 && ine[1] == 'E' && ine[2] == '=' )
                            {
                                split = ine;
                            }
                           break;
                        }
                        ++ine;
                    }

                    if (!split)
                    {
                        printf( "no file specified!\n" );
                        exit( EXITBAD );
                    }

                    if ( depth == 0 )
                    {
                        string file_name_v;
                        int file_name_l = 0;
                        const char * file_name_s = 0;

                        /* expand the temporary file name var inline */
                        #if 0
                        string_copy(&file_name_v,"$(");
                        string_append_range(&file_name_v,in+2,split);
                        string_push_back(&file_name_v,')');
                        #else
                        string_new(&file_name_v);
                        string_append_range(&file_name_v,in+2,split);
                        #endif
                        file_name_l = var_string(file_name_v.value,out,oute-out+1,lol);
                        string_free(&file_name_v);
                        if ( file_name_l < 0 ) return -1;
                        file_name_s = out;

                        /* for stdout/stderr we will create a temp file and generate
                           a command that outputs the content as needed. */
                        if ( strcmp( "STDOUT", out ) == 0 || strcmp( "STDERR", out ) == 0 )
                        {
                            int err_redir = strcmp( "STDERR", out ) == 0;
                            out[0] = '\0';
                            file_name_s = path_tmpfile();
                            file_name_l = strlen(file_name_s);
                            #if defined( OS_NT ) || defined( OS_OS2 )
                            if ( (out+7+file_name_l+(err_redir?5:0)) >= oute ) return -1;
                            sprintf( out,"type \"%s\"%s",
                                file_name_s,
                                err_redir ? " 1>&2" : "" );
                            #else
                            if ( (out+6+file_name_l+(err_redir?5:0)) >= oute ) return -1;
                            sprintf( out,"cat \"%s\"%s",
                                file_name_s,
                                err_redir ? " 1>&2" : "" );
                            #endif
                            /* we also make sure that the temp files created by this
                               get nuked eventually. */
                            file_remove_atexit( file_name_s );
                        }

                        /* expand the file value into the file reference */
                        if ( !globs.noexec )
                            var_string_to_file( split+3, ine-split-4, file_name_s, lol );

                        /* continue on with the expansion */
                        out += strlen(out);
                    }

                    /* and continue with the parsing just past the @() reference */
                    in = ine;
                }
                #endif

		*out++ = *in++;
	    }

        /* Add zero to 'out' so that 'lastword' is correctly zero-terminated. */
        if (out >= oute)
            return -1;
        /* Don't increment, intentionally. */
        *out= '\0';

	    /* If a variable encountered, expand it and and embed the */
	    /* space-separated members of the list in the output. */

	    if( dollar )
	    {
		LIST	*l;

		l = var_expand( L0, lastword, out, lol, 0 );

		out = lastword;

		while ( l )
		{
		    int so = strlen( l->string );

		    if( out + so >= oute )
			return -1;

		    strcpy( out, l->string );
		    out += so;
		    l = list_next( l );
		    if ( l ) *out++ = ' ';
		}

		list_free( l );
	    }
	}

	if( out >= oute )
	    return -1;

	*out++ = '\0';

	return out - out0;
}
Exemple #20
0
void packet_parse(SSH_SESSION *session) {
  STRING *error_s = NULL;
  char *error = NULL;
  int type = session->in_packet.type;
  u32 tmp;

#ifdef HAVE_SSH1
  if (session->version == 1) {
    /* SSH-1 */
    switch(type) {
      case SSH_MSG_DISCONNECT:
        ssh_log(session, SSH_LOG_PACKET, "Received SSH_MSG_DISCONNECT");
        ssh_set_error(session, SSH_FATAL, "Received SSH_MSG_DISCONNECT");

        ssh_socket_close(session->socket);
        session->alive = 0;
        return;
      case SSH_SMSG_STDOUT_DATA:
      case SSH_SMSG_STDERR_DATA:
      case SSH_SMSG_EXITSTATUS:
        channel_handle1(session,type);
        return;
      case SSH_MSG_DEBUG:
      case SSH_MSG_IGNORE:
        break;
      default:
        ssh_log(session, SSH_LOG_PACKET,
            "Unexpected message code %d", type);
    }
    return;
  } else {
#endif /* HAVE_SSH1 */
    switch(type) {
      case SSH2_MSG_DISCONNECT:
        buffer_get_u32(session->in_buffer, &tmp);
        error_s = buffer_get_ssh_string(session->in_buffer);
        if (error_s == NULL) {
          return;
        }
        error = string_to_char(error_s);
        string_free(error_s);
        if (error == NULL) {
          return;
        }
        ssh_log(session, SSH_LOG_PACKET, "Received SSH_MSG_DISCONNECT\n");
        ssh_set_error(session, SSH_FATAL,
            "Received SSH_MSG_DISCONNECT: %s",error);

        SAFE_FREE(error);

        ssh_socket_close(session->socket);
        session->alive = 0;

        return;
      case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
      case SSH2_MSG_CHANNEL_DATA:
      case SSH2_MSG_CHANNEL_EXTENDED_DATA:
      case SSH2_MSG_CHANNEL_REQUEST:
      case SSH2_MSG_CHANNEL_EOF:
      case SSH2_MSG_CHANNEL_CLOSE:
        channel_handle(session,type);
      case SSH2_MSG_IGNORE:
      case SSH2_MSG_DEBUG:
        return;
      default:
        ssh_log(session, SSH_LOG_RARE, "Received unhandled packet %d", type);
    }
#ifdef HAVE_SSH1
  }
#endif
}
Exemple #21
0
/*
 * ui_readline_print()
 *
 * wy¶wietla dany tekst na ekranie, uwa¿aj±c na trwaj±ce w danych chwili
 * readline().
 */
void ui_readline_print(window_t *w, int separate, const /*locale*/ char *xline)
{
	int old_end = rl_end, id = w->id;
	char *old_prompt = NULL, *line_buf = NULL;
	const char *line = NULL;

	if (config_timestamp) {
			/* XXX: recode timestamp? for fun or wcs? */
		string_t s = string_init(NULL);
		const char *p = xline;
		const char *buf = timestamp(formated_config_timestamp);

		string_append(s, "\033[0m");
		string_append(s, buf);
		string_append_c(s, ' ');
		
		while (*p) {
			string_append_c(s, *p);
			if (*p == '\n' && *(p + 1)) {
				string_append(s, buf);
				string_append_c(s, ' ');
			}
			p++;
		}

		line = line_buf = string_free(s, 0);
	} else
		line = xline;

	/* je¶li nie piszemy do aktualnego, to zapisz do bufora i wyjd¼ */
	if (id != window_current->id) {
		window_write(id, line);

		/* XXX trzeba jeszcze waln±æ od¶wie¿enie prompta */
		goto done;
	}

	/* je¶li mamy ukrywaæ wszystko, wychodzimy */
	if (pager_lines == -2)
		goto done;

	window_write(window_current->id, line);

	/* ukryj prompt, je¶li jeste¶my w trakcie readline */
	if (in_readline) {
		old_prompt = g_strdup(rl_prompt);
		rl_end = 0;
/*		set_prompt(NULL);*/
		rl_redisplay();
			/* XXX: string width instead?
			 * or cleartoeol? */
		printf("\r%*c\r", (int) xstrlen(old_prompt), ' ');
	}

	printf("%s", line);

	if (pager_lines >= 0) {
		pager_lines++;

		if (pager_lines >= screen_lines - 2) {
			const gchar *prompt = format_find("readline_more");
			char *lprompt = ekg_recode_to_locale(prompt);
			char *tmp;
				/* XXX: lprompt pretty const, make it static? */

			in_readline++;

			set_prompt(lprompt);

			pager_lines = -1;
			tmp = readline(lprompt);
			g_free(lprompt);
			in_readline--;
			if (tmp) {
				free(tmp); /* allocd by readline */
				pager_lines = 0;
			} else {
				printf("\n");
				pager_lines = -2;
			}
			printf("\033[A\033[K");		/* XXX brzydko */
		}
	}

	/* je¶li jeste¶my w readline, poka¿ z powrotem prompt */
	if (in_readline) {
		rl_end = old_end;
		set_prompt(old_prompt);
		g_free(old_prompt);
		rl_forced_update_display();
	}
	
done:
	if (line_buf)
		g_free(line_buf);
}
Exemple #22
0
OBJECT * search( OBJECT * target, timestamp * const time,
    OBJECT * * another_target, int const file )
{
    PATHNAME f[ 1 ];
    LIST * varlist;
    string buf[ 1 ];
    int found = 0;
    OBJECT * boundname = 0;

    if ( another_target )
        *another_target = 0;

    if ( !explicit_bindings )
        explicit_bindings = hashinit( sizeof( BINDING ), "explicitly specified "
            "locations" );

    string_new( buf );

    /* Parse the filename. */
    path_parse( object_str( target ), f );

    f->f_grist.ptr = 0;
    f->f_grist.len = 0;

    varlist = var_get( root_module(), constant_LOCATE );
    if ( !list_empty( varlist ) )
    {
        OBJECT * key;
        f->f_root.ptr = object_str( list_front( varlist ) );
        f->f_root.len = strlen( object_str( list_front( varlist ) ) );

        path_build( f, buf );

        if ( DEBUG_SEARCH )
            printf( "locate %s: %s\n", object_str( target ), buf->value );

        key = object_new( buf->value );
        timestamp_from_path( time, key );
        object_free( key );
        found = 1;
    }
    else if ( varlist = var_get( root_module(), constant_SEARCH ),
        !list_empty( varlist ) )
    {
        LISTITER iter = list_begin( varlist );
        LISTITER const end = list_end( varlist );
        for ( ; iter != end; iter = list_next( iter ) )
        {
            BINDING * ba;
            file_info_t * ff;
            OBJECT * key;
            OBJECT * test_path;

            f->f_root.ptr = object_str( list_item( iter ) );
            f->f_root.len = strlen( object_str( list_item( iter ) ) );

            string_truncate( buf, 0 );
            path_build( f, buf );

            if ( DEBUG_SEARCH )
                printf( "search %s: %s\n", object_str( target ), buf->value );

            test_path = object_new( buf->value );
            key = path_as_key( test_path );
            object_free( test_path );
            ff = file_query( key );
            timestamp_from_path( time, key );

            if ( ( ba = (BINDING *)hash_find( explicit_bindings, key ) ) )
            {
                if ( DEBUG_SEARCH )
                    printf(" search %s: found explicitly located target %s\n",
                        object_str( target ), object_str( ba->target ) );
                if ( another_target )
                    *another_target = ba->target;
                found = 1;
                object_free( key );
                break;
            }
            else if ( ff )
            {
                if ( !file || ff->is_file )
                {
                    found = 1;
                    object_free( key );
                    break;
                }
            }
            object_free( key );
        }
    }

    if ( !found )
    {
        /* Look for the obvious. */
        /* This is a questionable move. Should we look in the obvious place if
         * SEARCH is set?
         */
        OBJECT * key;

        f->f_root.ptr = 0;
        f->f_root.len = 0;

        string_truncate( buf, 0 );
        path_build( f, buf );

        if ( DEBUG_SEARCH )
            printf( "search %s: %s\n", object_str( target ), buf->value );

        key = object_new( buf->value );
        timestamp_from_path( time, key );
        object_free( key );
    }

    boundname = object_new( buf->value );
    string_free( buf );

    /* Prepare a call to BINDRULE if the variable is set. */
    call_bind_rule( target, boundname );

    return boundname;
}
Exemple #23
0
/*
 * Find the default paths to all of our important sub-directories.
 *
 * The purpose of each sub-directory is described in "variable.c".
 *
 * All of the sub-directories should, by default, be located inside
 * the main "lib" directory, whose location is very system dependant.
 *
 * This function takes a writable buffer, initially containing the
 * "path" to the "lib" directory, for example, "/pkg/lib/angband/",
 * or a system dependant string, for example, ":lib:".  The buffer
 * must be large enough to contain at least 32 more characters.
 *
 * Various command line options may allow some of the important
 * directories to be changed to user-specified directories, most
 * importantly, the "info" and "user" and "save" directories,
 * but this is done after this function, see "main.c".
 *
 * In general, the initial path should end in the appropriate "PATH_SEP"
 * string.  All of the "sub-directory" paths (created below or supplied
 * by the user) will NOT end in the "PATH_SEP" string, see the special
 * "path_build()" function in "util.c" for more information.
 *
 * Mega-Hack -- support fat raw files under NEXTSTEP, using special
 * "suffixed" directories for the "ANGBAND_DIR_DATA" directory, but
 * requiring the directories to be created by hand by the user.
 *
 * Hack -- first we free all the strings, since this is known
 * to succeed even if the strings have not been allocated yet,
 * as long as the variables start out as "NULL".  This allows
 * this function to be called multiple times, for example, to
 * try several base "path" values until a good one is found.
 */
void init_file_paths(char *path)
{
	char *tail;

#ifdef SET_UID
	char buf[1024];
#endif /* SET_UID */

	/*** Free everything ***/

	/* Free the main path */
	string_free(ANGBAND_DIR);

	/* Free the sub-paths */
	string_free(ANGBAND_DIR_APEX);
	string_free(ANGBAND_DIR_BONE);
	string_free(ANGBAND_DIR_DATA);
	string_free(ANGBAND_DIR_EDIT);
	string_free(ANGBAND_DIR_FILE);
	string_free(ANGBAND_DIR_HELP);
	string_free(ANGBAND_DIR_INFO);
	string_free(ANGBAND_DIR_SAVE);
	string_free(ANGBAND_DIR_PREF);
	string_free(ANGBAND_DIR_USER);
	string_free(ANGBAND_DIR_XTRA);


	/*** Prepare the "path" ***/

	/* Hack -- save the main directory */
	ANGBAND_DIR = string_make(path);

	/* Prepare to append to the Base Path */
	tail = path + strlen(path);


#ifdef VM


	/*** Use "flat" paths with VM/ESA ***/

	/* Use "blank" path names */
	ANGBAND_DIR_APEX = string_make("");
	ANGBAND_DIR_BONE = string_make("");
	ANGBAND_DIR_DATA = string_make("");
	ANGBAND_DIR_EDIT = string_make("");
	ANGBAND_DIR_FILE = string_make("");
	ANGBAND_DIR_HELP = string_make("");
	ANGBAND_DIR_INFO = string_make("");
	ANGBAND_DIR_SAVE = string_make("");
	ANGBAND_DIR_PREF = string_make("");
	ANGBAND_DIR_USER = string_make("");
	ANGBAND_DIR_XTRA = string_make("");


#else /* VM */


	/*** Build the sub-directory names ***/

	/* Build a path name */
	strcpy(tail, "apex");
	ANGBAND_DIR_APEX = string_make(path);

	/* Build a path name */
	strcpy(tail, "bone");
	ANGBAND_DIR_BONE = string_make(path);

	/* Build a path name */
	strcpy(tail, "data");
	ANGBAND_DIR_DATA = string_make(path);

	/* Build a path name */
	strcpy(tail, "edit");
	ANGBAND_DIR_EDIT = string_make(path);

	/* Build a path name */
	strcpy(tail, "file");
	ANGBAND_DIR_FILE = string_make(path);

	/* Build a path name */
	strcpy(tail, "help");
	ANGBAND_DIR_HELP = string_make(path);

	/* Build a path name */
	strcpy(tail, "info");
	ANGBAND_DIR_INFO = string_make(path);

	/* Build a path name */
	strcpy(tail, "save");
	ANGBAND_DIR_SAVE = string_make(path);

	/* Build a path name */
	strcpy(tail, "pref");
	ANGBAND_DIR_PREF = string_make(path);

#ifdef PRIVATE_USER_PATH

	/* Build the path to the user specific directory */
	path_build(buf, 1024, PRIVATE_USER_PATH, VERSION_NAME);

	/* Build a relative path name */
	ANGBAND_DIR_USER = string_make(buf);

#else /* PRIVATE_USER_PATH */

	/* Build a path name */
	strcpy(tail, "user");
	ANGBAND_DIR_USER = string_make(path);

#endif /* PRIVATE_USER_PATH */

	/* Build a path name */
	strcpy(tail, "xtra");
	ANGBAND_DIR_XTRA = string_make(path);

#endif /* VM */


#ifdef NeXT

	/* Allow "fat binary" usage with NeXT */
	if (TRUE)
	{
		cptr next = NULL;

# if defined(m68k)
		next = "m68k";
# endif

# if defined(i386)
		next = "i386";
# endif

# if defined(sparc)
		next = "sparc";
# endif

# if defined(hppa)
		next = "hppa";
# endif

		/* Use special directory */
		if (next)
		{
			/* Forget the old path name */
			string_free(ANGBAND_DIR_DATA);

			/* Build a new path name */
			sprintf(tail, "data-%s", next);
			ANGBAND_DIR_DATA = string_make(path);
		}
	}

#endif /* NeXT */

}
Exemple #24
0
void module_reset_dir(cptr dir, cptr new_path)
{
	cptr *d = 0;
	char buf[1025];

	if (!strcmp(dir, "apex")) d = &ANGBAND_DIR_APEX;
	if (!strcmp(dir, "bone")) d = &ANGBAND_DIR_BONE;
	if (!strcmp(dir, "core")) d = &ANGBAND_DIR_CORE;
	if (!strcmp(dir, "dngn")) d = &ANGBAND_DIR_DNGN;
	if (!strcmp(dir, "data")) d = &ANGBAND_DIR_DATA;
	if (!strcmp(dir, "edit")) d = &ANGBAND_DIR_EDIT;
	if (!strcmp(dir, "file")) d = &ANGBAND_DIR_FILE;
	if (!strcmp(dir, "help")) d = &ANGBAND_DIR_HELP;
	if (!strcmp(dir, "info")) d = &ANGBAND_DIR_INFO;
	if (!strcmp(dir, "scpt")) d = &ANGBAND_DIR_SCPT;
	if (!strcmp(dir, "patch")) d = &ANGBAND_DIR_PATCH;
	if (!strcmp(dir, "pref")) d = &ANGBAND_DIR_PREF;
	if (!strcmp(dir, "xtra")) d = &ANGBAND_DIR_XTRA;
	if (!strcmp(dir, "user")) d = &ANGBAND_DIR_USER;
	if (!strcmp(dir, "note")) d = &ANGBAND_DIR_NOTE;
	if (!strcmp(dir, "cmov")) d = &ANGBAND_DIR_CMOV;
#ifndef PRIVATE_USER_PATH
	if (!strcmp(dir, "save")) d = &ANGBAND_DIR_SAVE;
#else /* PRIVATE_USER_PATH */
	if (
#ifdef PRIVATE_USER_PATH_APEX
	    !strcmp(dir, "apex") ||
#endif
	    !strcmp(dir, "user") ||
	    !strcmp(dir, "note") ||
	    !strcmp(dir, "cmov"))
	{
		char user_path[1024];
		/* copied from init_file_paths */
		path_parse(user_path, 1024, PRIVATE_USER_PATH);
		strcat(user_path, USER_PATH_VERSION);
		strnfmt(buf, 1024, "%s%s%s", user_path, PATH_SEP, new_path);
		string_free(*d);
		*d = string_make(buf);
	}
#ifdef PRIVATE_USER_PATH_DATA
	else if (!strcmp(dir, "data"))
	{
		module_reset_dir_aux(&ANGBAND_DIR_DATA, new_path);
	}
#endif
	else if (!strcmp(dir, "save"))
	{
		module_reset_dir_aux(&ANGBAND_DIR_SAVE, new_path);

		/* Tell the savefile code that we must not use setuid */
		savefile_setuid = FALSE;
	}
	else
#endif /* PRIVATE_USER_PATH */
	{
		/* Build the new path */
		strnfmt(buf, 1024, "%s%s%s%s%s", ANGBAND_DIR_MODULES, PATH_SEP, new_path, PATH_SEP, dir);

		string_free(*d);
		*d = string_make(buf);
	}
}
Exemple #25
0
/*
 * lexer___next
 *
 * Returns the next lexeme in the stream.
 * If 'erroneof' is set, reaching the end of a file (not the
 * end of the stream) should be considered an error condition --
 * this happens when we're in the middle of parsing a lexical
 * conditional or a macro definition; they must be wholly contained
 * within a single file.
 *
 * This is the internal version that handles both lexer_next
 * and lexer_peek processing.
 */
static lexeme_t *
lexer___next (lexer_ctx_t ctx, int erroneof, int peek, textpos_t *posp)
{
    lexeme_t *lex = 0;
    lextype_t lextype;
    strdesc_t *tok;
    unsigned int column;
    char *cp;

    if (ctx == 0) {
        return &errlex;
    }

    if (ctx->atend) {
        return &endlex;
    }

    while (ctx->chain != 0) {
        lexchain_t *chain = ctx->chain;
        lex = (peek ? lexseq_head(&chain->seq) : lexseq_remhead(&chain->seq));
        if (lex != 0) {
            break;
        }
        if (chain->strm != 0) {
            scantype_t type;
            unsigned int sflags;

            sflags = (erroneof ? SCAN_M_ERRONEOF : 0) |
                     (ctx->signok ? SCAN_M_SIGNOK : 0);

            type = scan_getnext(chain->strm, sflags, &tok,
                                &chain->curline, &column);
            if (!scan_ok(type)) {
                textpos_t pos = textpos_create(chain->filename_index,
                                               chain->curline, column);
                log_signal(ctx->logctx, pos, STC__INVTOKEN);
                lex = &errlex;
                string_free(ctx->strctx, tok);
                break;
            }
            if (!peek && posp != 0) {
                *posp = textpos_create(chain->filename_index, chain->curline, column);
            }
            if (type == SCANTYPE_END) {
                scan_close(chain->strm);
                chain->strm = 0;
                ctx->chain = chain->nextchain;
                lexchain_free(ctx, chain);
                if (ctx->chain == 0) {
                    lex = &endlex;
                    ctx->atend = 1;
                    string_free(ctx->strctx, tok);
                    break;
                }
                string_free(ctx->strctx, tok);
                continue;
            }
            switch (type) {
                case SCANTYPE_DECLITERAL:
                    lextype = LEXTYPE_NUMERIC;
                    ctx->signok = 0;
                    break;
                case SCANTYPE_QUOTEDSTRING:
                    lextype = LEXTYPE_STRING;
                    ctx->signok = 1;
                    break;
                case SCANTYPE_OPERATOR:
                    cp = strchr(operators, *tok->ptr);
                    lextype = opertypes[cp-operators];
                    ctx->signok = 1;
                    break;
                case SCANTYPE_PUNCTUATION:
                    cp = strchr(delimiters, *tok->ptr);
                    lextype = delimtypes[cp-delimiters];
                    ctx->signok = (strchr(")>]", *tok->ptr) == 0);
                    break;
                case SCANTYPE_IDENTIFIER:
                    lextype = LEXTYPE_NAME;
                    ctx->signok = 0;
                    break;
                default:
                    lextype = LEXTYPE_NONE;
                    break;
            }
            if (lextype == LEXTYPE_NONE) {
                lex = &errlex;
            } else {
                lex = lexeme_create(ctx->lexctx, lextype, tok);
                if (peek) {
                    lexseq_inshead(&chain->seq, lex);
                }
            }
            string_free(ctx->strctx, tok);
            break;
        } else {
            ctx->chain = chain->nextchain;
            lexchain_free(ctx, chain);
            if (ctx->chain == 0) {
                lex = &endlex;
                ctx->atend = 1;
                break;
            }
        }
    }
    return lex;

} /* lexer___next */
Exemple #26
0
void
file_dirscan( 
	char *dir,
	scanback func,
	void	*closure )
{

    struct FAB xfab;
    struct NAM xnam;
    struct XABDAT xab;
    char esa[256];
    char filename[256];
    string filename2[1];
    char dirname[256];
    register int status;
    PATHNAME f;

    memset( (char *)&f, '\0', sizeof( f ) );

    f.f_root.ptr = dir;
    f.f_root.len = strlen( dir );

	/* get the input file specification
	 */
    xnam = cc$rms_nam;
    xnam.nam$l_esa = esa;
    xnam.nam$b_ess = sizeof( esa ) - 1;
    xnam.nam$l_rsa = filename;
    xnam.nam$b_rss = min( sizeof( filename ) - 1, NAM$C_MAXRSS );

    xab = cc$rms_xabdat;                /* initialize extended attributes */
    xab.xab$b_cod = XAB$C_DAT;		/* ask for date */
    xab.xab$l_nxt = NULL;               /* terminate XAB chain      */

    xfab = cc$rms_fab;
    xfab.fab$l_dna = DEFAULT_FILE_SPECIFICATION;
    xfab.fab$b_dns = sizeof( DEFAULT_FILE_SPECIFICATION ) - 1;
    xfab.fab$l_fop = FAB$M_NAM;
    xfab.fab$l_fna = dir;			/* address of file name	    */
    xfab.fab$b_fns = strlen( dir );		/* length of file name	    */
    xfab.fab$l_nam = &xnam;			/* address of NAB block	    */
    xfab.fab$l_xab = (char *)&xab;       /* address of XAB block     */


    status = sys$parse( &xfab );

    if( DEBUG_BINDSCAN )
	printf( "scan directory %s\n", dir );

    if ( !( status & 1 ) )
	return;



    /* Add bogus directory for [000000] */

    if( !strcmp( dir, "[000000]" ) )
    {
	(*func)( closure, "[000000]", 1 /* time valid */, 1 /* old but true */ );
    }

    /* Add bogus directory for [] */

    if( !strcmp( dir, "[]" ) )
    {
	(*func)( closure, "[]", 1 /* time valid */, 1 /* old but true */ );
	(*func)( closure, "[-]", 1 /* time valid */, 1 /* old but true */ );
    }

    string_new( filename2 );
    while ( (status = sys$search( &xfab )) & 1 )
    {
	char *s;
	time_t time;

	/* "I think that might work" - eml */

	sys$open( &xfab );
	sys$close( &xfab );

	file_cvttime( (unsigned int *)&xab.xab$q_rdt, &time );

	filename[xnam.nam$b_rsl] = '\0';

	/* What we do with the name depends on the suffix: */
	/* .dir is a directory */
	/* .xxx is a file with a suffix */
	/* . is no suffix at all */

	if( xnam.nam$b_type == 4 && !strncmp( xnam.nam$l_type, ".DIR", 4 ) )
	{
	    /* directory */
	    sprintf( dirname, "[.%.*s]", xnam.nam$b_name, xnam.nam$l_name );
	    f.f_dir.ptr = dirname;
	    f.f_dir.len = strlen( dirname );
	    f.f_base.ptr = 0;
	    f.f_base.len = 0;
	    f.f_suffix.ptr = 0;
	    f.f_suffix.len = 0;
	}
	else
	{
	    /* normal file with a suffix */
	    f.f_dir.ptr = 0;
	    f.f_dir.len = 0;
	    f.f_base.ptr = xnam.nam$l_name;
	    f.f_base.len = xnam.nam$b_name;
	    f.f_suffix.ptr = xnam.nam$l_type;
	    f.f_suffix.len = xnam.nam$b_type;
	}

        string_truncate( filename2, 0 );
	path_build( &f, filename2, 0 );

	/*
	if( DEBUG_SEARCH )
	    printf("root '%s' base %.*s suf %.*s = %s\n",
		    dir,
		    xnam.nam$b_name, xnam.nam$l_name, 
		    xnam.nam$b_type, xnam.nam$l_type,
		    filename2);
	*/

	(*func)( closure, filename2->value, 1 /* time valid */, time );
    }
    string_free( filename2 );
}    
Exemple #27
0
/*
 * declare_macro
 *
 * Common logic for parsing macro declarations.
 *
 * MACRO macro-name { (param,...) } { [param,...] } = {stuff} % {,...}
 * KEYWORDMACRO macro-name { (param{=defval},...) } = {stuff} % {,...}
 */
int
declare_macro (expr_ctx_t ctx, scopectx_t scope, lextype_t curlt)
{
    parse_ctx_t pctx = expr_parse_ctx(ctx);
    int skip_to_end = 0;
    lexeme_t *lex;
    lextype_t lt;
    strdesc_t *ltext;
    name_t *np;
    int is_kwdmacro = (curlt == LEXTYPE_DCL_KEYWORDMACRO);
    struct macrodecl_s *macro;
    textpos_t pos;
    namedef_t ndef;

    memset(&ndef, 0, sizeof(ndef));
    ndef.lt = LEXTYPE_NAME_MACRO;
    ndef.flags = NAME_M_DECLARED;
    while (1) {
        if (!parse_decl_name(pctx, &ltext, &pos)) {
            expr_signal(ctx, STC__NAMEEXP);
            skip_to_end = 1;
        }
        lt = parser_next(pctx, QL_NAME, 0);
        if (lt != LEXTYPE_DELIM_LPAR &&
            lt != LEXTYPE_OP_ASSIGN &&
            lt != LEXTYPE_DELIM_LBRACK) {
            expr_signal(ctx, STC__SYNTAXERR);
            skip_to_end = 1;
        }
        ndef.name = ltext->ptr;
        ndef.namelen = ltext->len;
        np = name_declare(scope, &ndef, pos, 0, 0, &macro);
        macro->type = (is_kwdmacro ? MACRO_KWD : MACRO_UNK);
        // Parse the regular parameters
        if (lt == LEXTYPE_DELIM_LPAR) {
            if (macro_paramlist(ctx, scope, is_kwdmacro, 1,
                                closers, 1, &macro->ptable,
                                &macro->plist) < 0) {
                skip_to_end = 1;
            }
            if (namereflist_length(&macro->plist) == 0) {
                expr_signal(ctx, STC__NOMACPRMS);
                skip_to_end = 1;
            }
            lt = parser_next(pctx, QL_NAME, 0);
            if (!is_kwdmacro) {
                macro->type = MACRO_SIMPLE;
            }
        }
        // Parse the iterative parameters (or the empty bracket pair
        // for conditional macros)
        if (lt == LEXTYPE_DELIM_LBRACK) {
            if (is_kwdmacro) {
                expr_signal(ctx, STC__ITERKWMAC);
                skip_to_end = 1;
            }
            if (macro_paramlist(ctx, scope, 0, 1, &closers[1], 1,
                                &macro->ptable, &macro->ilist) < 0) {
                skip_to_end = 1;
            }
            lt = parser_next(pctx, QL_NAME, 0);
            macro->type = (namereflist_length(&macro->ilist) == 0 ?
                           MACRO_COND : MACRO_ITER);
        }

        if (lt == LEXTYPE_OP_ASSIGN) {

            // If the type is still unknown, there were no parameter
            // lists, so we know this is a simple, non-parameterized
            // macro
            if (macro->type == MACRO_UNK) {
                macro->type = MACRO_SIMPLE;
            }

            // Parse the macro body.  It must be wholly contained within
            // the currently open file, so we set ERRONEOF to tell the
            // parser that.
            parser_incr_erroneof(pctx);
            parser_scope_begin(pctx);
            for (lt = parser_next(pctx, QL_MACRO, &lex);
                 lt != LEXTYPE_LXF_DELIM_PERCENT;
                 lt = parser_next(pctx, QL_MACRO, &lex)) {
                if (lt == LEXTYPE_END || lt == LEXTYPE_NONE) {
                    expr_signal(ctx, STC__SYNTAXERR);
                    skip_to_end = 1;
                    break;
                }
                lexseq_instail(&macro->body, lex);
            }
            parser_scope_end(pctx);
            parser_decr_erroneof(pctx);
        }

        if (skip_to_end) {
            name_free(np);
            string_free(expr_strctx(ctx), ltext);
            break;
        }
        if (macro->ptable != 0) {
            scope_setparent(macro->ptable, 0);
        }
        string_free(expr_strctx(ctx), ltext);

        if (parser_expect(pctx, QL_NAME, LEXTYPE_DELIM_SEMI, 0, 1)) {
            break;
        }
        if (!parser_expect(pctx, QL_NAME, LEXTYPE_DELIM_COMMA, 0, 1)) {
            expr_signal(ctx, STC__DELIMEXP, ",");
            parser_skip_to_delim(pctx, LEXTYPE_DELIM_SEMI);
            break;
        }

    } /* while 1 */

    return 1;

} /* define_macro */
Exemple #28
0
error_t
strexp_eval( struct program *program, struct strexp *strexp,
	     struct string **string )
{
  error_t error; struct string *string1, *string2; float value1, value2;
  size_t start, end, length;

  int integer; char character, buffer[256];

  error = string_new( string ); if( error != BASIC_ERROR_NONE ) return error;

  switch( strexp->type ) {

  case STREXP_STRING_ID:
    error = string_copy( (*string), strexp->types.string );
    if( error != BASIC_ERROR_NONE ) { string_destroy( string ); return error; }
    break;

  case STREXP_VARIABLE_ID:
    error = program_lookup_string( program, strexp->types.name, *string );
    if( error || program->error ) { string_destroy( string ); return error; }
    break;

  case STREXP_NUMEXP_ID:
    error = numexp_eval( program, strexp->types.numexp.exp, &value1 );
    if( error || program->error ) { string_destroy( string ); return error; }

    switch( strexp->types.numexp.type ) {
    case CHRS:			/* CHR$ */
      integer = value1;
      if( integer < 0 || integer >= 256 ) {
	program->error = BASIC_PROGRAM_ERROR_B;
	string_destroy( string );
	return BASIC_ERROR_NONE;
      }
      
      character = integer;
      error = string_create( (*string), &character, 1 );
      if( error ) { string_destroy( string ); return error; }
      break;

    case STRS:			/* STR$ */
      snprintf( buffer, 256, "%f", value1 );
      error = string_create( (*string), buffer, strlen( buffer ) );
      if( error ) { string_destroy( string ); return error; }
      break;

    default:
      fprintf( stderr, "Unknown numexp strexp type %d evaluated\n",
	       strexp->types.numexp.type );
      return BASIC_ERROR_UNKNOWN;
    }
    break;

  case STREXP_STREXP_ID:
    error = strexp_eval( program, strexp->types.strexp.exp, &string1 );
    if( error || program->error ) { string_destroy( string ); return error; }

    switch( strexp->types.strexp.type ) {
    case VALS:
      error = vals_eval( program, string1, string );
      if( error || program->error ) return error;
      break;

    default:
      fprintf( stderr, "Unknown strexp strexp type %d evaluated\n",
	       strexp->types.strexp.type );
      string_destroy( string ); string_free( string1 );
      return BASIC_ERROR_UNKNOWN;
    }
    break;

  case STREXP_TWOSTREXP_ID:
    error = strexp_eval( program, strexp->types.twostrexp.exp1, &string1 );
    if( error || program->error ) { string_destroy( string ); return error; }

    error = strexp_eval( program, strexp->types.twostrexp.exp2, &string2 );
    if( error || program->error ) {
      string_destroy( string ); string_free( string1 );
      return error;
    }

    switch( strexp->types.twostrexp.type ) {
    case '+':
      error = string_concat( (*string), string1, string2 );
      if( error != BASIC_ERROR_NONE ) {
	string_destroy( string );
	string_free( string1 ); string_free( string2 );
	return error;
      }
      break;

    default:
      fprintf( stderr, "Unknown two arg strexp type %d evaluated\n",
	       strexp->types.twostrexp.type );
      string_destroy( string ); string_free( string1 ); string_free( string2 );
      return BASIC_ERROR_UNKNOWN;
    }
    string_free( string1 ); string_free( string2 );
    break;

  case STREXP_AND_ID:
    error = numexp_eval( program, strexp->types.and.exp2, &value1 );
    if( error || program->error ) { string_destroy( string ); return error; }
    
    error = strexp_eval( program, strexp->types.and.exp1, &string1 );
    if( error || program->error ) { string_destroy( string ); return error; }

    if( value1 ) {
      error = string_copy( *string, string1 );
      if( error ) {
	string_destroy( string ); string_free( string1 );
	return error;
      }
    }
    
    string_free( string1 );
    break;

  case STREXP_SLICER_ID:
    error = strexp_eval( program, strexp->types.slicer.exp, &string1 );
    if( error || program->error ) { string_destroy( string ); return error; }

    if( strexp->types.slicer.slicer->start ) {
      error = numexp_eval( program, strexp->types.slicer.slicer->start,
			   &value1 );
      if( error || program->error ) {
	string_destroy( string ); string_free( string1 );
	return error;
      }
      start = value1;
    } else {
      start = 1;
    }

    if( strexp->types.slicer.slicer->end ) {
      error = numexp_eval( program, strexp->types.slicer.slicer->end,
			   &value2 );
      if( error || program->error ) {
	string_destroy( string ); string_free( string1 );
	return error;
      }
      end = value2;
    } else {
      end = string1->length;
    }

    if( start < 1 || end > string1->length ) {
      string_destroy( string ); string_free( string1 );
      program->error = BASIC_PROGRAM_ERROR_3;
      return BASIC_ERROR_NONE;
    }

    length = end >= start ? end - start + 1 : 0;
    error = string_create( (*string), &((string1->buffer)[start-1]), length );
    if( error ) {
      string_destroy( string ); string_free( string1 );
      return error;
    }

    string_free( string1 );
    return BASIC_ERROR_NONE;

  default:
    fprintf( stderr, "Unknown strexp type %d evaluated\n", strexp->type );
    string_destroy( string );
    return BASIC_ERROR_UNKNOWN;

  }

  return BASIC_ERROR_NONE;
}
Exemple #29
0
static int tunet_logon_recv_remaining_data()
{
	BYTE tmpbuf[1024 * 8];
	CHAR tmp[1024];

	CHAR sztmp[255];

	BYTE *p;
	INT len;
	BYTE key77[8];
	
	STRING *str = NULL;
	char des3data[12];
	des3_context ctx3;
	TIME tm;


	UINT32 datalen, port;
	UINT32 uint_money;
	BYTE btag;


//	BOOL sr, sw, se;
	
	if(!main_socket) return OK;
//	printf("tunet_logon_recv_remaining_data() called.\n");
//	os_socket_tcp_status(main_socket, &sr, &sw, &se);


	if(tunet_state != TUNET_STATE_RECV_REMAINING_DATA && tunet_state != TUNET_STATE_KEEPALIVE)
		return OK;

/*

	if(se)
	{
		logs_append(g_logs, "TUNET_NETWORK_ERROR", "RECV_REMAINING_DATA", NULL, 0);
		return ERR;
	}

	if(!sr) return OK;
*/


	len = os_socket_tcp_recv(main_socket, tmpbuf, sizeof(tmpbuf));
	if(len == -1)
	{
		logs_append(g_logs, "TUNET_NETWORK_ERROR", "RECV_REMAINING_DATA", NULL, 0);
		return ERR;
	}


	if(len > 0)
	{
		main_socket_buffer = buffer_append(main_socket_buffer, tmpbuf, len);
		logs_append(g_logs, "TUNET_LOGON_RECV", "REMAINING", tmpbuf, len);

		buf2output(tmpbuf, len, tmp, 16);
		//dprintf("data received(recv remaining):\n%s\n", tmp);

		

		p = main_socket_buffer->data;
		while(buffer_fetch_BYTE(main_socket_buffer, &p, &btag))
		{
			switch(btag)
			{
				case 0x01:
					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen))
						return OK;

					datalen = htonl(datalen);

					memset(keepalive_server, 0, sizeof(keepalive_server));
					if(!buffer_fetch_bytes(main_socket_buffer, &p, (BYTE *)keepalive_server, datalen))
						return OK;

					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &port))
						return OK;

					port = htonl(port);
					keepalive_server_port = (short)port;

					snprintf(sztmp, sizeof(sztmp), "%s:%d", keepalive_server, keepalive_server_port);
					//dprintf("保持活动服务器:%s\n", sztmp);



					//we got the KEEPALIVE server, try to keep alive
					os_tick_clear(keepalive_timeout);
					tunet_state = TUNET_STATE_KEEPALIVE;

					logs_append(g_logs, "TUNET_LOGON_KEEPALIVE_SERVER", sztmp, NULL, 0);

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					break;
				case 0x02:
					//出错消息
					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen))
						return OK;
					datalen = htonl(datalen);

					//dprintf("出错消息长 %d\n", datalen);

					if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, datalen))
						return OK;

					//dprintf("%s\n", str->str);


					tunet_state = TUNET_STATE_ERROR;

					logs_append(g_logs, "TUNET_LOGON_ERROR", str->str, NULL, 0);

					str = string_free(str);

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					

					break;
				case 0x05:
					if(buffer_fetch_BYTE(main_socket_buffer, &p, &btag))
					{
						if(btag != 0)
						{
							//dprintf("与消息中介服务器通信结束。\n");
							main_socket = os_socket_tcp_close(main_socket);

							logs_append(g_logs, "TUNET_LOGON_FINISH_MSGSERVER", NULL, NULL, 0);

							main_socket_buffer = buffer_rollto(main_socket_buffer, p);
							p = main_socket_buffer->data;
							
							break;
						}
					}

					BUF_ROLL(p, -1);  //restore the point for further use


					//出错消息
					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen))
						return OK;
					datalen = htonl(datalen);

					//dprintf("出错消息长 %d\n", datalen);

					if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, datalen))
						return OK;

					//dprintf("%s\n", str->str);
					
					tunet_state = TUNET_STATE_ERROR;

					logs_append(g_logs, "TUNET_LOGON_ERROR", str->str, NULL, 0);

					str = string_free(str);

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					
					break;
					
				case 0x04:
				case 0x08:
					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen))
						return OK;

					datalen = htonl(datalen);

					memset(msg_server, 0, sizeof(msg_server));
					if(!buffer_fetch_bytes(main_socket_buffer, &p, (BYTE *)msg_server, datalen))
						return OK;

					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &port))
						return OK;

					port = htonl(port);

					msg_server_port = (short)port;

					if(!buffer_fetch_bytes(main_socket_buffer, &p, key77, 8))
						return OK;

					//登陆消息
					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen))
						return OK;
					datalen = htonl(datalen);

					//dprintf("登陆消息长 %d\n", datalen);

					if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, datalen))
						return OK;
					//dprintf("%s\n", str->str);

					logs_append(g_logs, "TUNET_LOGON_MSG", str->str, NULL, 0);

					str = string_free(str);


					//make a new key for keep-alive
					//dprintf("key77 == %s\n", buf2hex(key77, 8, tmp));
					memset(des3data, 0, sizeof(des3data));
					des3_set_3keys( &ctx3, userconfig.md5Password,
										   userconfig.md5Password + 8,
										   userconfig.md5Password );

					des3_encrypt( &ctx3, (uint8 *)key77, (uint8 *)des3data);

					memcpy(keepalive_key, des3data, 8);


					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					//--------------------------------
					snprintf(sztmp, sizeof(sztmp), "%s:%d", msg_server, msg_server_port);

					//dprintf("准备连接到消息中介服务器 %s 获得活动服务器地址....\n", sztmp);

					logs_append(g_logs, "TUNET_LOGON_MSGSERVER", sztmp, NULL, 0);

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					//switch to another server to get alive-server ip
					strcpy(keepalive_server, "");
					main_socket = os_socket_tcp_close(main_socket);
					main_socket = os_socket_tcp_connect(msg_server, msg_server_port, FALSE);

					break;
				case 0x1b:
					if(!buffer_fetch_DWORD(main_socket_buffer, &p, &uint_money))
						return OK;

					uint_money = htonl(uint_money);
					snprintf(sztmp, sizeof(sztmp), "%0.2f", tunet_imoney_to_fmoney(uint_money));
					//dprintf("您在登陆前的余额是:%s\n", sztmp);

					logs_append(g_logs, "TUNET_LOGON_MONEY", sztmp, NULL, 0);

					if(buffer_has_data(main_socket_buffer, p, 16))
					{
						snprintf(sztmp, sizeof(sztmp), "%d.%d.%d.%d/%d.%d.%d.%d", p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]);
						logs_append(g_logs, "TUNET_LOGON_IPs", sztmp, NULL, 0);
						//dprintf("登陆IP状况: %s\n", sztmp);
						BUF_ROLL(p, 8);

						
						tm = os_time_convert(htonl(BUFDWORD(p)));
						snprintf(sztmp, sizeof(sztmp), "%d-%d-%d %d:%d:%d", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second );
						logs_append(g_logs, "TUNET_LOGON_SERVERTIME", sztmp, NULL, 0);
						//dprintf("当前服务器时间: %s\n", sztmp);
						BUF_ROLL(p, 4);

						tm = os_time_convert(htonl(BUFDWORD(p)));
						snprintf(sztmp, sizeof(sztmp), "%d-%d-%d %d:%d:%d", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second );
						logs_append(g_logs, "TUNET_LOGON_LASTTIME", sztmp, NULL, 0);
						//dprintf("上次登陆时间: %s\n", sztmp);
						BUF_ROLL(p, 4);
					}
					else
					{
						return OK;
					}

					main_socket_buffer = buffer_rollto(main_socket_buffer, p);
					p = main_socket_buffer->data;

					break;
			}
		}

	}

	return OK;

}
Exemple #30
0
STRING *ssh_encrypt_rsa1(SSH_SESSION *session, STRING *data, PUBLIC_KEY *key) {
  STRING *str = NULL;
  size_t len = string_len(data);
  size_t size = 0;
#ifdef HAVE_LIBGCRYPT
  const char *tmp = NULL;
  gcry_sexp_t ret_sexp;
  gcry_sexp_t data_sexp;

  if (gcry_sexp_build(&data_sexp, NULL, "(data(flags pkcs1)(value %b))",
      len, data->string)) {
    ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
    return NULL;
  }
  if (gcry_pk_encrypt(&ret_sexp, data_sexp, key->rsa_pub)) {
    gcry_sexp_release(data_sexp);
    ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
    return NULL;
  }

  gcry_sexp_release(data_sexp);

  data_sexp = gcry_sexp_find_token(ret_sexp, "a", 0);
  if (data_sexp == NULL) {
    ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
    gcry_sexp_release(ret_sexp);
    return NULL;
  }
  tmp = gcry_sexp_nth_data(data_sexp, 1, &size);
  if (*tmp == 0) {
    size--;
    tmp++;
  }

  str = string_new(size);
  if (str == NULL) {
    ssh_set_error(session, SSH_FATAL, "Not enough space");
    gcry_sexp_release(data_sexp);
    gcry_sexp_release(ret_sexp);
    return NULL;
  }
  string_fill(str, tmp, size);

  gcry_sexp_release(data_sexp);
  gcry_sexp_release(ret_sexp);
#elif defined HAVE_LIBCRYPTO
  size = RSA_size(key->rsa_pub);

  str = string_new(size);
  if (str == NULL) {
    ssh_set_error(session, SSH_FATAL, "Not enough space");
    return NULL;
  }

  if (RSA_public_encrypt(len, data->string, str->string, key->rsa_pub,
      RSA_PKCS1_PADDING) < 0) {
    string_free(str);
    return NULL;
  }
#endif

  return str;
}