code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef CHANNELS_H_ #define CHANNELS_H_ #include "libssh/priv.h" struct ssh_channel_struct { struct ssh_channel_struct *prev; struct ssh_channel_struct *next; ssh_session session; /* SSH_SESSION pointer */ uint32_t local_channel; uint32_t local_window; int local_eof; uint32_t local_maxpacket; uint32_t remote_channel; uint32_t remote_window; int remote_eof; /* end of file received */ uint32_t remote_maxpacket; int open; /* shows if the channel is still opened */ int delayed_close; ssh_buffer stdout_buffer; ssh_buffer stderr_buffer; void *userarg; int version; int blocking; int exit_status; }; void channel_handle(ssh_session session, int type); ssh_channel channel_new(ssh_session session); int channel_default_bufferize(ssh_channel channel, void *data, int len, int is_stderr); uint32_t ssh_channel_new_id(ssh_session session); ssh_channel ssh_channel_from_local(ssh_session session, uint32_t id); int channel_write_common(ssh_channel channel, const void *data, uint32_t len, int is_stderr); #endif /* CHANNELS_H_ */
zzlydm-fbbs
include/libssh/channels.h
C
gpl3
1,985
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef POLL_H_ #define POLL_H_ #include "config.h" #ifdef HAVE_POLL #include <poll.h> typedef struct pollfd ssh_pollfd_t; #else /* HAVE_POLL */ /* poll emulation support */ typedef struct ssh_pollfd_struct { socket_t fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */ } ssh_pollfd_t; /* poll.c */ #ifndef POLLIN #define POLLIN 0x001 /* There is data to read. */ #endif #ifndef POLLPRI #define POLLPRI 0x002 /* There is urgent data to read. */ #endif #ifndef POLLOUT #define POLLOUT 0x004 /* Writing now will not block. */ #endif #ifndef POLLERR #define POLLERR 0x008 /* Error condition. */ #endif #ifndef POLLHUP #define POLLHUP 0x010 /* Hung up. */ #endif #ifndef POLLNVAL #define POLLNVAL 0x020 /* Invalid polling request. */ #endif #ifndef POLLRDNORM #define POLLRDNORM 0x040 /* mapped to read fds_set */ #endif #ifndef POLLRDBAND #define POLLRDBAND 0x080 /* mapped to exception fds_set */ #endif #ifndef POLLWRNORM #define POLLWRNORM 0x100 /* mapped to write fds_set */ #endif #ifndef POLLWRBAND #define POLLWRBAND 0x200 /* mapped to write fds_set */ #endif typedef unsigned long int nfds_t; #endif /* HAVE_POLL */ void ssh_poll_init(void); int ssh_poll(ssh_pollfd_t *fds, nfds_t nfds, int timeout); typedef struct ssh_poll_ctx_struct *ssh_poll_ctx; typedef struct ssh_poll_handle_struct *ssh_poll_handle; /** * @brief SSH poll callback. * * @param p Poll object this callback belongs to. * @param fd The raw socket. * @param revents The current poll events on the socket. * @param userdata Userdata to be passed to the callback function. * * @return 0 on success, < 0 if you removed the poll object from * it's poll context. */ typedef int (*ssh_poll_callback)(ssh_poll_handle p, int fd, int revents, void *userdata); ssh_poll_handle ssh_poll_new(socket_t fd, short events, ssh_poll_callback cb, void *userdata); void ssh_poll_free(ssh_poll_handle p); ssh_poll_ctx ssh_poll_get_ctx(ssh_poll_handle p); short ssh_poll_get_events(ssh_poll_handle p); void ssh_poll_set_events(ssh_poll_handle p, short events); void ssh_poll_add_events(ssh_poll_handle p, short events); void ssh_poll_remove_events(ssh_poll_handle p, short events); socket_t ssh_poll_get_fd(ssh_poll_handle p); void ssh_poll_set_callback(ssh_poll_handle p, ssh_poll_callback cb, void *userdata); ssh_poll_ctx ssh_poll_ctx_new(size_t chunk_size); void ssh_poll_ctx_free(ssh_poll_ctx ctx); int ssh_poll_ctx_add(ssh_poll_ctx ctx, ssh_poll_handle p); void ssh_poll_ctx_remove(ssh_poll_ctx ctx, ssh_poll_handle p); int ssh_poll_ctx_dopoll(ssh_poll_ctx ctx, int timeout); #endif /* POLL_H_ */
zzlydm-fbbs
include/libssh/poll.h
C
gpl3
3,622
/* Public include file for server support */ /* * This file is part of the SSH Library * * Copyright (c) 2003-2008 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ /** * @defgroup ssh_server SSH Server * @addtogroup ssh_server * @{ */ #ifndef SERVER_H #define SERVER_H #include "libssh/libssh.h" #define SERVERBANNER CLIENTBANNER #ifdef __cplusplus extern "C" { #endif enum ssh_bind_options_e { SSH_BIND_OPTIONS_BINDADDR, SSH_BIND_OPTIONS_BINDPORT, SSH_BIND_OPTIONS_BINDPORT_STR, SSH_BIND_OPTIONS_HOSTKEY, SSH_BIND_OPTIONS_DSAKEY, SSH_BIND_OPTIONS_RSAKEY, SSH_BIND_OPTIONS_BANNER, SSH_BIND_OPTIONS_LOG_VERBOSITY, SSH_BIND_OPTIONS_LOG_VERBOSITY_STR }; //typedef struct ssh_bind_struct SSH_BIND; typedef struct ssh_bind_struct* ssh_bind; /** * @brief Creates a new SSH server bind. * * @return A newly allocated ssh_bind session pointer. */ LIBSSH_API ssh_bind ssh_bind_new(void); /** * @brief Set the opitons for the current SSH server bind. * * @param sshbind The ssh server bind to use. * * @param type The option type to set. * * @param value The option value to set. * * @return 0 on success, < 0 on error. */ LIBSSH_API int ssh_bind_options_set(ssh_bind sshbind, enum ssh_bind_options_e type, const void *value); /** * @brief Start listening to the socket. * * @param ssh_bind_o The ssh server bind to use. * * @return 0 on success, < 0 on error. */ LIBSSH_API int ssh_bind_listen(ssh_bind ssh_bind_o); /** * @brief Set the session to blocking/nonblocking mode. * * @param ssh_bind_o The ssh server bind to use. * * @param blocking Zero for nonblocking mode. */ LIBSSH_API void ssh_bind_set_blocking(ssh_bind ssh_bind_o, int blocking); /** * @brief Recover the file descriptor from the session. * * @param ssh_bind_o The ssh server bind to get the fd from. * * @return The file descriptor. */ LIBSSH_API socket_t ssh_bind_get_fd(ssh_bind ssh_bind_o); /** * @brief Set the file descriptor for a session. * * @param ssh_bind_o The ssh server bind to set the fd. * * @param fd The file descriptssh_bind B */ LIBSSH_API void ssh_bind_set_fd(ssh_bind ssh_bind_o, socket_t fd); /** * @brief Allow the file descriptor to accept new sessions. * * @param ssh_bind_o The ssh server bind to use. */ LIBSSH_API void ssh_bind_fd_toaccept(ssh_bind ssh_bind_o); /** * @brief Accept an incoming ssh connection and initialize the session. * * @param ssh_bind_o The ssh server bind to accept a connection. * @param session A preallocated ssh session * @see ssh_new * @return A newly allocated ssh session, NULL on error. */ LIBSSH_API int ssh_bind_accept(ssh_bind ssh_bind_o, ssh_session session); /** * @brief Free a ssh servers bind. * * @param ssh_bind_o The ssh server bind to free. */ LIBSSH_API void ssh_bind_free(ssh_bind ssh_bind_o); /** * @brief Exchange the banner and cryptographic keys. * * @param session The ssh session to accept a connection. * * @return 0 on success, < 0 on error. */ LIBSSH_API int ssh_accept(ssh_session session); LIBSSH_API int channel_write_stderr(ssh_channel channel, const void *data, uint32_t len); /* messages.c */ LIBSSH_API int ssh_message_reply_default(ssh_message msg); LIBSSH_API char *ssh_message_auth_user(ssh_message msg); LIBSSH_API char *ssh_message_auth_password(ssh_message msg); LIBSSH_API ssh_public_key ssh_message_auth_publickey(ssh_message msg); LIBSSH_API int ssh_message_auth_reply_success(ssh_message msg,int partial); LIBSSH_API int ssh_message_auth_reply_pk_ok(ssh_message msg, ssh_string algo, ssh_string pubkey); LIBSSH_API int ssh_message_auth_set_methods(ssh_message msg, int methods); LIBSSH_API int ssh_message_service_reply_success(ssh_message msg); LIBSSH_API char *ssh_message_service_service(ssh_message msg); LIBSSH_API void ssh_set_message_callback(ssh_session session, int(*ssh_message_callback)(ssh_session session, ssh_message msg)); LIBSSH_API char *ssh_message_channel_request_open_originator(ssh_message msg); LIBSSH_API int ssh_message_channel_request_open_originator_port(ssh_message msg); LIBSSH_API char *ssh_message_channel_request_open_destination(ssh_message msg); LIBSSH_API int ssh_message_channel_request_open_destination_port(ssh_message msg); LIBSSH_API ssh_channel ssh_message_channel_request_channel(ssh_message msg); LIBSSH_API char *ssh_message_channel_request_pty_term(ssh_message msg); LIBSSH_API int ssh_message_channel_request_pty_width(ssh_message msg); LIBSSH_API int ssh_message_channel_request_pty_height(ssh_message msg); LIBSSH_API int ssh_message_channel_request_pty_pxwidth(ssh_message msg); LIBSSH_API int ssh_message_channel_request_pty_pxheight(ssh_message msg); LIBSSH_API char *ssh_message_channel_request_env_name(ssh_message msg); LIBSSH_API char *ssh_message_channel_request_env_value(ssh_message msg); LIBSSH_API char *ssh_message_channel_request_command(ssh_message msg); LIBSSH_API char *ssh_message_channel_request_subsystem(ssh_message msg); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* SERVER_H */ /** * @} */ /* vim: set ts=2 sw=2 et cindent: */
zzlydm-fbbs
include/libssh/server.h
C
gpl3
5,923
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef BUFFER_H_ #define BUFFER_H_ /* Describes a buffer state */ struct ssh_buffer_struct { char *data; uint32_t used; uint32_t allocated; uint32_t pos; }; int buffer_add_ssh_string(ssh_buffer buffer, ssh_string string); int buffer_add_u8(ssh_buffer buffer, uint8_t data); int buffer_add_u16(ssh_buffer buffer, uint16_t data); int buffer_add_u32(ssh_buffer buffer, uint32_t data); int buffer_add_u64(ssh_buffer buffer, uint64_t data); int buffer_add_data(ssh_buffer buffer, const void *data, uint32_t len); int buffer_prepend_data(ssh_buffer buffer, const void *data, uint32_t len); int buffer_add_buffer(ssh_buffer buffer, ssh_buffer source); int buffer_reinit(ssh_buffer buffer); /* buffer_get_rest returns a pointer to the current position into the buffer */ void *buffer_get_rest(ssh_buffer buffer); /* buffer_get_rest_len returns the number of bytes which can be read */ uint32_t buffer_get_rest_len(ssh_buffer buffer); /* buffer_read_*() returns the number of bytes read, except for ssh strings */ int buffer_get_u8(ssh_buffer buffer, uint8_t *data); int buffer_get_u32(ssh_buffer buffer, uint32_t *data); int buffer_get_u64(ssh_buffer buffer, uint64_t *data); uint32_t buffer_get_data(ssh_buffer buffer, void *data, uint32_t requestedlen); /* buffer_get_ssh_string() is an exception. if the String read is too large or invalid, it will answer NULL. */ ssh_string buffer_get_ssh_string(ssh_buffer buffer); /* gets a string out of a SSH-1 mpint */ ssh_string buffer_get_mpint(ssh_buffer buffer); /* buffer_pass_bytes acts as if len bytes have been read (used for padding) */ uint32_t buffer_pass_bytes_end(ssh_buffer buffer, uint32_t len); uint32_t buffer_pass_bytes(ssh_buffer buffer, uint32_t len); #endif /* BUFFER_H_ */
zzlydm-fbbs
include/libssh/buffer.h
C
gpl3
2,622
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef MESSAGES_H_ #define MESSAGES_H_ #include "config.h" struct ssh_auth_request { char *username; int method; char *password; struct ssh_public_key_struct *public_key; char signature_state; }; struct ssh_channel_request_open { int type; uint32_t sender; uint32_t window; uint32_t packet_size; char *originator; uint16_t originator_port; char *destination; uint16_t destination_port; }; struct ssh_service_request { char *service; }; struct ssh_channel_request { int type; ssh_channel channel; uint8_t want_reply; /* pty-req type specifics */ char *TERM; uint32_t width; uint32_t height; uint32_t pxwidth; uint32_t pxheight; ssh_string modes; /* env type request */ char *var_name; char *var_value; /* exec type request */ char *command; /* subsystem */ char *subsystem; }; struct ssh_message_struct { ssh_session session; int type; struct ssh_auth_request auth_request; struct ssh_channel_request_open channel_request_open; struct ssh_channel_request channel_request; struct ssh_service_request service_request; }; void message_handle(ssh_session session, uint32_t type); int ssh_execute_message_callbacks(ssh_session session); #endif /* MESSAGES_H_ */
zzlydm-fbbs
include/libssh/messages.h
C
gpl3
2,184
#ifndef __AGENT_H #define __AGENT_H #include "libssh/libssh.h" /* Messages for the authentication agent connection. */ #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2 #define SSH_AGENTC_RSA_CHALLENGE 3 #define SSH_AGENT_RSA_RESPONSE 4 #define SSH_AGENT_FAILURE 5 #define SSH_AGENT_SUCCESS 6 #define SSH_AGENTC_ADD_RSA_IDENTITY 7 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8 #define SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES 9 /* private OpenSSH extensions for SSH2 */ #define SSH2_AGENTC_REQUEST_IDENTITIES 11 #define SSH2_AGENT_IDENTITIES_ANSWER 12 #define SSH2_AGENTC_SIGN_REQUEST 13 #define SSH2_AGENT_SIGN_RESPONSE 14 #define SSH2_AGENTC_ADD_IDENTITY 17 #define SSH2_AGENTC_REMOVE_IDENTITY 18 #define SSH2_AGENTC_REMOVE_ALL_IDENTITIES 19 /* smartcard */ #define SSH_AGENTC_ADD_SMARTCARD_KEY 20 #define SSH_AGENTC_REMOVE_SMARTCARD_KEY 21 /* lock/unlock the agent */ #define SSH_AGENTC_LOCK 22 #define SSH_AGENTC_UNLOCK 23 /* add key with constraints */ #define SSH_AGENTC_ADD_RSA_ID_CONSTRAINED 24 #define SSH2_AGENTC_ADD_ID_CONSTRAINED 25 #define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26 #define SSH_AGENT_CONSTRAIN_LIFETIME 1 #define SSH_AGENT_CONSTRAIN_CONFIRM 2 /* extended failure messages */ #define SSH2_AGENT_FAILURE 30 /* additional error code for ssh.com's ssh-agent2 */ #define SSH_COM_AGENT2_FAILURE 102 #define SSH_AGENT_OLD_SIGNATURE 0x01 struct ssh_agent_struct { struct socket *sock; ssh_buffer ident; unsigned int count; }; #ifndef _WIN32 /* agent.c */ /** * @brief Create a new ssh agent structure. * * @return An allocated ssh agent structure or NULL on error. */ struct ssh_agent_struct *agent_new(struct ssh_session_struct *session); void agent_close(struct ssh_agent_struct *agent); /** * @brief Free an allocated ssh agent structure. * * @param agent The ssh agent structure to free. */ void agent_free(struct ssh_agent_struct *agent); /** * @brief Check if the ssh agent is running. * * @param session The ssh session to check for the agent. * * @return 1 if it is running, 0 if not. */ int agent_is_running(struct ssh_session_struct *session); int agent_get_ident_count(struct ssh_session_struct *session); struct ssh_public_key_struct *agent_get_next_ident(struct ssh_session_struct *session, char **comment); struct ssh_public_key_struct *agent_get_first_ident(struct ssh_session_struct *session, char **comment); ssh_string agent_sign_data(struct ssh_session_struct *session, struct ssh_buffer_struct *data, struct ssh_public_key_struct *pubkey); #endif #endif /* __AGENT_H */ /* vim: set ts=2 sw=2 et cindent: */
zzlydm-fbbs
include/libssh/agent.h
C
gpl3
3,014
#ifndef __SSH1_H #define __SSH1_H #define SSH_MSG_NONE 0 /* no message */ #define SSH_MSG_DISCONNECT 1 /* cause (string) */ #define SSH_SMSG_PUBLIC_KEY 2 /* ck,msk,srvk,hostk */ #define SSH_CMSG_SESSION_KEY 3 /* key (BIGNUM) */ #define SSH_CMSG_USER 4 /* user (string) */ #define SSH_CMSG_AUTH_RHOSTS 5 /* user (string) */ #define SSH_CMSG_AUTH_RSA 6 /* modulus (BIGNUM) */ #define SSH_SMSG_AUTH_RSA_CHALLENGE 7 /* int (BIGNUM) */ #define SSH_CMSG_AUTH_RSA_RESPONSE 8 /* int (BIGNUM) */ #define SSH_CMSG_AUTH_PASSWORD 9 /* pass (string) */ #define SSH_CMSG_REQUEST_PTY 10 /* TERM, tty modes */ #define SSH_CMSG_WINDOW_SIZE 11 /* row,col,xpix,ypix */ #define SSH_CMSG_EXEC_SHELL 12 /* */ #define SSH_CMSG_EXEC_CMD 13 /* cmd (string) */ #define SSH_SMSG_SUCCESS 14 /* */ #define SSH_SMSG_FAILURE 15 /* */ #define SSH_CMSG_STDIN_DATA 16 /* data (string) */ #define SSH_SMSG_STDOUT_DATA 17 /* data (string) */ #define SSH_SMSG_STDERR_DATA 18 /* data (string) */ #define SSH_CMSG_EOF 19 /* */ #define SSH_SMSG_EXITSTATUS 20 /* status (int) */ #define SSH_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* channel (int) */ #define SSH_MSG_CHANNEL_OPEN_FAILURE 22 /* channel (int) */ #define SSH_MSG_CHANNEL_DATA 23 /* ch,data (int,str) */ #define SSH_MSG_CHANNEL_CLOSE 24 /* channel (int) */ #define SSH_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* channel (int) */ /* SSH_CMSG_X11_REQUEST_FORWARDING 26 OBSOLETE */ #define SSH_SMSG_X11_OPEN 27 /* channel (int) */ #define SSH_CMSG_PORT_FORWARD_REQUEST 28 /* p,host,hp (i,s,i) */ #define SSH_MSG_PORT_OPEN 29 /* ch,h,p (i,s,i) */ #define SSH_CMSG_AGENT_REQUEST_FORWARDING 30 /* */ #define SSH_SMSG_AGENT_OPEN 31 /* port (int) */ #define SSH_MSG_IGNORE 32 /* string */ #define SSH_CMSG_EXIT_CONFIRMATION 33 /* */ #define SSH_CMSG_X11_REQUEST_FORWARDING 34 /* proto,data (s,s) */ #define SSH_CMSG_AUTH_RHOSTS_RSA 35 /* user,mod (s,mpi) */ #define SSH_MSG_DEBUG 36 /* string */ #define SSH_CMSG_REQUEST_COMPRESSION 37 /* level 1-9 (int) */ #define SSH_CMSG_MAX_PACKET_SIZE 38 /* size 4k-1024k (int) */ #define SSH_CMSG_AUTH_TIS 39 /* we use this for s/key */ #define SSH_SMSG_AUTH_TIS_CHALLENGE 40 /* challenge (string) */ #define SSH_CMSG_AUTH_TIS_RESPONSE 41 /* response (string) */ #define SSH_CMSG_AUTH_KERBEROS 42 /* (KTEXT) */ #define SSH_SMSG_AUTH_KERBEROS_RESPONSE 43 /* (KTEXT) */ #define SSH_CMSG_HAVE_KERBEROS_TGT 44 /* credentials (s) */ #define SSH_CMSG_HAVE_AFS_TOKEN 65 /* token (s) */ /* protocol version 1.5 overloads some version 1.3 message types */ #define SSH_MSG_CHANNEL_INPUT_EOF SSH_MSG_CHANNEL_CLOSE #define SSH_MSG_CHANNEL_OUTPUT_CLOSE SSH_MSG_CHANNEL_CLOSE_CONFIRMATION /* * Authentication methods. New types can be added, but old types should not * be removed for compatibility. The maximum allowed value is 31. */ #define SSH_AUTH_RHOSTS 1 #define SSH_AUTH_RSA 2 #define SSH_AUTH_PASSWORD 3 #define SSH_AUTH_RHOSTS_RSA 4 #define SSH_AUTH_TIS 5 #define SSH_AUTH_KERBEROS 6 #define SSH_PASS_KERBEROS_TGT 7 /* 8 to 15 are reserved */ #define SSH_PASS_AFS_TOKEN 21 /* Protocol flags. These are bit masks. */ #define SSH_PROTOFLAG_SCREEN_NUMBER 1 /* X11 forwarding includes screen */ #define SSH_PROTOFLAG_HOST_IN_FWD_OPEN 2 /* forwarding opens contain host */ /* cipher flags. they are bit numbers */ #define SSH_CIPHER_NONE 0 /* No encryption */ #define SSH_CIPHER_IDEA 1 /* IDEA in CFB mode */ #define SSH_CIPHER_DES 2 /* DES in CBC mode */ #define SSH_CIPHER_3DES 3 /* Triple-DES in CBC mode */ #define SSH_CIPHER_RC4 5 /* RC4 */ #define SSH_CIPHER_BLOWFISH 6 #endif
zzlydm-fbbs
include/libssh/ssh1.h
C
gpl3
3,660
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef SESSION_H_ #define SESSION_H_ #include "libssh/priv.h" #include "libssh/packet.h" #include "libssh/pcap.h" typedef struct ssh_kbdint_struct* ssh_kbdint; struct ssh_session_struct { struct error_struct error; struct socket *socket; char *serverbanner; char *clientbanner; int protoversion; int server; int client; int openssh; uint32_t send_seq; uint32_t recv_seq; /* status flags */ int closed; int closed_by_except; int connected; /* !=0 when the user got a session handle */ int alive; /* two previous are deprecated */ int auth_service_asked; /* socket status */ int blocking; // functions should block ssh_string banner; /* that's the issue banner from the server */ char *remotebanner; /* that's the SSH- banner from remote host. */ char *discon_msg; /* disconnect message from the remote host */ ssh_buffer in_buffer; PACKET in_packet; ssh_buffer out_buffer; /* the states are used by the nonblocking stuff to remember */ /* where it was before being interrupted */ int packet_state; int dh_handshake_state; ssh_string dh_server_signature; //information used by dh_handshake. KEX server_kex; KEX client_kex; ssh_buffer in_hashbuf; ssh_buffer out_hashbuf; struct ssh_crypto_struct *current_crypto; struct ssh_crypto_struct *next_crypto; /* next_crypto is going to be used after a SSH2_MSG_NEWKEYS */ ssh_channel channels; /* linked list of channels */ int maxchannel; int exec_channel_opened; /* version 1 only. more info in channels1.c */ ssh_agent agent; /* ssh agent */ /* keyb interactive data */ struct ssh_kbdint_struct *kbdint; int version; /* 1 or 2 */ /* server host keys */ ssh_private_key rsa_key; ssh_private_key dsa_key; /* auths accepted by server */ int auth_methods; int hostkeys; /* contains type of host key wanted by client, in server impl */ struct ssh_list *ssh_message_list; /* list of delayed SSH messages */ int (*ssh_message_callback)( struct ssh_session_struct *session, ssh_message msg); int log_verbosity; /*cached copy of the option structure */ int log_indent; /* indentation level in enter_function logs */ ssh_callbacks callbacks; /* Callbacks to user functions */ /* options */ #ifdef WITH_PCAP ssh_pcap_context pcap_ctx; /* pcap debugging context */ #endif char *username; char *host; char *bindaddr; /* TODO: check if needed */ char *xbanner; /* TODO: looks like it is not needed */ struct ssh_list *identity; char *sshdir; char *knownhosts; char *wanted_methods[10]; unsigned long timeout; /* seconds */ unsigned long timeout_usec; unsigned int port; socket_t fd; int ssh2; int ssh1; char *ProxyCommand; }; int ssh_handle_packets(ssh_session session); void ssh_global_request_handle(ssh_session session); #endif /* SESSION_H_ */
zzlydm-fbbs
include/libssh/session.h
C
gpl3
3,943
/* * This file is part of the SSH Library * * Copyright (c) 2009 Aris Adamantiadis <aris@0xbadc0de.be> * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ /* callback.h * This file includes the public declarations for the libssh callback mechanism */ #ifndef _SSH_CALLBACK_H #define _SSH_CALLBACK_H #include <libssh/libssh.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /** * @brief SSH authentication callback. * * @param prompt Prompt to be displayed. * @param buf Buffer to save the password. You should null-terminate it. * @param len Length of the buffer. * @param echo Enable or disable the echo of what you type. * @param verify Should the password be verified? * @param userdata Userdata to be passed to the callback function. Useful * for GUI applications. * * @return 0 on success, < 0 on error. */ typedef int (*ssh_auth_callback) (const char *prompt, char *buf, size_t len, int echo, int verify, void *userdata); typedef void (*ssh_log_callback) (ssh_session session, int priority, const char *message, void *userdata); /** this callback will be called with status going from 0.0 to 1.0 during * connection */ typedef void (*ssh_status_callback) (ssh_session session, float status, void *userdata); struct ssh_callbacks_struct { /** size of this structure. internal, shoud be set with ssh_callbacks_init()*/ size_t size; /** User-provided data. User is free to set anything he wants here */ void *userdata; /** this functions will be called if e.g. a keyphrase is needed. */ ssh_auth_callback auth_function; /** this function will be called each time a loggable event happens. */ ssh_log_callback log_function; /** this function gets called during connection time to indicate the percentage * of connection steps completed. */ void (*connect_status_function)(void *userdata, float status); }; typedef struct ssh_callbacks_struct * ssh_callbacks; /** Initializes an ssh_callbacks_struct * A call to this macro is mandatory when you have set a new * ssh_callback_struct structure. Its goal is to maintain the binary * compatibility with future versions of libssh as the structure * evolves with time. */ #define ssh_callbacks_init(p) do {\ (p)->size=sizeof(*(p)); \ } while(0); /** * @brief Set the callback functions. * * This functions sets the callback structure to use your own callback * functions for auth, logging and status. * * @code * struct ssh_callbacks_struct cb; * memset(&cb, 0, sizeof(struct ssh_callbacks_struct)); * cb.userdata = data; * cb.auth_function = my_auth_function; * * ssh_callbacks_init(&cb); * ssh_set_callbacks(session, &cb); * @endcode * * @param session The session to set the callback structure. * * @param cb The callback itself. * * @return 0 on success, < 0 on error. */ LIBSSH_API int ssh_set_callbacks(ssh_session session, ssh_callbacks cb); #ifdef __cplusplus } #endif #endif /*_SSH_CALLBACK_H */
zzlydm-fbbs
include/libssh/callbacks.h
C
gpl3
3,769
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef DH_H_ #define DH_H_ #include "config.h" /* DH key generation */ #include "libssh/keys.h" void ssh_print_bignum(const char *which,bignum num); int dh_generate_e(ssh_session session); int dh_generate_f(ssh_session session); int dh_generate_x(ssh_session session); int dh_generate_y(ssh_session session); int ssh_crypto_init(void); void ssh_crypto_finalize(void); ssh_string dh_get_e(ssh_session session); ssh_string dh_get_f(ssh_session session); int dh_import_f(ssh_session session,ssh_string f_string); int dh_import_e(ssh_session session, ssh_string e_string); void dh_import_pubkey(ssh_session session,ssh_string pubkey_string); int dh_build_k(ssh_session session); int make_sessionid(ssh_session session); /* add data for the final cookie */ int hashbufin_add_cookie(ssh_session session, unsigned char *cookie); int hashbufout_add_cookie(ssh_session session); int generate_session_keys(ssh_session session); int sig_verify(ssh_session session, ssh_public_key pubkey, SIGNATURE *signature, unsigned char *digest, int size); /* returns 1 if server signature ok, 0 otherwise. The NEXT crypto is checked, not the current one */ int signature_verify(ssh_session session,ssh_string signature); bignum make_string_bn(ssh_string string); ssh_string make_bignum_string(bignum num); #endif /* DH_H_ */
zzlydm-fbbs
include/libssh/dh.h
C
gpl3
2,182
/* * This file is part of the SSH Library * * Copyright (c) 2003-2008 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ /** * @file sftp.h * * @brief SFTP handling functions * * SFTP commands are channeled by the ssh sftp subsystem. Every packet is * sent/read using a sftp_packet type structure. Related to these packets, * most of the server answers are messages having an ID and a message * specific part. It is described by sftp_message when reading a message, * the sftp system puts it into the queue, so the process having asked for * it can fetch it, while continuing to read for other messages (it is * unspecified in which order messages may be sent back to the client * * @defgroup ssh_sftp SFTP Functions * @{ */ #ifndef SFTP_H #define SFTP_H #include <sys/types.h> #include "libssh.h" #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 #ifndef uid_t typedef uint32_t uid_t; #endif /* uid_t */ #ifndef gid_t typedef uint32_t gid_t; #endif /* gid_t */ #ifdef _MSC_VER #ifndef ssize_t typedef _W64 SSIZE_T ssize_t; #endif /* ssize_t */ #endif /* _MSC_VER */ #endif /* _WIN32 */ typedef struct sftp_attributes_struct* sftp_attributes; typedef struct sftp_client_message_struct* sftp_client_message; typedef struct sftp_dir_struct* sftp_dir; typedef struct sftp_ext_struct *sftp_ext; typedef struct sftp_file_struct* sftp_file; typedef struct sftp_message_struct* sftp_message; typedef struct sftp_packet_struct* sftp_packet; typedef struct sftp_request_queue_struct* sftp_request_queue; typedef struct sftp_session_struct* sftp_session; typedef struct sftp_status_message_struct* sftp_status_message; typedef struct sftp_statvfs_struct* sftp_statvfs_t; struct sftp_session_struct { ssh_session session; ssh_channel channel; int server_version; int client_version; int version; sftp_request_queue queue; uint32_t id_counter; int errnum; void **handles; sftp_ext ext; }; struct sftp_packet_struct { sftp_session sftp; uint8_t type; ssh_buffer payload; }; /* file handler */ struct sftp_file_struct { sftp_session sftp; char *name; uint64_t offset; ssh_string handle; int eof; int nonblocking; }; struct sftp_dir_struct { sftp_session sftp; char *name; ssh_string handle; /* handle to directory */ ssh_buffer buffer; /* contains raw attributes from server which haven't been parsed */ uint32_t count; /* counts the number of following attributes structures into buffer */ int eof; /* end of directory listing */ }; struct sftp_message_struct { sftp_session sftp; uint8_t packet_type; ssh_buffer payload; uint32_t id; }; /* this is a bunch of all data that could be into a message */ struct sftp_client_message_struct { sftp_session sftp; uint8_t type; uint32_t id; char *filename; /* can be "path" */ uint32_t flags; sftp_attributes attr; ssh_string handle; uint64_t offset; uint32_t len; int attr_num; ssh_buffer attrbuf; /* used by sftp_reply_attrs */ ssh_string data; /* can be newpath of rename() */ }; struct sftp_request_queue_struct { sftp_request_queue next; sftp_message message; }; /* SSH_FXP_MESSAGE described into .7 page 26 */ struct sftp_status_message_struct { uint32_t id; uint32_t status; ssh_string error; ssh_string lang; char *errormsg; char *langmsg; }; struct sftp_attributes_struct { char *name; char *longname; /* ls -l output on openssh, not reliable else */ uint32_t flags; uint8_t type; uint64_t size; uint32_t uid; uint32_t gid; char *owner; /* set if openssh and version 4 */ char *group; /* set if openssh and version 4 */ uint32_t permissions; uint64_t atime64; uint32_t atime; uint32_t atime_nseconds; uint64_t createtime; uint32_t createtime_nseconds; uint64_t mtime64; uint32_t mtime; uint32_t mtime_nseconds; ssh_string acl; uint32_t extended_count; ssh_string extended_type; ssh_string extended_data; }; struct sftp_statvfs_struct { uint64_t f_bsize; /* file system block size */ uint64_t f_frsize; /* fundamental fs block size */ uint64_t f_blocks; /* number of blocks (unit f_frsize) */ uint64_t f_bfree; /* free blocks in file system */ uint64_t f_bavail; /* free blocks for non-root */ uint64_t f_files; /* total file inodes */ uint64_t f_ffree; /* free file inodes */ uint64_t f_favail; /* free file inodes for to non-root */ uint64_t f_fsid; /* file system id */ uint64_t f_flag; /* bit mask of f_flag values */ uint64_t f_namemax; /* maximum filename length */ }; #define LIBSFTP_VERSION 3 /** * @brief Start a new sftp session. * * @param session The ssh session to use. * * @return A new sftp session or NULL on error. */ LIBSSH_API sftp_session sftp_new(ssh_session session); /** * @brief Close and deallocate a sftp session. * * @param sftp The sftp session handle to free. */ LIBSSH_API void sftp_free(sftp_session sftp); /** * @brief Initialize the sftp session with the server. * * @param sftp The sftp session to initialize. * * @return 0 on success, < 0 on error with ssh error set. */ LIBSSH_API int sftp_init(sftp_session sftp); /** * @brief Get the last sftp error. * * Use this function to get the latest error set by a posix like sftp function. * * @param sftp The sftp session where the error is saved. * * @return The saved error (see server responses), < 0 if an error * in the function occured. */ LIBSSH_API int sftp_get_error(sftp_session sftp); /** * @brief Get the count of extensions provided by the server. * * @param sftp The sftp session to use. * * @return The count of extensions provided by the server, 0 on error or * not available. */ LIBSSH_API unsigned int sftp_extensions_get_count(sftp_session sftp); /** * @brief Get the name of the extension provided by the server. * * @param sftp The sftp session to use. * * @param indexn The index number of the extension name you want. * * @return The name of the extension. */ LIBSSH_API const char *sftp_extensions_get_name(sftp_session sftp, unsigned int indexn); /** * @brief Get the data of the extension provided by the server. * * This is normally the version number of the extension. * * @param sftp The sftp session to use. * * @param indexn The index number of the extension data you want. * * @return The data of the extension. */ LIBSSH_API const char *sftp_extensions_get_data(sftp_session sftp, unsigned int indexn); /** * @brief Check if the given extension is supported. * * @param sftp The sftp session to use. * * @param name The name of the extension. * * @param data The data of the extension. * * @return 1 if supported, 0 if not. * * Example: * * @code * sftp_extension_supported(sftp, "statvfs@openssh.com", "2"); * @endcode */ LIBSSH_API int sftp_extension_supported(sftp_session sftp, const char *name, const char *data); /** * @brief Open a directory used to obtain directory entries. * @param session The sftp session handle to open the directory. * @param path The path of the directory to open. * * @return A sftp directory handle or NULL on error with ssh and * sftp error set. * * @see sftp_readdir * @see sftp_closedir */ LIBSSH_API sftp_dir sftp_opendir(sftp_session session, const char *path); /** * @brief Get a single file attributes structure of a directory. * * @param session The sftp session handle to read the directory entry. * @param dir The opened sftp directory handle to read from. * * @return A file attribute structure or NULL at the end of the * directory. * * @see sftp_opendir() * @see sftp_attribute_free() * @see sftp_closedir() */ LIBSSH_API sftp_attributes sftp_readdir(sftp_session session, sftp_dir dir); /** * @brief Tell if the directory has reached EOF (End Of File). * * @param dir The sftp directory handle. * * @return 1 if the directory is EOF, 0 if not. * * @see sftp_readdir() */ LIBSSH_API int sftp_dir_eof(sftp_dir dir); /** * @brief Get information about a file or directory. * * @param session The sftp session handle. * @param path The path to the file or directory to obtain the * information. * * @return The sftp attributes structure of the file or directory, * NULL on error with ssh and sftp error set. */ LIBSSH_API sftp_attributes sftp_stat(sftp_session session, const char *path); /** * @brief Get information about a file or directory. * * Identical to sftp_stat, but if the file or directory is a symbolic link, * then the link itself is stated, not the file that it refers to. * * @param session The sftp session handle. * @param path The path to the file or directory to obtain the * information. * * @return The sftp attributes structure of the file or directory, * NULL on error with ssh and sftp error set. */ LIBSSH_API sftp_attributes sftp_lstat(sftp_session session, const char *path); /** * @brief Get information about a file or directory from a file handle. * * @param file The sftp file handle to get the stat information. * * @return The sftp attributes structure of the file or directory, * NULL on error with ssh and sftp error set. */ LIBSSH_API sftp_attributes sftp_fstat(sftp_file file); /** * @brief Free a sftp attribute structure. * * @param file The sftp attribute structure to free. */ LIBSSH_API void sftp_attributes_free(sftp_attributes file); /** * @brief Close a directory handle opened by sftp_opendir(). * * @param dir The sftp directory handle to close. * * @return Returns SSH_NO_ERROR or SSH_ERROR if an error occured. */ LIBSSH_API int sftp_closedir(sftp_dir dir); /** * @brief Close an open file handle. * * @param file The open sftp file handle to close. * * @return Returns SSH_NO_ERROR or SSH_ERROR if an error occured. * * @see sftp_open() */ LIBSSH_API int sftp_close(sftp_file file); /** * @brief Open a file on the server. * * @param session The sftp session handle. * * @param file The file to be opened. * * @param accesstype Is one of O_RDONLY, O_WRONLY or O_RDWR which request * opening the file read-only,write-only or read/write. * Acesss may also be bitwise-or'd with one or more of * the following: * O_CREAT - If the file does not exist it will be * created. * O_EXCL - When used with O_CREAT, if the file already * exists it is an error and the open will fail. * O_TRUNC - If the file already exists it will be * truncated. * * @param mode Mode specifies the permissions to use if a new file is * created. It is modified by the process's umask in * the usual way: The permissions of the created file are * (mode & ~umask) * * @return A sftp file handle, NULL on error with ssh and sftp * error set. */ LIBSSH_API sftp_file sftp_open(sftp_session session, const char *file, int accesstype, mode_t mode); LIBSSH_API void sftp_file_set_nonblocking(sftp_file handle); LIBSSH_API void sftp_file_set_blocking(sftp_file handle); /** * @brief Read from a file using an opened sftp file handle. * * @param file The opened sftp file handle to be read from. * * @param buf Pointer to buffer to recieve read data. * * @param count Size of the buffer in bytes. * * @return Number of bytes written, < 0 on error with ssh and sftp * error set. */ LIBSSH_API ssize_t sftp_read(sftp_file file, void *buf, size_t count); /** * @brief Start an asynchronous read from a file using an opened sftp file handle. * * Its goal is to avoid the slowdowns related to the request/response pattern * of a synchronous read. To do so, you must call 2 functions: * * sftp_async_read_begin() and sftp_async_read(). * * The first step is to call sftp_async_read_begin(). This function returns a * request identifier. The second step is to call sftp_async_read() using the * returned identifier. * * @param file The opened sftp file handle to be read from. * * @param len Size to read in bytes. * * @return An identifier corresponding to the sent request, < 0 on * error. * * @warning When calling this function, the internal offset is * updated corresponding to the len parameter. * * @warning A call to sftp_async_read_begin() sends a request to * the server. When the server answers, libssh allocates * memory to store it until sftp_async_read() is called. * Not calling sftp_async_read() will lead to memory * leaks. * * @see sftp_async_read() * @see sftp_open() */ LIBSSH_API int sftp_async_read_begin(sftp_file file, uint32_t len); /** * @brief Wait for an asynchronous read to complete and save the data. * * @param file The opened sftp file handle to be read from. * * @param data Pointer to buffer to recieve read data. * * @param len Size of the buffer in bytes. It should be bigger or * equal to the length parameter of the * sftp_async_read_begin() call. * * @param id The identifier returned by the sftp_async_read_begin() * function. * * @return Number of bytes read, 0 on EOF, SSH_ERROR if an error * occured, SSH_AGAIN if the file is opened in nonblocking * mode and the request hasn't been executed yet. * * @warning A call to this function with an invalid identifier * will never return. * * @see sftp_async_read_begin() */ LIBSSH_API int sftp_async_read(sftp_file file, void *data, uint32_t len, uint32_t id); /** * @brief Write to a file using an opened sftp file handle. * * @param file Open sftp file handle to write to. * * @param buf Pointer to buffer to write data. * * @param count Size of buffer in bytes. * * @return Number of bytes written, < 0 on error with ssh and sftp * error set. * * @see sftp_open() * @see sftp_read() * @see sftp_close() */ LIBSSH_API ssize_t sftp_write(sftp_file file, const void *buf, size_t count); /** * @brief Seek to a specific location in a file. * * @param file Open sftp file handle to seek in. * * @param new_offset Offset in bytes to seek. * * @return 0 on success, < 0 on error. */ LIBSSH_API int sftp_seek(sftp_file file, uint32_t new_offset); /** * @brief Seek to a specific location in a file. This is the * 64bit version. * * @param file Open sftp file handle to seek in. * * @param new_offset Offset in bytes to seek. * * @return 0 on success, < 0 on error. */ LIBSSH_API int sftp_seek64(sftp_file file, uint64_t new_offset); /** * @brief Report current byte position in file. * * @param file Open sftp file handle. * * @return The offset of the current byte relative to the beginning * of the file associated with the file descriptor. < 0 on * error. */ LIBSSH_API unsigned long sftp_tell(sftp_file file); /** * @brief Report current byte position in file. * * @param file Open sftp file handle. * * @return The offset of the current byte relative to the beginning * of the file associated with the file descriptor. < 0 on * error. */ LIBSSH_API uint64_t sftp_tell64(sftp_file file); /** * @brief Rewinds the position of the file pointer to the beginning of the * file. * * @param file Open sftp file handle. */ LIBSSH_API void sftp_rewind(sftp_file file); /** * @brief Unlink (delete) a file. * * @param sftp The sftp session handle. * * @param file The file to unlink/delete. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_unlink(sftp_session sftp, const char *file); /** * @brief Remove a directoy. * * @param sftp The sftp session handle. * * @param directory The directory to remove. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_rmdir(sftp_session sftp, const char *directory); /** * @brief Create a directory. * * @param sftp The sftp session handle. * * @param directory The directory to create. * * @param mode Specifies the permissions to use. It is modified by the * process's umask in the usual way: * The permissions of the created file are (mode & ~umask) * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_mkdir(sftp_session sftp, const char *directory, mode_t mode); /** * @brief Rename or move a file or directory. * * @param sftp The sftp session handle. * * @param original The original url (source url) of file or directory to * be moved. * * @param newname The new url (destination url) of the file or directory * after the move. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_rename(sftp_session sftp, const char *original, const char *newname); /** * @brief Set file attributes on a file, directory or symbolic link. * * @param sftp The sftp session handle. * * @param file The file which attributes should be changed. * * @param attr The file attributes structure with the attributes set * which should be changed. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_setstat(sftp_session sftp, const char *file, sftp_attributes attr); /** * @brief Change the file owner and group * * @param sftp The sftp session handle. * * @param file The file which owner and group should be changed. * * @param owner The new owner which should be set. * * @param group The new group which should be set. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_chown(sftp_session sftp, const char *file, uid_t owner, gid_t group); /** * @brief Change permissions of a file * * @param sftp The sftp session handle. * * @param file The file which owner and group should be changed. * * @param mode Specifies the permissions to use. It is modified by the * process's umask in the usual way: * The permissions of the created file are (mode & ~umask) * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_chmod(sftp_session sftp, const char *file, mode_t mode); /** * @brief Change the last modification and access time of a file. * * @param sftp The sftp session handle. * * @param file The file which owner and group should be changed. * * @param times A timeval structure which contains the desired access * and modification time. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_utimes(sftp_session sftp, const char *file, const struct timeval *times); /** * @brief Create a symbolic link. * * @param sftp The sftp session handle. * * @param target Specifies the target of the symlink. * * @param dest Specifies the path name of the symlink to be created. * * @return 0 on success, < 0 on error with ssh and sftp error set. */ LIBSSH_API int sftp_symlink(sftp_session sftp, const char *target, const char *dest); /** * @brief Read the value of a symbolic link. * * @param sftp The sftp session handle. * * @param path Specifies the path name of the symlink to be read. * * @return The target of the link, NULL on error. */ LIBSSH_API char *sftp_readlink(sftp_session sftp, const char *path); /** * @brief Get information about a mounted file system. * * @param sftp The sftp session handle. * * @param path The pathname of any file within the mounted file system. * * @return A statvfs structure or NULL on error. */ LIBSSH_API sftp_statvfs_t sftp_statvfs(sftp_session sftp, const char *path); /** * @brief Get information about a mounted file system. * * @param file An opened file. * * @return A statvfs structure or NULL on error. */ LIBSSH_API sftp_statvfs_t sftp_fstatvfs(sftp_file file); /** * @brief Free the memory of an allocated statvfs. * * @param statvfs_o The statvfs to free. */ LIBSSH_API void sftp_statvfs_free(sftp_statvfs_t statvfs_o); /** * @brief Canonicalize a sftp path. * * @param sftp The sftp session handle. * * @param path The path to be canonicalized. * * @return The canonicalize path, NULL on error. */ LIBSSH_API char *sftp_canonicalize_path(sftp_session sftp, const char *path); /** * @brief Get the version of the SFTP protocol supported by the server * * @param sftp The sftp session handle. * * @return The server version. */ LIBSSH_API int sftp_server_version(sftp_session sftp); #ifdef WITH_SERVER /** * @brief Create a new sftp server session. * * @param session The ssh session to use. * * @param chan The ssh channel to use. * * @return A new sftp server session. */ LIBSSH_API sftp_session sftp_server_new(ssh_session session, ssh_channel chan); /** * @brief Intialize the sftp server. * * @param sftp The sftp session to init. * * @return 0 on success, < 0 on error. */ LIBSSH_API int sftp_server_init(sftp_session sftp); #endif /* WITH_SERVER */ /* this is not a public interface */ #define SFTP_HANDLES 256 sftp_packet sftp_packet_read(sftp_session sftp); int sftp_packet_write(sftp_session sftp,uint8_t type, ssh_buffer payload); void sftp_packet_free(sftp_packet packet); int buffer_add_attributes(ssh_buffer buffer, sftp_attributes attr); sftp_attributes sftp_parse_attr(sftp_session session, ssh_buffer buf,int expectname); /* sftpserver.c */ sftp_client_message sftp_get_client_message(sftp_session sftp); void sftp_client_message_free(sftp_client_message msg); int sftp_reply_name(sftp_client_message msg, const char *name, sftp_attributes attr); int sftp_reply_handle(sftp_client_message msg, ssh_string handle); ssh_string sftp_handle_alloc(sftp_session sftp, void *info); int sftp_reply_attr(sftp_client_message msg, sftp_attributes attr); void *sftp_handle(sftp_session sftp, ssh_string handle); int sftp_reply_status(sftp_client_message msg, uint32_t status, const char *message); int sftp_reply_names_add(sftp_client_message msg, const char *file, const char *longname, sftp_attributes attr); int sftp_reply_names(sftp_client_message msg); int sftp_reply_data(sftp_client_message msg, const void *data, int len); void sftp_handle_remove(sftp_session sftp, void *handle); /* SFTP commands and constants */ #define SSH_FXP_INIT 1 #define SSH_FXP_VERSION 2 #define SSH_FXP_OPEN 3 #define SSH_FXP_CLOSE 4 #define SSH_FXP_READ 5 #define SSH_FXP_WRITE 6 #define SSH_FXP_LSTAT 7 #define SSH_FXP_FSTAT 8 #define SSH_FXP_SETSTAT 9 #define SSH_FXP_FSETSTAT 10 #define SSH_FXP_OPENDIR 11 #define SSH_FXP_READDIR 12 #define SSH_FXP_REMOVE 13 #define SSH_FXP_MKDIR 14 #define SSH_FXP_RMDIR 15 #define SSH_FXP_REALPATH 16 #define SSH_FXP_STAT 17 #define SSH_FXP_RENAME 18 #define SSH_FXP_READLINK 19 #define SSH_FXP_SYMLINK 20 #define SSH_FXP_STATUS 101 #define SSH_FXP_HANDLE 102 #define SSH_FXP_DATA 103 #define SSH_FXP_NAME 104 #define SSH_FXP_ATTRS 105 #define SSH_FXP_EXTENDED 200 #define SSH_FXP_EXTENDED_REPLY 201 /* attributes */ /* sftp draft is completely braindead : version 3 and 4 have different flags for same constants */ /* and even worst, version 4 has same flag for 2 different constants */ /* follow up : i won't develop any sftp4 compliant library before having a clarification */ #define SSH_FILEXFER_ATTR_SIZE 0x00000001 #define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004 #define SSH_FILEXFER_ATTR_ACCESSTIME 0x00000008 #define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008 #define SSH_FILEXFER_ATTR_CREATETIME 0x00000010 #define SSH_FILEXFER_ATTR_MODIFYTIME 0x00000020 #define SSH_FILEXFER_ATTR_ACL 0x00000040 #define SSH_FILEXFER_ATTR_OWNERGROUP 0x00000080 #define SSH_FILEXFER_ATTR_SUBSECOND_TIMES 0x00000100 #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000 #define SSH_FILEXFER_ATTR_UIDGID 0x00000002 /* types */ #define SSH_FILEXFER_TYPE_REGULAR 1 #define SSH_FILEXFER_TYPE_DIRECTORY 2 #define SSH_FILEXFER_TYPE_SYMLINK 3 #define SSH_FILEXFER_TYPE_SPECIAL 4 #define SSH_FILEXFER_TYPE_UNKNOWN 5 /* server responses */ #define SSH_FX_OK 0 #define SSH_FX_EOF 1 #define SSH_FX_NO_SUCH_FILE 2 #define SSH_FX_PERMISSION_DENIED 3 #define SSH_FX_FAILURE 4 #define SSH_FX_BAD_MESSAGE 5 #define SSH_FX_NO_CONNECTION 6 #define SSH_FX_CONNECTION_LOST 7 #define SSH_FX_OP_UNSUPPORTED 8 #define SSH_FX_INVALID_HANDLE 9 #define SSH_FX_NO_SUCH_PATH 10 #define SSH_FX_FILE_ALREADY_EXISTS 11 #define SSH_FX_WRITE_PROTECT 12 #define SSH_FX_NO_MEDIA 13 /* file flags */ #define SSH_FXF_READ 0x01 #define SSH_FXF_WRITE 0x02 #define SSH_FXF_APPEND 0x04 #define SSH_FXF_CREAT 0x08 #define SSH_FXF_TRUNC 0x10 #define SSH_FXF_EXCL 0x20 #define SSH_FXF_TEXT 0x40 /* rename flags */ #define SSH_FXF_RENAME_OVERWRITE 0x00000001 #define SSH_FXF_RENAME_ATOMIC 0x00000002 #define SSH_FXF_RENAME_NATIVE 0x00000004 #define SFTP_OPEN SSH_FXP_OPEN #define SFTP_CLOSE SSH_FXP_CLOSE #define SFTP_READ SSH_FXP_READ #define SFTP_WRITE SSH_FXP_WRITE #define SFTP_LSTAT SSH_FXP_LSTAT #define SFTP_FSTAT SSH_FXP_FSTAT #define SFTP_SETSTAT SSH_FXP_SETSTAT #define SFTP_FSETSTAT SSH_FXP_FSETSTAT #define SFTP_OPENDIR SSH_FXP_OPENDIR #define SFTP_READDIR SSH_FXP_READDIR #define SFTP_REMOVE SSH_FXP_REMOVE #define SFTP_MKDIR SSH_FXP_MKDIR #define SFTP_RMDIR SSH_FXP_RMDIR #define SFTP_REALPATH SSH_FXP_REALPATH #define SFTP_STAT SSH_FXP_STAT #define SFTP_RENAME SSH_FXP_RENAME #define SFTP_READLINK SSH_FXP_READLINK #define SFTP_SYMLINK SSH_FXP_SYMLINK /* openssh flags */ #define SSH_FXE_STATVFS_ST_RDONLY 0x1 /* read-only */ #define SSH_FXE_STATVFS_ST_NOSUID 0x2 /* no setuid */ #ifdef __cplusplus } ; #endif #endif /* SFTP_H */ /** @} */ /* vim: set ts=2 sw=2 et cindent: */
zzlydm-fbbs
include/libssh/sftp.h
C
gpl3
28,441
/* * This file is part of the SSH Library * * Copyright (c) 2003-2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef _LIBSSH_H #define _LIBSSH_H #ifdef LIBSSH_STATIC #define LIBSSH_API #else #if defined _WIN32 || defined __CYGWIN__ #ifdef LIBSSH_EXPORTS #ifdef __GNUC__ #define LIBSSH_API __attribute__((dllexport)) #else #define LIBSSH_API __declspec(dllexport) #endif #else #ifdef __GNUC__ #define LIBSSH_API __attribute__((dllimport)) #else #define LIBSSH_API __declspec(dllimport) #endif #endif #else #if __GNUC__ >= 4 #define LIBSSH_API __attribute__((visibility("default"))) #else #define LIBSSH_API #endif #endif #endif #ifdef _MSC_VER /* Visual Studio hasn't inttypes.h so it doesn't know uint32_t */ typedef int int32_t; typedef unsigned int uint32_t; typedef unsigned short uint16_t; typedef unsigned char uint8_t; typedef unsigned long long uint64_t; typedef int mode_t; #else /* _MSC_VER */ #include <unistd.h> #include <inttypes.h> #endif /* _MSC_VER */ #ifdef _WIN32 #include <winsock2.h> #else /* _WIN32 */ #include <sys/select.h> /* for fd_set * */ #include <netdb.h> #endif /* _WIN32 */ #define SSH_STRINGIFY(s) SSH_TOSTRING(s) #define SSH_TOSTRING(s) #s /* libssh version macros */ #define SSH_VERSION_INT(a, b, c) ((a) << 16 | (b) << 8 | (c)) #define SSH_VERSION_DOT(a, b, c) a ##.## b ##.## c #define SSH_VERSION(a, b, c) SSH_VERSION_DOT(a, b, c) /* libssh version */ #define LIBSSH_VERSION_MAJOR 0 #define LIBSSH_VERSION_MINOR 4 #define LIBSSH_VERSION_MICRO 3 #define LIBSSH_VERSION_INT SSH_VERSION_INT(LIBSSH_VERSION_MAJOR, \ LIBSSH_VERSION_MINOR, \ LIBSSH_VERSION_MICRO) #define LIBSSH_VERSION SSH_VERSION(LIBSSH_VERSION_MAJOR, \ LIBSSH_VERSION_MINOR, \ LIBSSH_VERSION_MICRO) /* GCC have printf type attribute check. */ #ifdef __GNUC__ #define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b))) #else #define PRINTF_ATTRIBUTE(a,b) #endif /* __GNUC__ */ #ifdef __GNUC__ #define SSH_DEPRECATED __attribute__ ((deprecated)) #else #define SSH_DEPRECATED #endif #ifdef __cplusplus extern "C" { #endif typedef struct ssh_agent_struct* ssh_agent; typedef struct ssh_buffer_struct* ssh_buffer; typedef struct ssh_channel_struct* ssh_channel; typedef struct ssh_message_struct* ssh_message; typedef struct ssh_pcap_file_struct* ssh_pcap_file; typedef struct ssh_private_key_struct* ssh_private_key; typedef struct ssh_public_key_struct* ssh_public_key; typedef struct ssh_scp_struct* ssh_scp; typedef struct ssh_session_struct* ssh_session; typedef struct ssh_string_struct* ssh_string; /* Socket type */ #ifdef _WIN32 #define socket_t SOCKET #else typedef int socket_t; #endif /* the offsets of methods */ enum ssh_kex_types_e { SSH_KEX=0, SSH_HOSTKEYS, SSH_CRYPT_C_S, SSH_CRYPT_S_C, SSH_MAC_C_S, SSH_MAC_S_C, SSH_COMP_C_S, SSH_COMP_S_C, SSH_LANG_C_S, SSH_LANG_S_C }; #define SSH_CRYPT 2 #define SSH_MAC 3 #define SSH_COMP 4 #define SSH_LANG 5 enum ssh_auth_e { SSH_AUTH_SUCCESS=0, SSH_AUTH_DENIED, SSH_AUTH_PARTIAL, SSH_AUTH_INFO, SSH_AUTH_ERROR=-1 }; /* auth flags */ #define SSH_AUTH_METHOD_UNKNOWN 0 #define SSH_AUTH_METHOD_NONE 0x0001 #define SSH_AUTH_METHOD_PASSWORD 0x0002 #define SSH_AUTH_METHOD_PUBLICKEY 0x0004 #define SSH_AUTH_METHOD_HOSTBASED 0x0008 #define SSH_AUTH_METHOD_INTERACTIVE 0x0010 /* messages */ enum ssh_requests_e { SSH_REQUEST_AUTH=1, SSH_REQUEST_CHANNEL_OPEN, SSH_REQUEST_CHANNEL, SSH_REQUEST_SERVICE, SSH_REQUEST_GLOBAL, }; enum ssh_channel_type_e { SSH_CHANNEL_UNKNOWN=0, SSH_CHANNEL_SESSION, SSH_CHANNEL_DIRECT_TCPIP, SSH_CHANNEL_FORWARDED_TCPIP, SSH_CHANNEL_X11 }; enum ssh_channel_requests_e { SSH_CHANNEL_REQUEST_UNKNOWN=0, SSH_CHANNEL_REQUEST_PTY, SSH_CHANNEL_REQUEST_EXEC, SSH_CHANNEL_REQUEST_SHELL, SSH_CHANNEL_REQUEST_ENV, SSH_CHANNEL_REQUEST_SUBSYSTEM, SSH_CHANNEL_REQUEST_WINDOW_CHANGE, }; /* status flags */ #define SSH_CLOSED 0x01 #define SSH_READ_PENDING 0x02 #define SSH_CLOSED_ERROR 0x04 enum ssh_server_known_e { SSH_SERVER_ERROR=-1, SSH_SERVER_NOT_KNOWN=0, SSH_SERVER_KNOWN_OK, SSH_SERVER_KNOWN_CHANGED, SSH_SERVER_FOUND_OTHER, SSH_SERVER_FILE_NOT_FOUND, }; #ifndef MD5_DIGEST_LEN #define MD5_DIGEST_LEN 16 #endif /* errors */ enum ssh_error_types_e { SSH_NO_ERROR=0, SSH_REQUEST_DENIED, SSH_FATAL, SSH_EINTR }; /* Error return codes */ #define SSH_OK 0 /* No error */ #define SSH_ERROR -1 /* Error of some kind */ #define SSH_AGAIN -2 /* The nonblocking call must be repeated */ #define SSH_EOF -127 /* We have already a eof */ /** \addtogroup ssh_log * @{ */ /** \brief Verbosity level for logging and help to debugging */ enum { /** No logging at all */ SSH_LOG_NOLOG=0, /** Only rare and noteworthy events */ SSH_LOG_RARE, /** High level protocol information */ SSH_LOG_PROTOCOL, /** Lower level protocol infomations, packet level */ SSH_LOG_PACKET, /** Every function path */ SSH_LOG_FUNCTIONS }; /** @} */ enum ssh_options_e { SSH_OPTIONS_HOST, SSH_OPTIONS_PORT, SSH_OPTIONS_PORT_STR, SSH_OPTIONS_FD, SSH_OPTIONS_USER, SSH_OPTIONS_SSH_DIR, SSH_OPTIONS_IDENTITY, SSH_OPTIONS_ADD_IDENTITY, SSH_OPTIONS_KNOWNHOSTS, SSH_OPTIONS_TIMEOUT, SSH_OPTIONS_TIMEOUT_USEC, SSH_OPTIONS_SSH1, SSH_OPTIONS_SSH2, SSH_OPTIONS_LOG_VERBOSITY, SSH_OPTIONS_LOG_VERBOSITY_STR, SSH_OPTIONS_CIPHERS_C_S, SSH_OPTIONS_CIPHERS_S_C, SSH_OPTIONS_COMPRESSION_C_S, SSH_OPTIONS_COMPRESSION_S_C, SSH_OPTIONS_PROXYCOMMAND }; enum { /** Code is going to write/create remote files */ SSH_SCP_WRITE, /** Code is going to read remote files */ SSH_SCP_READ, SSH_SCP_RECURSIVE=0x10 }; enum ssh_scp_request_types { /** A new directory is going to be pulled */ SSH_SCP_REQUEST_NEWDIR=1, /** A new file is going to be pulled */ SSH_SCP_REQUEST_NEWFILE, /** End of requests */ SSH_SCP_REQUEST_EOF, /** End of directory */ SSH_SCP_REQUEST_ENDDIR, /** Warning received */ SSH_SCP_REQUEST_WARNING }; LIBSSH_API void buffer_free(ssh_buffer buffer); LIBSSH_API void *buffer_get(ssh_buffer buffer); LIBSSH_API uint32_t buffer_get_len(ssh_buffer buffer); LIBSSH_API ssh_buffer buffer_new(void); LIBSSH_API ssh_channel channel_accept_x11(ssh_channel channel, int timeout_ms); LIBSSH_API int channel_change_pty_size(ssh_channel channel,int cols,int rows); LIBSSH_API ssh_channel channel_forward_accept(ssh_session session, int timeout_ms); LIBSSH_API int channel_close(ssh_channel channel); LIBSSH_API int channel_forward_cancel(ssh_session session, const char *address, int port); LIBSSH_API int channel_forward_listen(ssh_session session, const char *address, int port, int *bound_port); LIBSSH_API void channel_free(ssh_channel channel); LIBSSH_API int channel_get_exit_status(ssh_channel channel); LIBSSH_API ssh_session channel_get_session(ssh_channel channel); LIBSSH_API int channel_is_closed(ssh_channel channel); LIBSSH_API int channel_is_eof(ssh_channel channel); LIBSSH_API int channel_is_open(ssh_channel channel); LIBSSH_API ssh_channel channel_new(ssh_session session); LIBSSH_API int channel_open_forward(ssh_channel channel, const char *remotehost, int remoteport, const char *sourcehost, int localport); LIBSSH_API int channel_open_session(ssh_channel channel); LIBSSH_API int channel_poll(ssh_channel channel, int is_stderr); LIBSSH_API int channel_read(ssh_channel channel, void *dest, uint32_t count, int is_stderr); LIBSSH_API int channel_read_buffer(ssh_channel channel, ssh_buffer buffer, uint32_t count, int is_stderr); LIBSSH_API int channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count, int is_stderr); LIBSSH_API int channel_request_env(ssh_channel channel, const char *name, const char *value); LIBSSH_API int channel_request_exec(ssh_channel channel, const char *cmd); LIBSSH_API int channel_request_pty(ssh_channel channel); LIBSSH_API int channel_request_pty_size(ssh_channel channel, const char *term, int cols, int rows); LIBSSH_API int channel_request_shell(ssh_channel channel); LIBSSH_API int channel_request_send_signal(ssh_channel channel, const char *signum); LIBSSH_API int channel_request_sftp(ssh_channel channel); LIBSSH_API int channel_request_subsystem(ssh_channel channel, const char *subsystem); LIBSSH_API int channel_request_x11(ssh_channel channel, int single_connection, const char *protocol, const char *cookie, int screen_number); LIBSSH_API int channel_send_eof(ssh_channel channel); LIBSSH_API int channel_select(ssh_channel *readchans, ssh_channel *writechans, ssh_channel *exceptchans, struct timeval * timeout); LIBSSH_API void channel_set_blocking(ssh_channel channel, int blocking); LIBSSH_API int channel_write(ssh_channel channel, const void *data, uint32_t len); LIBSSH_API void privatekey_free(ssh_private_key prv); LIBSSH_API ssh_private_key privatekey_from_file(ssh_session session, const char *filename, int type, const char *passphrase); LIBSSH_API void publickey_free(ssh_public_key key); LIBSSH_API int ssh_publickey_to_file(ssh_session session, const char *file, ssh_string pubkey, int type); LIBSSH_API ssh_string publickey_from_file(ssh_session session, const char *filename, int *type); LIBSSH_API ssh_public_key publickey_from_privatekey(ssh_private_key prv); LIBSSH_API ssh_string publickey_to_string(ssh_public_key key); LIBSSH_API int ssh_try_publickey_from_file(ssh_session session, const char *keyfile, ssh_string *publickey, int *type); LIBSSH_API int ssh_auth_list(ssh_session session); LIBSSH_API char *ssh_basename (const char *path); LIBSSH_API void ssh_clean_pubkey_hash(unsigned char **hash); LIBSSH_API int ssh_connect(ssh_session session); LIBSSH_API const char *ssh_copyright(void); LIBSSH_API void ssh_disconnect(ssh_session session); LIBSSH_API char *ssh_dirname (const char *path); LIBSSH_API int ssh_finalize(void); LIBSSH_API void ssh_free(ssh_session session); LIBSSH_API const char *ssh_get_disconnect_message(ssh_session session); LIBSSH_API const char *ssh_get_error(void *error); LIBSSH_API int ssh_get_error_code(void *error); LIBSSH_API socket_t ssh_get_fd(ssh_session session); LIBSSH_API char *ssh_get_hexa(const unsigned char *what, size_t len); LIBSSH_API char *ssh_get_issue_banner(ssh_session session); LIBSSH_API int ssh_get_openssh_version(ssh_session session); LIBSSH_API ssh_string ssh_get_pubkey(ssh_session session); LIBSSH_API int ssh_get_pubkey_hash(ssh_session session, unsigned char **hash); LIBSSH_API int ssh_get_random(void *where,int len,int strong); LIBSSH_API int ssh_get_version(ssh_session session); LIBSSH_API int ssh_get_status(ssh_session session); LIBSSH_API int ssh_init(void); LIBSSH_API int ssh_is_server_known(ssh_session session); LIBSSH_API void ssh_log(ssh_session session, int prioriry, const char *format, ...) PRINTF_ATTRIBUTE(3, 4); LIBSSH_API ssh_channel ssh_message_channel_request_open_reply_accept(ssh_message msg); LIBSSH_API int ssh_message_channel_request_reply_success(ssh_message msg); LIBSSH_API void ssh_message_free(ssh_message msg); LIBSSH_API ssh_message ssh_message_get(ssh_session session); LIBSSH_API ssh_message ssh_message_retrieve(ssh_session session, uint32_t packettype); LIBSSH_API int ssh_message_subtype(ssh_message msg); LIBSSH_API int ssh_message_type(ssh_message msg); LIBSSH_API int ssh_mkdir (const char *pathname, mode_t mode); LIBSSH_API ssh_session ssh_new(void); LIBSSH_API int ssh_options_copy(ssh_session src, ssh_session *dest); LIBSSH_API int ssh_options_getopt(ssh_session session, int *argcptr, char **argv); LIBSSH_API int ssh_options_parse_config(ssh_session session, const char *filename); LIBSSH_API int ssh_options_set(ssh_session session, enum ssh_options_e type, const void *value); LIBSSH_API int ssh_pcap_file_close(ssh_pcap_file pcap); LIBSSH_API void ssh_pcap_file_free(ssh_pcap_file pcap); LIBSSH_API ssh_pcap_file ssh_pcap_file_new(void); LIBSSH_API int ssh_pcap_file_open(ssh_pcap_file pcap, const char *filename); LIBSSH_API int ssh_privatekey_type(ssh_private_key privatekey); LIBSSH_API void ssh_print_hexa(const char *descr, const unsigned char *what, size_t len); LIBSSH_API int ssh_scp_accept_request(ssh_scp scp); LIBSSH_API int ssh_scp_close(ssh_scp scp); LIBSSH_API int ssh_scp_deny_request(ssh_scp scp, const char *reason); LIBSSH_API void ssh_scp_free(ssh_scp scp); LIBSSH_API int ssh_scp_init(ssh_scp scp); LIBSSH_API int ssh_scp_leave_directory(ssh_scp scp); LIBSSH_API ssh_scp ssh_scp_new(ssh_session session, int mode, const char *location); LIBSSH_API int ssh_scp_pull_request(ssh_scp scp); LIBSSH_API int ssh_scp_push_directory(ssh_scp scp, const char *dirname, int mode); LIBSSH_API int ssh_scp_push_file(ssh_scp scp, const char *filename, size_t size, int perms); LIBSSH_API int ssh_scp_read(ssh_scp scp, void *buffer, size_t size); LIBSSH_API const char *ssh_scp_request_get_filename(ssh_scp scp); LIBSSH_API int ssh_scp_request_get_permissions(ssh_scp scp); LIBSSH_API size_t ssh_scp_request_get_size(ssh_scp scp); LIBSSH_API const char *ssh_scp_request_get_warning(ssh_scp scp); LIBSSH_API int ssh_scp_write(ssh_scp scp, const void *buffer, size_t len); LIBSSH_API int ssh_select(ssh_channel *channels, ssh_channel *outchannels, socket_t maxfd, fd_set *readfds, struct timeval *timeout); LIBSSH_API int ssh_service_request(ssh_session session, const char *service); LIBSSH_API void ssh_set_blocking(ssh_session session, int blocking); LIBSSH_API void ssh_set_fd_except(ssh_session session); LIBSSH_API void ssh_set_fd_toread(ssh_session session); LIBSSH_API void ssh_set_fd_towrite(ssh_session session); LIBSSH_API void ssh_silent_disconnect(ssh_session session); LIBSSH_API int ssh_set_pcap_file(ssh_session session, ssh_pcap_file pcapfile); #ifndef _WIN32 LIBSSH_API int ssh_userauth_agent_pubkey(ssh_session session, const char *username, ssh_public_key publickey); #endif LIBSSH_API int ssh_userauth_autopubkey(ssh_session session, const char *passphrase); LIBSSH_API int ssh_userauth_kbdint(ssh_session session, const char *user, const char *submethods); LIBSSH_API const char *ssh_userauth_kbdint_getinstruction(ssh_session session); LIBSSH_API const char *ssh_userauth_kbdint_getname(ssh_session session); LIBSSH_API int ssh_userauth_kbdint_getnprompts(ssh_session session); LIBSSH_API const char *ssh_userauth_kbdint_getprompt(ssh_session session, unsigned int i, char *echo); LIBSSH_API int ssh_userauth_kbdint_setanswer(ssh_session session, unsigned int i, const char *answer); LIBSSH_API int ssh_userauth_list(ssh_session session, const char *username); LIBSSH_API int ssh_userauth_none(ssh_session session, const char *username); LIBSSH_API int ssh_userauth_offer_pubkey(ssh_session session, const char *username, int type, ssh_string publickey); LIBSSH_API int ssh_userauth_password(ssh_session session, const char *username, const char *password); LIBSSH_API int ssh_userauth_pubkey(ssh_session session, const char *username, ssh_string publickey, ssh_private_key privatekey); LIBSSH_API const char *ssh_version(int req_version); LIBSSH_API int ssh_write_knownhost(ssh_session session); LIBSSH_API void string_burn(ssh_string str); LIBSSH_API ssh_string string_copy(ssh_string str); LIBSSH_API void *string_data(ssh_string str); LIBSSH_API int string_fill(ssh_string str, const void *data, size_t len); LIBSSH_API void string_free(ssh_string str); LIBSSH_API ssh_string string_from_char(const char *what); LIBSSH_API size_t string_len(ssh_string str); LIBSSH_API ssh_string string_new(size_t size); LIBSSH_API char *string_to_char(ssh_string str); #ifdef __cplusplus } #endif #endif /* _LIBSSH_H */ /* vim: set ts=2 sw=2 et cindent: */
zzlydm-fbbs
include/libssh/libssh.h
C
gpl3
16,637
/* * This file is part of the SSH Library * * Copyright (c) 2003-2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ /* * priv.h file * This include file contains everything you shouldn't deal with in * user programs. Consider that anything in this file might change * without notice; libssh.h file will keep backward compatibility * on binary & source */ #ifndef _LIBSSH_PRIV_H #define _LIBSSH_PRIV_H #include "config.h" #ifdef _MSC_VER /** Imitate define of inttypes.h */ #define PRIdS "Id" #define strcasecmp _stricmp #define strncasecmp _strnicmp #define strtoull _strtoui64 #define isblank(ch) ((ch) == ' ' || (ch) == '\t' || (ch) == '\n' || (ch) == '\r') #if _MSC_VER >= 1400 #define strdup _strdup #endif #define usleep(X) Sleep(((X)+1000)/1000) #undef strtok_r #define strtok_r strtok_s #ifndef HAVE_SNPRINTF #ifdef HAVE__SNPRINTF_S #define snprintf(d, n, ...) _snprintf_s((d), (n), _TRUNCATE, __VA_ARGS__) #else #ifdef HAVE__SNPRINTF #define snprintf _snprintf #else #error "no snprintf compatible function found" #endif /* HAVE__SNPRINTF */ #endif /* HAVE__SNPRINTF_S */ #endif /* HAVE_SNPRINTF */ #ifndef HAVE_VSNPRINTF #ifdef HAVE__VSNPRINTF_S #define vsnprintf(s, n, f, v) _vsnprintf_s((s), (n), _TRUNCATE, (f), (v)) #else #ifdef HAVE__VSNPRINTF #define vsnprintf _vsnprintf #else /* HAVE_VSNPRINTF */ #error "No vsnprintf compatible function found" #endif /* HAVE__VSNPRINTF */ #endif /* HAVE__VSNPRINTF_S */ #endif /* HAVE_VSNPRINTF */ #ifndef HAVE_STRNCPY #define strncpy(d, s, n) strncpy_s((d), (n), (s), _TRUNCATE) #endif #else /* _MSC_VER */ #include <unistd.h> #define PRIdS "zd" #endif /* _MSC_VER */ #include "libssh/libssh.h" #include "libssh/callbacks.h" #include "libssh/crypto.h" /* some constants */ #define MAX_PACKET_LEN 262144 #define ERROR_BUFFERLEN 1024 #define CLIENTBANNER1 "SSH-1.5-libssh-" SSH_STRINGIFY(LIBSSH_VERSION) #define CLIENTBANNER2 "SSH-2.0-libssh-" SSH_STRINGIFY(LIBSSH_VERSION) #define KBDINT_MAX_PROMPT 256 /* more than openssh's :) */ /* some types for public keys */ enum public_key_types_e{ TYPE_DSS=1, TYPE_RSA, TYPE_RSA1 }; #ifdef __cplusplus extern "C" { #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif typedef struct kex_struct { unsigned char cookie[16]; char **methods; } KEX; struct error_struct { /* error handling */ unsigned int error_code; char error_buffer[ERROR_BUFFERLEN]; }; /* TODO: remove that include */ #include "libssh/wrapper.h" struct ssh_keys_struct { const char *privatekey; const char *publickey; }; struct ssh_message_struct; /* server data */ struct ssh_bind_struct { struct error_struct error; ssh_callbacks callbacks; /* Callbacks to user functions */ /* options */ char *wanted_methods[10]; char *banner; char *dsakey; char *rsakey; char *bindaddr; socket_t bindfd; unsigned int bindport; unsigned int log_verbosity; int blocking; int toaccept; }; /* client.c */ int ssh_send_banner(ssh_session session, int is_server); char *ssh_get_banner(ssh_session session); /* config.c */ int ssh_config_parse_file(ssh_session session, const char *filename); /* errors.c */ void ssh_set_error(void *error, int code, const char *descr, ...) PRINTF_ATTRIBUTE(3, 4); void ssh_set_error_oom(void *); void ssh_set_error_invalid(void *, const char *); /* in crypt.c */ uint32_t packet_decrypt_len(ssh_session session,char *crypted); int packet_decrypt(ssh_session session, void *packet,unsigned int len); unsigned char *packet_encrypt(ssh_session session,void *packet,unsigned int len); /* it returns the hmac buffer if exists*/ int packet_hmac_verify(ssh_session session,ssh_buffer buffer,unsigned char *mac); /* connect.c */ int ssh_regex_init(void); void ssh_regex_finalize(void); ssh_session ssh_session_new(void); socket_t ssh_connect_host(ssh_session session, const char *host,const char *bind_addr, int port, long timeout, long usec); /* in kex.c */ extern const char *ssh_kex_nums[]; int ssh_send_kex(ssh_session session, int server_kex); void ssh_list_kex(ssh_session session, KEX *kex); int set_kex(ssh_session session); int ssh_get_kex(ssh_session session, int server_kex); int verify_existing_algo(int algo, const char *name); char **space_tokenize(const char *chain); int ssh_get_kex1(ssh_session session); char *ssh_find_matching(const char *in_d, const char *what_d); /* in base64.c */ ssh_buffer base64_to_bin(const char *source); unsigned char *bin_to_base64(const unsigned char *source, int len); /* gzip.c */ int compress_buffer(ssh_session session,ssh_buffer buf); int decompress_buffer(ssh_session session,ssh_buffer buf, size_t maxlen); /* crc32.c */ uint32_t ssh_crc32(const char *buf, uint32_t len); /* auth1.c */ int ssh_userauth1_none(ssh_session session, const char *username); int ssh_userauth1_offer_pubkey(ssh_session session, const char *username, int type, ssh_string pubkey); int ssh_userauth1_password(ssh_session session, const char *username, const char *password); /* channels1.c */ int channel_open_session1(ssh_channel channel); int channel_request_pty_size1(ssh_channel channel, const char *terminal, int cols, int rows); int channel_change_pty_size1(ssh_channel channel, int cols, int rows); int channel_request_shell1(ssh_channel channel); int channel_request_exec1(ssh_channel channel, const char *cmd); int channel_handle1(ssh_session session, int type); int channel_write1(ssh_channel channel, const void *data, int len); /* match.c */ int match_hostname(const char *host, const char *pattern, unsigned int len); /* log.c */ /* misc.c */ #ifdef _WIN32 int gettimeofday(struct timeval *__p, void *__t); #endif /* _WIN32 */ #ifndef __FUNCTION__ #if defined(__SUNPRO_C) #define __FUNCTION__ __func__ #endif #endif #define _enter_function(sess) \ do {\ if((sess)->log_verbosity >= SSH_LOG_FUNCTIONS){ \ ssh_log((sess),SSH_LOG_FUNCTIONS,"entering function %s line %d in " __FILE__ , __FUNCTION__,__LINE__);\ (sess)->log_indent++; \ } \ } while(0) #define _leave_function(sess) \ do { \ if((sess)->log_verbosity >= SSH_LOG_FUNCTIONS){ \ (sess)->log_indent--; \ ssh_log((sess),SSH_LOG_FUNCTIONS,"leaving function %s line %d in " __FILE__ , __FUNCTION__,__LINE__);\ }\ } while(0) #ifdef DEBUG_CALLTRACE #define enter_function() _enter_function(session) #define leave_function() _leave_function(session) #else #define enter_function() (void)session #define leave_function() (void)session #endif /* options.c */ int ssh_options_set_algo(ssh_session session, int algo, const char *list); int ssh_options_apply(ssh_session session); /** Free memory space */ #define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0) /** Zero a structure */ #define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x)) /** Zero a structure given a pointer to the structure */ #define ZERO_STRUCTP(x) do { if ((x) != NULL) memset((char *)(x), 0, sizeof(*(x))); } while(0) /** Get the size of an array */ #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) /** Overwrite the complete string with 'X' */ #define BURN_STRING(x) do { if ((x) != NULL) memset((x), 'X', strlen((x))); } while(0) #ifdef HAVE_LIBGCRYPT /* gcrypt_missing.c */ int my_gcry_dec2bn(bignum *bn, const char *data); char *my_gcry_bn2dec(bignum bn); #endif /* !HAVE_LIBGCRYPT */ #ifdef __cplusplus } #endif #endif /* _LIBSSH_PRIV_H */ /* vim: set ts=2 sw=2 et cindent: */
zzlydm-fbbs
include/libssh/priv.h
C
gpl3
8,154
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef KEYFILES_H_ #define KEYFILES_H_ /* in keyfiles.c */ ssh_private_key _privatekey_from_file(void *session, const char *filename, int type); ssh_string try_publickey_from_file(ssh_session session, struct ssh_keys_struct keytab, char **privkeyfile, int *type); #endif /* KEYFILES_H_ */
zzlydm-fbbs
include/libssh/keyfiles.h
C
gpl3
1,174
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef KEYS_H_ #define KEYS_H_ #include "config.h" #include "libssh/libssh.h" #include "libssh/wrapper.h" struct ssh_public_key_struct { int type; const char *type_c; /* Don't free it ! it is static */ #ifdef HAVE_LIBGCRYPT gcry_sexp_t dsa_pub; gcry_sexp_t rsa_pub; #elif HAVE_LIBCRYPTO DSA *dsa_pub; RSA *rsa_pub; #endif }; struct ssh_private_key_struct { int type; #ifdef HAVE_LIBGCRYPT gcry_sexp_t dsa_priv; gcry_sexp_t rsa_priv; #elif defined HAVE_LIBCRYPTO DSA *dsa_priv; RSA *rsa_priv; #endif }; typedef struct signature_struct { int type; #ifdef HAVE_LIBGCRYPT gcry_sexp_t dsa_sign; gcry_sexp_t rsa_sign; #elif defined HAVE_LIBCRYPTO DSA_SIG *dsa_sign; ssh_string rsa_sign; #endif } SIGNATURE; const char *ssh_type_to_char(int type); int ssh_type_from_name(const char *name); ssh_buffer ssh_userauth_build_digest(ssh_session session, ssh_message msg, char *service); ssh_private_key privatekey_make_dss(ssh_session session, ssh_buffer buffer); ssh_private_key privatekey_make_rsa(ssh_session session, ssh_buffer buffer, const char *type); ssh_private_key privatekey_from_string(ssh_session session, ssh_string privkey_s); ssh_public_key publickey_make_dss(ssh_session session, ssh_buffer buffer); ssh_public_key publickey_make_rsa(ssh_session session, ssh_buffer buffer, int type); ssh_public_key publickey_from_string(ssh_session session, ssh_string pubkey_s); SIGNATURE *signature_from_string(ssh_session session, ssh_string signature,ssh_public_key pubkey,int needed_type); void signature_free(SIGNATURE *sign); ssh_string ssh_do_sign_with_agent(struct ssh_session_struct *session, struct ssh_buffer_struct *buf, struct ssh_public_key_struct *publickey); ssh_string ssh_do_sign(ssh_session session,ssh_buffer sigbuf, ssh_private_key privatekey); ssh_string ssh_sign_session_id(ssh_session session, ssh_private_key privatekey); ssh_string ssh_encrypt_rsa1(ssh_session session, ssh_string data, ssh_public_key key); #endif /* KEYS_H_ */
zzlydm-fbbs
include/libssh/keys.h
C
gpl3
2,903
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef PACKET_H_ #define PACKET_H_ /* this structure should go someday */ typedef struct packet_struct { int valid; uint32_t len; uint8_t type; } PACKET; void packet_parse(ssh_session session); int packet_send(ssh_session session); int packet_read(ssh_session session); int packet_translate(ssh_session session); int packet_wait(ssh_session session,int type,int blocking); int packet_flush(ssh_session session, int enforce_blocking); #endif /* PACKET_H_ */
zzlydm-fbbs
include/libssh/packet.h
C
gpl3
1,335
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef MISC_H_ #define MISC_H_ /* in misc.c */ /* gets the user home dir. */ char *ssh_get_user_home_dir(void); char *ssh_get_local_username(ssh_session session); int ssh_file_readaccess_ok(const char *file); char *ssh_path_expand_tilde(const char *d); char *ssh_path_expand_escape(ssh_session session, const char *s); /* macro for byte ordering */ uint64_t ntohll(uint64_t); #define htonll(x) ntohll(x) /* list processing */ struct ssh_list { struct ssh_iterator *root; struct ssh_iterator *end; }; struct ssh_iterator { struct ssh_iterator *next; const void *data; }; struct ssh_list *ssh_list_new(void); void ssh_list_free(struct ssh_list *list); struct ssh_iterator *ssh_list_get_iterator(const struct ssh_list *list); int ssh_list_append(struct ssh_list *list, const void *data); int ssh_list_prepend(struct ssh_list *list, const void *data); void ssh_list_remove(struct ssh_list *list, struct ssh_iterator *iterator); char *ssh_hostport(const char *host, int port); const void *_ssh_list_pop_head(struct ssh_list *list); #define ssh_iterator_value(type, iterator)\ ((type)((iterator)->data)) /** @brief fetch the head element of a list and remove it from list * @param type type of the element to return * @param list the ssh_list to use * @return the first element of the list, or NULL if the list is empty */ #define ssh_list_pop_head(type, ssh_list)\ ((type)_ssh_list_pop_head(ssh_list)) #endif /* MISC_H_ */
zzlydm-fbbs
include/libssh/misc.h
C
gpl3
2,315
/* * This file is part of the SSH Library * * Copyright (c) 2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef WRAPPER_H_ #define WRAPPER_H_ #include "config.h" #ifdef MD5_DIGEST_LEN #undef MD5_DIGEST_LEN #endif /* wrapper things */ #ifdef HAVE_LIBGCRYPT #include <gcrypt.h> typedef gcry_md_hd_t SHACTX; typedef gcry_md_hd_t MD5CTX; typedef gcry_md_hd_t HMACCTX; #define SHA_DIGEST_LEN 20 #define MD5_DIGEST_LEN 16 #define EVP_MAX_MD_SIZE 36 typedef gcry_mpi_t bignum; #define bignum_new() gcry_mpi_new(0) #define bignum_free(num) gcry_mpi_release(num) #define bignum_set_word(bn,n) gcry_mpi_set_ui(bn,n) #define bignum_bin2bn(bn,datalen,data) gcry_mpi_scan(data,GCRYMPI_FMT_USG,bn,datalen,NULL) #define bignum_bn2dec(num) my_gcry_bn2dec(num) #define bignum_dec2bn(num, data) my_gcry_dec2bn(data, num) #define bignum_bn2hex(num,data) gcry_mpi_aprint(GCRYMPI_FMT_HEX,data,NULL,num) #define bignum_hex2bn(num,datalen,data) gcry_mpi_scan(num,GCRYMPI_FMT_HEX,data,datalen,NULL) #define bignum_rand(num,bits) gcry_mpi_randomize(num,bits,GCRY_STRONG_RANDOM),gcry_mpi_set_bit(num,bits-1),gcry_mpi_set_bit(num,0) #define bignum_mod_exp(dest,generator,exp,modulo) gcry_mpi_powm(dest,generator,exp,modulo) #define bignum_num_bits(num) gcry_mpi_get_nbits(num) #define bignum_num_bytes(num) ((gcry_mpi_get_nbits(num)+7)/8) #define bignum_is_bit_set(num,bit) gcry_mpi_test_bit(num,bit) #define bignum_bn2bin(num,datalen,data) gcry_mpi_print(GCRYMPI_FMT_USG,data,datalen,NULL,num) #define bignum_cmp(num1,num2) gcry_mpi_cmp(num1,num2) #elif defined HAVE_LIBCRYPTO #include <openssl/dsa.h> #include <openssl/rsa.h> #include <openssl/sha.h> #include <openssl/md5.h> #include <openssl/hmac.h> typedef SHA_CTX* SHACTX; typedef MD5_CTX* MD5CTX; typedef HMAC_CTX* HMACCTX; #define SHA_DIGEST_LEN SHA_DIGEST_LENGTH #define MD5_DIGEST_LEN MD5_DIGEST_LENGTH #include <openssl/bn.h> #include <openssl/opensslv.h> #define OPENSSL_0_9_7b 0x0090702fL #if (OPENSSL_VERSION_NUMBER <= OPENSSL_0_9_7b) #define BROKEN_AES_CTR #endif typedef BIGNUM* bignum; typedef BN_CTX* bignum_CTX; #define bignum_new() BN_new() #define bignum_free(num) BN_clear_free(num) #define bignum_set_word(bn,n) BN_set_word(bn,n) #define bignum_bin2bn(bn,datalen,data) BN_bin2bn(bn,datalen,data) #define bignum_bn2dec(num) BN_bn2dec(num) #define bignum_dec2bn(bn,data) BN_dec2bn(data,bn) #define bignum_bn2hex(num) BN_bn2hex(num) #define bignum_rand(rnd, bits, top, bottom) BN_rand(rnd,bits,top,bottom) #define bignum_ctx_new() BN_CTX_new() #define bignum_ctx_free(num) BN_CTX_free(num) #define bignum_mod_exp(dest,generator,exp,modulo,ctx) BN_mod_exp(dest,generator,exp,modulo,ctx) #define bignum_num_bytes(num) BN_num_bytes(num) #define bignum_num_bits(num) BN_num_bits(num) #define bignum_is_bit_set(num,bit) BN_is_bit_set(num,bit) #define bignum_bn2bin(num,ptr) BN_bn2bin(num,ptr) #define bignum_cmp(num1,num2) BN_cmp(num1,num2) #endif /* OPENSSL_CRYPTO */ MD5CTX md5_init(void); void md5_update(MD5CTX c, const void *data, unsigned long len); void md5_final(unsigned char *md,MD5CTX c); SHACTX sha1_init(void); void sha1_update(SHACTX c, const void *data, unsigned long len); void sha1_final(unsigned char *md,SHACTX c); void sha1(unsigned char *digest,int len,unsigned char *hash); #define HMAC_SHA1 1 #define HMAC_MD5 2 HMACCTX hmac_init(const void *key,int len,int type); void hmac_update(HMACCTX c, const void *data, unsigned long len); void hmac_final(HMACCTX ctx,unsigned char *hashmacbuf,unsigned int *len); int crypt_set_algorithms(ssh_session ); int crypt_set_algorithms_server(ssh_session session); struct ssh_crypto_struct *crypto_new(void); void crypto_free(struct ssh_crypto_struct *crypto); #endif /* WRAPPER_H_ */
zzlydm-fbbs
include/libssh/wrapper.h
C
gpl3
4,465
#ifndef PCAP_H_ #define PCAP_H_ #include "config.h" #include "libssh/libssh.h" #ifdef WITH_PCAP typedef struct ssh_pcap_context_struct* ssh_pcap_context; int ssh_pcap_file_write_packet(ssh_pcap_file pcap, ssh_buffer packet, uint32_t original_len); ssh_pcap_context ssh_pcap_context_new(ssh_session session); void ssh_pcap_context_free(ssh_pcap_context ctx); enum ssh_pcap_direction{ SSH_PCAP_DIR_IN, SSH_PCAP_DIR_OUT }; void ssh_pcap_context_set_file(ssh_pcap_context, ssh_pcap_file); int ssh_pcap_context_write(ssh_pcap_context,enum ssh_pcap_direction direction, void *data, uint32_t len, uint32_t origlen); #endif /* WITH_PCAP */ #endif /* PCAP_H_ */ /* vim: set ts=2 sw=2 et cindent: */
zzlydm-fbbs
include/libssh/pcap.h
C
gpl3
701
/* * This file is part of the SSH Library * * Copyright (c) 2003-2009 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef _SCP_H #define _SCP_H enum ssh_scp_states { SSH_SCP_NEW, //Data structure just created SSH_SCP_WRITE_INITED, //Gave our intention to write SSH_SCP_WRITE_WRITING,//File was opened and currently writing SSH_SCP_READ_INITED, //Gave our intention to read SSH_SCP_READ_REQUESTED, //We got a read request SSH_SCP_READ_READING, //File is opened and reading SSH_SCP_ERROR, //Something bad happened SSH_SCP_TERMINATED //Transfer finished }; struct ssh_scp_struct { ssh_session session; int mode; int recursive; ssh_channel channel; char *location; enum ssh_scp_states state; size_t filelen; size_t processed; enum ssh_scp_request_types request_type; char *request_name; char *warning; int request_mode; }; int ssh_scp_read_string(ssh_scp scp, char *buffer, size_t len); int ssh_scp_integer_mode(const char *mode); char *ssh_scp_string_mode(int mode); int ssh_scp_response(ssh_scp scp, char **response); #endif
zzlydm-fbbs
include/libssh/scp.h
C
gpl3
1,845
#ifndef __SSH2_H #define __SSH2_H #define SSH2_MSG_DISCONNECT 1 #define SSH2_MSG_IGNORE 2 #define SSH2_MSG_UNIMPLEMENTED 3 #define SSH2_MSG_DEBUG 4 #define SSH2_MSG_SERVICE_REQUEST 5 #define SSH2_MSG_SERVICE_ACCEPT 6 #define SSH2_MSG_KEXINIT 20 #define SSH2_MSG_NEWKEYS 21 #define SSH2_MSG_KEXDH_INIT 30 #define SSH2_MSG_KEXDH_REPLY 31 #define SSH2_MSG_KEX_DH_GEX_REQUEST_OLD 30 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 #define SSH2_MSG_KEX_DH_GEX_INIT 32 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 #define SSH2_MSG_KEX_DH_GEX_REQUEST 34 #define SSH2_MSG_USERAUTH_REQUEST 50 #define SSH2_MSG_USERAUTH_FAILURE 51 #define SSH2_MSG_USERAUTH_SUCCESS 52 #define SSH2_MSG_USERAUTH_BANNER 53 #define SSH2_MSG_USERAUTH_PK_OK 60 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 #define SSH2_MSG_GLOBAL_REQUEST 80 #define SSH2_MSG_REQUEST_SUCCESS 81 #define SSH2_MSG_REQUEST_FAILURE 82 #define SSH2_MSG_CHANNEL_OPEN 90 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 #define SSH2_MSG_CHANNEL_DATA 94 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 #define SSH2_MSG_CHANNEL_EOF 96 #define SSH2_MSG_CHANNEL_CLOSE 97 #define SSH2_MSG_CHANNEL_REQUEST 98 #define SSH2_MSG_CHANNEL_SUCCESS 99 #define SSH2_MSG_CHANNEL_FAILURE 100 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 #define SSH2_DISCONNECT_RESERVED 4 #define SSH2_DISCONNECT_MAC_ERROR 5 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 #define SSH2_DISCONNECT_CONNECTION_LOST 10 #define SSH2_DISCONNECT_BY_APPLICATION 11 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 #define SSH2_OPEN_CONNECT_FAILED 2 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 #define SSH2_EXTENDED_DATA_STDERR 1 #endif
zzlydm-fbbs
include/libssh/ssh2.h
C
gpl3
2,336
#!/bin/sh xgettext -k_ -d fbbs -s -o fbbs.pot ../src/*.c
zzlydm-fbbs
i18n/extract.sh
Shell
gpl3
58
#!/bin/sh msgmerge -s -U fbbs.po fbbs.pot
zzlydm-fbbs
i18n/update.sh
Shell
gpl3
43
#include "fbbs/dbi.h" #include "fbbs/post.h" #include "fbbs/time.h" #include "fbbs/web.h" enum { QUERY_LENGTH = 512, }; bool allow_reply(uint_t flag) { return !(flag & FILE_NOREPLY); } int get_post_mark(uint_t flag) { int mark = ' '; if (flag & FILE_DIGEST) mark = 'G'; if (flag & FILE_MARKED) { if (mark == ' ') mark = 'M'; else mark = 'B'; } if ((flag & FILE_WATER) && mark == ' ') mark = 'W'; return mark; } int bbs_board(web_ctx_t *ctx) { const char *bid = get_param(ctx->r, "bid"); const char *action = get_param(ctx->r, "a"); const char *pid = get_param(ctx->r, "pid"); bool asc = (*action == 'n'); bool act = (*action == 'n' || *action == 'p'); char *query = pool_alloc(ctx->p, QUERY_LENGTH); int len = snprintf(query, QUERY_LENGTH, "SELECT u.name, p.flag, p.time, p.user_name, p.id, p.title " "FROM posts p LEFT JOIN users u ON p.user_id = u.id " "WHERE p.board_id = $1 AND itype = 0 %s " "ORDER BY p.id %s LIMIT 20", asc ? "AND p.id > $2" : (*action == 'p' ? "AND p.id < $2" : ""), asc ? "ASC" : "DESC"); if (len >= QUERY_LENGTH) return -1; db_param_t param[] = { PARAM_TEXT(bid), PARAM_TEXT(pid) }; db_res_t *res = db_exec_params(ctx->d, query, act ? 2 : 1, param, true); if (db_res_status(res) != DBRES_TUPLES_OK) { db_clear(res); return -1; } xml_header(NULL); printf("<bbs_board>"); int rows = db_num_rows(res); long begin = 0, end = 0; if (rows > 0) { int e = asc ? rows : -1; int step = asc ? 1 : -1; for (int i = asc ? 0 : rows - 1; i != e; i += step) { uint_t flag = db_get_integer(res, i, 1); printf("<po %sm='%c' o='%s' t='%s' id='%ld'>", allow_reply(flag) ? "" : "nore='1' ", get_post_mark(flag), db_get_value(res, i, 3), date2str(db_get_time(res, i, 2), DATE_XML), db_get_bigint(res, i, 4)); xml_print(db_get_value(res, i, 5)); printf("</po>\n"); } begin = db_get_bigint(res, asc ? 0 : rows - 1, 4); end = db_get_bigint(res, asc ? rows - 1 : 0, 4); } db_clear(res); const char *q = "SELECT id, name, description FROM boards WHERE id = $1"; res = db_exec_params(ctx->d, q, 1, param, true); if (db_res_status(res) != DBRES_TUPLES_OK) { db_clear(res); return -1; } printf("<brd bid='%d' name='%s' desc='%s' begin='%ld' end='%ld'/>", db_get_integer(res, 0, 0), db_get_value(res, 0, 1), db_get_value(res, 0, 2), begin, end); printf("</bbs_board>"); db_clear(res); return 0; }
zzlydm-fbbs
www/board.c
C
gpl3
2,442
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic -Werror") add_definitions(-D_XOPEN_SOURCE=600) add_executable(fbwebd web.c main.c board.c parse.c post.c) target_link_libraries(fbwebd crypt fcgi fbbs fbbspg) install(TARGETS fbwebd RUNTIME DESTINATION bin)
zzlydm-fbbs
www/CMakeLists.txt
CMake
gpl3
265
#include <stdlib.h> #include <string.h> #include <unistd.h> #include "fbbs/pool.h" #include "fbbs/string.h" #include "fbbs/web.h" extern int bbs_board(web_ctx_t *ctx); extern int bbs_post(web_ctx_t *ctx); typedef struct web_handler_t { const char *name; ///< name of the handler. int (*func)(web_ctx_t *); ///< handler function. } web_handler_t; int fcgi_foo(web_ctx_t *ctx) { html_header(); printf("</head><body><p>Hello, world!</p>" "<p>Your IP addr is: %s</p></body></html>", ctx->r->from); return 0; } static const web_handler_t _handlers[] = { { "board", bbs_board }, { "foo", fcgi_foo }, { "post", bbs_post }, { NULL, NULL } }; static const web_handler_t *_get_handler(void) { char *url = getenv("SCRIPT_NAME"); if (!url) return NULL; char *name = strrchr(url, '/'); if (!name) name = url; else ++name; const web_handler_t *h = _handlers; while (h->name) { if (streq(name, h->name)) return h; ++h; } return NULL; } /** * The main entrance of bbswebd. * @return 0 on success, 1 on initialization error. */ int main(void) { config_t cfg; config_init(&cfg); if (config_load(&cfg, DEFAULT_CFG_FILE) != 0) return EXIT_FAILURE; db_conn_t *conn = db_connect(config_get(&cfg, "host"), config_get(&cfg, "port"), config_get(&cfg, "dbname"), config_get(&cfg, "user"), config_get(&cfg, "password")); if (db_status(conn) != DB_CONNECTION_OK) return EXIT_FAILURE; if (chdir(config_get(&cfg, "root")) < 0) return EXIT_FAILURE; while (FCGI_Accept() >= 0) { pool_t *p = pool_create(DEFAULT_POOL_SIZE); http_req_t *r = get_request(p); if (!r) return EXIT_FAILURE; web_ctx_t ctx = { .c = &cfg, .d = conn, .p = p, .r = r }; int ret; const web_handler_t *h = _get_handler(); if (!h) { ; } else { ret = (*(h->func))(&ctx); } pool_destroy(p); } return 0; }
zzlydm-fbbs
www/main.c
C
gpl3
1,861
#include <ctype.h> #include <stdlib.h> #include <string.h> #include "fbbs/error.h" #include "fbbs/pool.h" #include "fbbs/string.h" #include "fbbs/web.h" /** * Get an environment variable. * The function searches environment list where FastCGI stores parameters * for a string that matches the string pointed by 'key'. The strings are * of the form key=value. * @param key The key. * @return a pointer to the value in the environment, or empty string if * there is no match */ static const char *_get_server_env(const char *key) { char *s = getenv(key); if (s) return s; return ""; } /** * Get decimal value of a hex char 'c' * @param c The hexadecimal character. * @return Converted decimal value, 0 on error. */ static int _hex2dec(int c) { c = toupper(c); switch (c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': return 10; case 'B': return 11; case 'C': return 12; case 'D': return 13; case 'E': return 14; case 'F': return 15; default: return 0; } } /** * Decode an url string. * @param s The string to be decoded. * @return The converted string. */ static char *_url_decode(char *s) { int m, n; for (m = 0, n = 0; s[m]; ++m, ++n) { if (s[m] == '+') { s[n] = ' '; } else if (s[m] == '%') { if (s[m + 1] && s[m + 2]) { s[n] = _hex2dec(s[m + 1]) * 16 + _hex2dec(s[m + 2]); m += 2; continue; } else { s[n] = '\0'; return s; } } else { s[n] = s[m]; } } s[n] = '\0'; return s; } /** * Parse a 'key=value' pair and put it into request struct. * @param r The http request. * @param begin The string. * @param len Length of the string. * @return 0 on success, ::FB_FATAL on error. */ static int _parse_param(http_req_t *r, const char *begin, size_t len) { if (len == 0) return 0; char *s = pool_alloc(r->p, len + 1); if (!s) return FB_FATAL; strlcpy(s, begin, len + 1); s[len] = '\0'; char *key = s, *val = strchr(s, '='); if (val) { *val++ = '\0'; _url_decode(val); } else { val = ""; } r->params[r->count].key = key; r->params[r->count].val = val; ++r->count; return 0; } /** * Parse 'key=value' pairs and put them into request struct. * @param r The http request. * @param key The name in the environment. * @param delim The delimiter. * @return 0 on success, ::FB_FATAL on error. */ static int _parse_params(http_req_t *r, const char *key, int delim) { const char *env = _get_server_env(key); const char *ptr = strchr(env, delim), *last = env; while (ptr) { if (_parse_param(r, last, ptr - last) != 0) return FB_FATAL; last = ptr + 1; ptr = strchr(last, delim); } if (_parse_param(r, last, strlen(last)) < 0) return FB_FATAL; return 0; } /** * Parse GET parameters and cookies. * @param r The http request. * @return 0 on success, FB_FATAL on error. */ static int _parse_http_req(http_req_t *r) { if (_parse_params(r, "QUERY_STRING", '&') < 0) return FB_FATAL; if (_parse_params(r, "HTTP_COOKIE", ';') < 0) return FB_FATAL; return 0; } /** * Get an http request. * The GET request and cookies are parsed into key=value pairs. * @param p A memory pool to use. * @return A parsed http request struct, NULL on error. */ http_req_t *get_request(pool_t *p) { http_req_t *r = pool_alloc(p, sizeof(*r)); if (!r) return NULL; r->p = p; r->count = 0; if (_parse_http_req(r) != 0) return NULL; const char *from = _get_server_env("REMOTE_ADDR"); size_t len = strlen(from) + 1; r->from = pool_alloc(p, len); if (!r->from) return NULL; strlcpy(r->from, from, len); return r; } /** * Get a parameter value. * @param r The http request. * @param key The name of the parameter. * @return the value corresponding to 'key', an empty string if not found. */ const char *get_param(http_req_t *r, const char *key) { for (int i = 0; i < r->count; ++i) { if (streq(r->params[i].key, key)) return r->params[i].val; } return ""; } /** * Parse parameters submitted by POST method. * @return 0 on success, -1 on error. */ int parse_post_data(http_req_t *r) { unsigned long size = strtoul(_get_server_env("CONTENT_LENGTH"), NULL, 10); if (size == 0) return 0; else if (size > MAX_CONTENT_LENGTH) size = MAX_CONTENT_LENGTH; char *buf = pool_alloc(r->p, size + 1); if (!buf) return -1; if (fread(buf, size, 1, stdin) != 1) return -1; buf[size] = '\0'; _parse_params(r, buf, '&'); return 0; } /** * Print HTML response header. */ void html_header(void) { printf("Content-type: text/html; charset="CHARSET"\n\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " "\"http://www.w3.org/TR/html4/strict.dtd\"><html><head>"); } /** * Print XML response header. * @param xslfile The name of the XSLT file. */ void xml_header(const char *xslfile) { const char *xsl = xslfile ? xslfile : "bbs"; printf("Content-type: text/xml; charset="CHARSET"\n\n" "<?xml version=\"1.0\" encoding=\""CHARSET"\"?>\n" "<?xml-stylesheet type=\"text/xsl\" href=\"../xsl/%s.xsl\"?>\n", xsl); } void print_session(void) { return; } void xml_print(const char *s) { char *c = (char *)s; char *last = c; char *subst; while (*c != '\0') { switch (*c) { case '<': subst = "&lt;"; break; case '>': subst = "&gt;"; break; case '&': subst = "&amp;"; break; case '\033': case '\r': subst = ""; break; default: subst = NULL; break; } if (subst) { fwrite(last, 1, c - last, stdout); fputs(subst, stdout); last = ++c; } else { ++c; } } fwrite(last, 1, c - last, stdout); }
zzlydm-fbbs
www/web.c
C
gpl3
5,728
#include <stdlib.h> #include "fbbs/web.h" int bbs_post(web_ctx_t *ctx) { const char *idstr = get_param(ctx->r, "id"); long id = strtol(idstr, NULL, 10); char file[128]; snprintf(file, sizeof(file), "posts/%ld/%ld", id / 10000, id); const char *query = "SELECT board_id, gid FROM posts WHERE id = $1"; db_param_t params[] = { PARAM_TEXT(idstr) }; db_res_t *res = db_exec_params(ctx->d, query, 1, params, true); if (db_res_status(res) != DBRES_TUPLES_OK || db_num_rows(res) <= 0) { db_clear(res); return -1; } xml_header(NULL); printf("<bbs_post bid='%d' gid='%ld'>", db_get_integer(res, 0, 0), db_get_bigint(res, 0, 1)); printf("<post id='%ld'>", id); xml_print_post(file, true); printf("</post>"); printf("</bbs_post>"); db_clear(res); return 0; }
zzlydm-fbbs
www/post.c
C
gpl3
783
function switchPanel(link) { var item = link.nextSibling; var expand = false; if (item.style.display == 'block') { item.style.display = 'none'; } else { item.style.display = 'block'; expand = true; } var id = link.parentNode.id; bbs.store.get('navbar', function(ok, val) { var str = '0000000'; if (ok && val && val.toString().length == 7) str = val.toString(); for (var i = 0; i < bbs.navbar.length; ++i) { if (bbs.navbar[i] == id) str = str.substring(0, i) + (expand ? 1 : 0) + str.substring(i + 1); } bbs.store.set('navbar', str); }); return false; } // for bbspst function preUpload() { var mywin = window.open('preupload?board=' + document.getElementById('brd').value, '_blank', 'width=600,height=300,scrollbars=yes'); if ((document.window != null) && (!mywin.opener)) mywin.opener = document.window; mywin.focus(); return false; } document.onkeydown = function(evt) { document.onkeypress = function() {return true;}; if (!document.getElementById('postform')) return true; evt = evt ? evt : event; if ((evt.keyCode == 87) && evt.ctrlKey) { // Ctrl-W document.onkeypress = function() {return false;}; document.postform.submit(); return false; } }; // for bbsmail function checkAll() { var inputs = document.getElementsByName('list')[0].getElementsByTagName('input'); for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == 'checkbox') { inputs[i].checked = true; } } return false; } function checkReverse() { var inputs = document.getElementsByName('list')[0].getElementsByTagName('input'); for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == 'checkbox') inputs[i].checked = !(inputs[i].checked); } return false; } function delSelected() { document.list.mode.value = 1; document.list.submit(); } function addLoadEvent(func) { if (typeof window.onload != 'function') { window.onload = func; } else { var old = window.onload; window.onload = function() { old(); func(); } } } function ie6fix() { var nav = document.getElementById('nav'); nav.style.height = document.documentElement.clientHeight - 10; var width = document.documentElement.clientWidth - 150; document.getElementById('hd').style.width = width; var div = document.getElementsByTagName('table'); for (var i = 0; i < div.length; ++i) { if (div[i].className == 'content') div[i].style.width = width; } div = document.getElementsByTagName('div'); for (var i = 0; i < div.length; ++i) { if (div[i].className == 'post') div[i].style.width = width; } } var HTTP = { _factories: [ function() { return new XMLHttpRequest(); }, function() { return new ActiveXObject("Msxml2.XMLHTTP"); }, function() { return new ActiveXObject("Microsoft.XMLHTTP"); } ], _factory: null, newRequest: function() { if (HTTP._factory != null) return HTTP._factory(); for(var i = 0; i < HTTP._factories.length; i++) { try { var factory = HTTP._factories[i]; var request = factory(); if (request != null) { HTTP._factory = factory; return request; } } catch(e) { continue; } } HTTP._factory = function() { throw new Error("XMLHttpRequest not supported"); } HTTP._factory(); } }; var bbs = { inited: false, interval: 300000, root: window.location.href.substring(0, window.location.href.lastIndexOf("/")), init: function () { if (!bbs.inited) { bbs.root = bbs.root.replace(/\W/g, "_"); bbs.store = new Persist.Store(bbs.root, { swf_path: '../persist.swf' }); bbs.inited = true; } }, showmail: function(mail) { if (mail > 0) { document.getElementById('navnm').style.display = 'inline-block'; document.getElementById('navmc').innerHTML = mail; } else { document.getElementById('navnm').style.display = 'none'; } }, check: function () { bbs.init(); bbs.store.get('last', function(ok, val) { //alert(parseInt(val)); var now = new Date().getTime(); if (ok && val && now - parseInt(val) < bbs.interval) { bbs.store.get('mail', function(ok, val) { if (ok && val) { var mail = parseInt(val); bbs.showmail(mail); } }); return; } var request = HTTP.newRequest(); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200) { var res = request.responseXML.getElementsByTagName('bbsidle')[0].getAttribute('mail'); bbs.store.set('mail', res); bbs.showmail(res); } } } request.open('GET', 'idle?date=' + now, true); request.send(null); bbs.store.set('last', now); }); }, navbar: [ 'navb', 'navt', 'navf', 'navc', 'navm', 'navco', 'navs' ], navinit: function() { bbs.init(); bbs.store.get('navbar', function(ok, val) { if (ok && val) { var str = val.toString(); for (var i = 0; i < bbs.navbar.length; i++) { var nav = document.getElementById(bbs.navbar[i]); nav && (nav.getElementsByTagName('ul')[0].style.display = (str.charAt(i) == '0' ? 'none' :'block')); } } }); }, syncinterval: 2000, sync: function() { bbs.navinit(); bbs.check(); } }; addLoadEvent(bbs.sync); setInterval(bbs.sync, bbs.syncinterval);
zzlydm-fbbs
html/js/bbs.js
JavaScript
gpl3
5,212
function closewin() { opener.document.postform.text.value += "\n" + document.getElementById('url').innerHTML + "\n"; return window.close(); }
zzlydm-fbbs
html/js/bbsupload.js
JavaScript
gpl3
147
body { text-align: center; background: #e6d373; behavior: url(csshover.htc); } a:link,a:visited{ text-decoration: none; font-weight: bold; color: #000000; list-style-type: none; font-size: 14px; } a:hover,a:active { color: #304c54; } #container { margin-right: auto; margin-left: auto; position: relative;; height: 548px; width: 850px; background-color: #e6d373; z-index: 1; border:1px solid #000000; } #im01 { background-image: url(images/images_01.gif); position: absolute; top:0; left:0; height: 231px; width: 431px; } #im02 { background-image: url(images/images_02.gif); position: absolute; height: 231px; width: 419px; top: 0px; right: 0px; } #im03{ background-image: url(images/images_03.gif); position: absolute; height: 222px; width: 432px; left: 0px; top: 231px; } #im04{ background-image: url(images/images_04.jpg); position: absolute; height: 317px; width: 418px; right: 0px; bottom: 0; } #im05{ background-image: url(images/images_05.gif); position: absolute; height: 95px; width: 432px; left: 0px; bottom: 0px; } div#nav{ background:transparent; z-index:13; text-align: left; color:#000000; } div#nav ul{ z-index:13; margin:0; padding:5px; width:120px; font-size:16px; position:absolute; left:70px; bottom:130px; border:1px solid #000000; border-right:2px solid #000000; border-bottom:2px solid #000000; } div#nav li { list-style-type: none; width:120px; height:25px; padding:2px; } div#nav ul ul{ position:absolute; top:0; left:130px; width:230px; height:170px; font-size:14px; display:none; border-top:1px solid #000000; border-left:0; border-bottom:0; border-right:1px solid #000000; } div#nav li a{display:block;} div#nav li li{ width:230px; height:20px; padding:0 0 0 5px; } div#nav li li a{ width:230px; display:block; } div#nav>ul a {width: auto;} /*div#nav li li a:hover,#nav li li a:active{ border:1px solid #ffffff; } */ #input{ position: absolute; top: 130px; left: 150px; color: #000000; z-index: 15; font-weight: bold; font-size: 14px; text-align: center; height: 40px; width: 350px; background-color: transparent; } .myinput{ color: #000000; background:transparent; width: 100px; border-top: none; border-right: none; border-left: none; border-bottom: 1px solid #000000; text-align: center; } .mybutton{ background:transparent; height: 20px; width: 50px; color:#000000; font-weight: bold; border-top: 1px solid #000000; border-right: none; border-bottom: 1px solid #000000; border-left: none; } #copyright{ text-align: left; font-size: 14px; color: #000000; position: absolute; left: 0px; bottom: -40px; } #code{ text-align: left; font-size: 14px; position: absolute; right:0px; bottom: -40px; } #code a:link,#code a:visited{ color:#000000; } div#nav ul.level1 li.submenu:hover ul.level2{display:block;}
zzlydm-fbbs
html/style.css
CSS
gpl3
3,131
#hd{position:absolute;top:0;left:144px;margin:0.5em;} #main{position:absolute;top:32px;left:144px;margin:0.5em 0 0.5em 0;} #ft{display:none;margin:0.5em;} #main td{font-size:12px;height:1;} table.content{width:100%;} th.ptitle,td.ptitle{width:auto;} .content tr{line-height:24px;} table.post{width:100%;}
zzlydm-fbbs
html/css/ie6fix.css
CSS
gpl3
305
body, div, ul, ol, li, h1, h2, h3, h4, h5, h6, form, input, textarea, p, blockquote, th, td, dl { margin: 0; padding: 0; } body { font-family: "SimSun", "Gill Sans MT", Verdana, sans-serif; font-size: 1em; width: 100%; background-color: #f0f7ff; } ul, ol { list-style: none; } table { border-collapse: separate; border-spacing: 0; } h2 { font-weight: bold; font-size: 1.5em; margin-bottom: 0.5em; } h3 { font-weight: normal; font-size: 1.2em; margin-bottom: 0.3em; } p { margin-bottom: 0.5em; } a { color: #000000; text-decoration: none; } a:hover { background-color: #ffffdd; } img { border: 0; vertical-align: middle; } th { background-color: #ccddff; text-align: left; } th, td { padding: 0 0.25em; } tr { height: 1.75em; line-height: 1.75em; vertical-align: middle; } #main { margin: 0.5em; font-size: 0.75em; } div.post { -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; border: 2px solid #ccddff; margin-bottom: 1em; width: 100%; } .post div { padding: 0.5em 0 0 0.5em; } div.post_h { background-color: #ccddff; padding-bottom: 0.5em; margin-bottom: 0.5em; } .post_h a { color: #336699; } .post_h span { display: inline-block; width: 4em; } div.post_q { color: #606060; background-color: #ddeeff; padding-left: 1em; } .post_q a { color: #336699; } div.post_s { border-top: 2px dotted #ccddff; font-family: monospace; } .a030 { color: Window; } .a130 { color: #c0c0c0; } .a031 { color: #800000; } .a131 { color: #800000; } .a032 { color: #008000; } .a132 { color: #008000; } .a033 { color: #808000; } .a133 { color: #808000; } .a034 { color: #000080; } .a134 { color: #000080; } .a035 { color: #800080; } .a135 { color: #800080; } .a036 { color: #008080; } .a136 { color: #008080; } .a037 { color: #000000; } .a137 { color: #000000; } .a40 { background-color: #f0f7ff; } .a41 { background-color: #ff0000; } .a42 { background-color: #00ff00; } .a43 { background-color: #ffff00; } .a44 { background-color: #0000ff; } .a45 { background-color: #ff00ff; } .a46 { background-color: #00ffff; } .a47 { background-color: #f0f7ff; }
zzlydm-fbbs
html/css/bbs.css
CSS
gpl3
2,081
* { font-family: Tahoma, Verdana, Arial; } img { border: none; vertical-align: middle; padding-right: 5px; } ul { list-style-type: none; margin: 0; padding: 0; } ul li { padding: 5px 0; margin-right: 10px; } input.txt { background: #edecec; width: 100px; height:20px; border: none; } .box { -webkit-border-radius: 8px; -moz-border-radius: 8px; background-color: #0a3601; } #container { position: relative; width: 810px; margin: 0 auto; } #left_panel { font-weight: bold; width: 155px; float: left; font-size: 0.75em; } #left_panel div { margin: auto 5px 4px 0px; } #left_panel a { color: #ffffff; font-size: 1em; text-decoration: none; display: block; } #left_panel a:hover { background-color: #1e3f45; } #menu { background-color: #505b5f; height: 190px; padding: 12px 10px 2px 12px; } #software { display: none; position: absolute; top: 68px; left: 125px; background-color: #505b5f; border: #F5E4EA solid 1px; } #software li { padding: 5px; margin: 0; } #loginbox { background-color: #505b5f; height: 105px; padding: 10px 0 5px 10px; } #info { background-color: #505b5f; height: 140px; margin-top: 2px; padding: 12px 0 0 12px; } #info p { margin: 2px 25px 8px 8px; padding-bottom: 4px; border-bottom: 2px solid #000000; } #info img { width: 16px; height: 16px; } #info ul li { padding: 1px 0 1px 8px; margin-right: 10px; } #main { background: url('/images/bbswebpic.png') no-repeat; padding-top: 480px; width: 640px; float: left; text-align: center; } #main a { color: black; } #main p { font-size: 0.8em; margin: 2px; }
zzlydm-fbbs
html/css/index.css
CSS
gpl3
1,690
<?xml version="1.0" encoding="gb2312"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <xsl:template name="showpost"> <xsl:param name='content'/> <xsl:variable name='before'><xsl:if test='not(contains($content, "&#10;"))'><xsl:value-of select='$content'/></xsl:if><xsl:value-of select='substring-before($content, "&#10;")'/></xsl:variable> <xsl:variable name='rest' select='substring-after($content, "&#10;")'/> <xsl:variable name='line'> <xsl:call-template name='replace-space'> <xsl:with-param name='str' select='$before'/> </xsl:call-template> </xsl:variable> <xsl:call-template name='showline'> <xsl:with-param name='content' select='$line'/> <xsl:with-param name='isquote' select='starts-with($line, ":&#160;") or starts-with($line, ">&#160;")'/> </xsl:call-template> <br/> <xsl:if test='$rest'> <xsl:call-template name='showpost'> <xsl:with-param name='content' select='$rest'/> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template name='replace-space'> <xsl:param name='str'/> <xsl:choose> <xsl:when test='contains($str, " ")'> <xsl:value-of select='substring-before($str, " ")'/><xsl:text>&#160;</xsl:text> <xsl:call-template name='replace-space'> <xsl:with-param name='str' select='substring-after($str, " ")'/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select='$str'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name='showline'> <xsl:param name='content'/> <xsl:param name='isquote'/> <xsl:choose> <xsl:when test='$isquote'> <xsl:call-template name='ansi-escape'> <xsl:with-param name='content' select='$content'/> <xsl:with-param name='fgcolor'>36</xsl:with-param> <xsl:with-param name='bgcolor'>40</xsl:with-param> <xsl:with-param name='ishl'>0</xsl:with-param> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:variable name='before'> <xsl:choose> <xsl:when test='contains($content, "http://")'> <xsl:value-of select='substring-before($content, "http://")'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='$content'/> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:if test='$before'> <xsl:call-template name='ansi-escape'> <xsl:with-param name='content' select='$before'/> <xsl:with-param name='fgcolor'>37</xsl:with-param> <xsl:with-param name='bgcolor'>40</xsl:with-param> <xsl:with-param name='ishl'>0</xsl:with-param> </xsl:call-template> </xsl:if> <xsl:variable name='after' select='substring-after($content, "http://")'/> <xsl:variable name='index'> <xsl:if test='$after'> <xsl:call-template name='not-str-token'> <xsl:with-param name='str' select='$after'/> <xsl:with-param name='delim'>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~$-_.+!*')(,/:;=?@%#&amp;</xsl:with-param> <xsl:with-param name='start' select='1'/> </xsl:call-template> </xsl:if> </xsl:variable> <xsl:variable name='url'> <xsl:if test='$after'> <xsl:choose> <xsl:when test='string-length($index)'> <xsl:value-of select='substring($after, 1, $index - 1)'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='$after'/> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:variable> <xsl:if test='contains($content, "http://")'> <xsl:call-template name='show-url'> <xsl:with-param name='url' select='concat("http://", $url)'/> </xsl:call-template> </xsl:if> <xsl:if test='$after and $index'> <xsl:call-template name='showline'> <xsl:with-param name='content' select='substring($after, $index)'/> <xsl:with-param name='isquote' select='0'/> </xsl:call-template> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name='show-url'> <xsl:param name='url'/> <xsl:variable name='length' select='string-length($url)'/> <xsl:variable name='lurl' select='translate($url, "JPEGNIF", "jpegnif")'/> <xsl:choose> <xsl:when test='(substring($lurl, $length - 4) = ".jpeg") or (substring($lurl, $length - 3) = ".jpg") or (substring($lurl, $length - 3) = ".png") or (substring($lurl, $length - 3) = ".gif")'> <img> <xsl:attribute name='src'><xsl:value-of select='$url'/></xsl:attribute> <xsl:attribute name='alt'><xsl:value-of select='$url'/></xsl:attribute> </img> </xsl:when> <xsl:otherwise> <a> <xsl:attribute name='href'><xsl:value-of select='$url'/></xsl:attribute> <xsl:value-of select='$url'/> </a> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name='ansi-escape'> <xsl:param name='content'/> <xsl:param name='fgcolor'/> <xsl:param name='bgcolor'/> <xsl:param name='ishl'/> <xsl:choose> <xsl:when test='contains($content, ">1b")'> <xsl:choose> <xsl:when test='$fgcolor = 37'> <xsl:value-of select='substring-before($content, ">1b")'/> </xsl:when> <xsl:otherwise> <span> <xsl:attribute name='class'>a0<xsl:value-of select='$fgcolor'/></xsl:attribute> <xsl:value-of select='substring-before($content, ">1b")'/> </span> </xsl:otherwise> </xsl:choose> <xsl:variable name='second' select='substring-after($content, ">1b")'/> <xsl:variable name='first-alpha'> <xsl:call-template name='not-str-token'> <xsl:with-param name='str' select='$second'/> <xsl:with-param name='delim'>0123456789;[</xsl:with-param> <xsl:with-param name='start' select='1'/> </xsl:call-template> </xsl:variable> <xsl:if test='string-length($first-alpha)'> <xsl:variable name='code'> <xsl:choose> <xsl:when test='substring($second, 1, 1) = "[" and substring($second, $first-alpha, 1) = "m"'> <xsl:value-of select='substring($second, 2, $first-alpha - 2)'/> </xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name='fgc'> <xsl:call-template name='get-color'> <xsl:with-param name='code' select='$code'/> <xsl:with-param name='param-name'>fgcolor</xsl:with-param> <xsl:with-param name='current-value' select='$fgcolor'/> </xsl:call-template> </xsl:variable> <xsl:variable name='bgc'> <xsl:choose> <xsl:when test='$bgcolor = "ignore"'>ignore</xsl:when> <xsl:otherwise> <xsl:call-template name='get-color'> <xsl:with-param name='code' select='$code'/> <xsl:with-param name='param-name'>bgcolor</xsl:with-param> <xsl:with-param name='current-value' select='$bgcolor'/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name='hl'> <xsl:call-template name='get-color'> <xsl:with-param name='code' select='$code'/> <xsl:with-param name='param-name'>highlight</xsl:with-param> <xsl:with-param name='current-value' select='$ishl'/> </xsl:call-template> </xsl:variable> <xsl:variable name='last' select='substring($second, $first-alpha + 1)'/> <xsl:variable name='text'> <xsl:choose> <xsl:when test='contains($last, ">1b")'> <xsl:value-of select='substring-before($last, ">1b")'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='$last'/> </xsl:otherwise> </xsl:choose> </xsl:variable> <span> <xsl:attribute name='class'>a<xsl:value-of select='$hl'/><xsl:value-of select='$fgc'/><xsl:if test='not($bgc = "ignore")'><xsl:text> </xsl:text>a<xsl:value-of select='$bgc'/></xsl:if></xsl:attribute> <xsl:value-of select='$text'/> </span> <xsl:variable name='next' select='substring($last, string-length($text) + 1)'/> <xsl:if test='$next'> <xsl:call-template name='ansi-escape'> <xsl:with-param name='content' select='$next'/> <xsl:with-param name='fgcolor' select='$fgc'/> <xsl:with-param name='bgcolor' select='$bgc'/> <xsl:with-param name='ishl' select='$hl'/> </xsl:call-template> </xsl:if> </xsl:if> </xsl:when> <xsl:otherwise> <xsl:choose> <xsl:when test='$fgcolor = 37'> <xsl:value-of select='$content'/> </xsl:when> <xsl:otherwise> <span> <xsl:attribute name='class'>a0<xsl:value-of select='$fgcolor'/></xsl:attribute> <xsl:value-of select='$content'/> </span> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name='not-str-token'> <xsl:param name='str'/> <xsl:param name='delim'/> <xsl:param name='start'/> <xsl:variable name='char' select='substring($str, $start, 1)'/> <xsl:if test='$char'> <xsl:choose> <xsl:when test='not(contains($delim, $char))'> <xsl:value-of select='$start'/> </xsl:when> <xsl:otherwise> <xsl:call-template name='not-str-token'> <xsl:with-param name='str' select='$str'/> <xsl:with-param name='delim' select='$delim'/> <xsl:with-param name='start' select='$start + 1'/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <xsl:template name='get-color'> <xsl:param name='code'/> <xsl:param name='param-name'/> <xsl:param name='current-value'/> <xsl:variable name='first'> <xsl:choose> <xsl:when test='contains($code, ";")'> <xsl:value-of select='substring-before($code, ";")'/> </xsl:when> <xsl:otherwise><xsl:value-of select='$code'/></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name='next' select='substring-after($code, ";")'/> <xsl:variable name='new-value'> <xsl:if test='$first'> <xsl:choose> <xsl:when test='$param-name = "fgcolor" and $first >= 30 and $first &lt;= 37'> <xsl:value-of select='$first'/> </xsl:when> <xsl:when test='$param-name = "bgcolor" and $first >= 40 and $first &lt;= 47'> <xsl:value-of select='$first'/> </xsl:when> <xsl:when test='$param-name = "highlight" and (($first = 0) or ($first = 1))'> <xsl:value-of select='$first'/> </xsl:when> <xsl:otherwise> <xsl:value-of select='$current-value'/> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:variable> <xsl:choose> <xsl:when test='$next'> <xsl:call-template name='get-color'> <xsl:with-param name='code' select='$next'/> <xsl:with-param name='param-name' select='$param-name'/> <xsl:with-param name='current-value' select='$new-value'/> </xsl:call-template> </xsl:when> <xsl:when test='not($next) and string-length($first) = 0'> <xsl:choose> <xsl:when test='$param-name = "fgcolor"'>37</xsl:when> <xsl:when test='$param-name = "bgcolor"'>40</xsl:when> <xsl:when test='$param-name = "highlight"'>0</xsl:when> <xsl:otherwise></xsl:otherwise> </xsl:choose> </xsl:when> <xsl:otherwise> <xsl:value-of select='$new-value'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="show-quoted"> <xsl:param name='content'/> <xsl:choose> <xsl:when test='contains($content, "&#10;")'> <xsl:variable name='before' select='substring-before($content, "&#10;")'/> <xsl:variable name='rest' select='substring-after($content, "&#10;")'/> <xsl:call-template name='remove-ansi'> <xsl:with-param name='str' select='$before'/> </xsl:call-template> <xsl:text>&#x0d;&#x0a;</xsl:text> <xsl:if test='$rest'> <xsl:call-template name='show-quoted'> <xsl:with-param name='content' select='$rest'/> </xsl:call-template> </xsl:if> </xsl:when> <xsl:otherwise> <xsl:call-template name='remove-ansi'> <xsl:with-param name='str' select='$content'/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name='remove-ansi'> <xsl:param name='str'/> <xsl:choose> <xsl:when test='contains($str, ">1b[")'> <xsl:value-of select='substring-before($str, ">1b[")'/> <xsl:variable name='after' select='substring-after($str, ">1b[")'/> <xsl:if test='$after'> <xsl:variable name='first-alpha'> <xsl:call-template name='not-str-token'> <xsl:with-param name='str' select='$after'/> <xsl:with-param name='delim'>0123456789;</xsl:with-param> <xsl:with-param name='start' select='1'/> </xsl:call-template> </xsl:variable> <xsl:if test='string-length($first-alpha)'> <xsl:call-template name='remove-ansi'> <xsl:with-param name='str' select='substring($after, $first-alpha + 1)'/> </xsl:call-template> </xsl:if> </xsl:if> </xsl:when> <xsl:otherwise> <xsl:value-of select='$str'/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
zzlydm-fbbs
html/xsl/showpost.xsl
XSLT
gpl3
12,914
<?xml version='1.0' encoding='utf-8'?> <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:output method='html' encoding='utf-8' doctype-public='-//W3C//DTD HTML 4.01//EN' doctype-system='http://www.w3.org/TR/html4/strict.dtd'/> <xsl:template name='timeconvert'> <xsl:param name='time'/> <xsl:value-of select='concat(substring($time, 6, 5), " ", substring($time, 12, 5))'/> </xsl:template> <xsl:template match='/'> <html> <head> <title></title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <link rel='stylesheet' type='text/css' href='../css/bbs.css'/> </head> <body> <div id='main'><xsl:apply-templates/></div> </body> </html> </xsl:template> <xsl:template match='bbs_board'> <h2><a href='board?bid={brd/@bid}'><xsl:value-of select='brd/@desc'/> [<xsl:value-of select='brd/@name'/>]</a></h2> <table> <tr><th>标记</th><th>作者</th><th>发表时间</th><th>标题</th></tr> <xsl:for-each select='po'> <tr> <td><xsl:value-of select='@m'/></td> <td><a href='user?name={@o}'><xsl:value-of select='@o'/></a></td> <td><xsl:call-template name='timeconvert'><xsl:with-param name='time' select='@t'/></xsl:call-template></td> <td><a href='post?id={@id}'><xsl:value-of select='.'/></a></td> </tr> </xsl:for-each> </table> <div> <a href='board?bid={brd/@bid}&amp;pid={brd/@begin}&amp;a=p'>前页</a> <a href='board?bid={brd/@bid}&amp;pid={brd/@end}&amp;a=n'>后页</a> </div> </xsl:template> <xsl:template match='bbs_post'> <a href='board?bid={@bid}'>返回版面</a> <a href='post?id={post/@id}&amp;a=n'>下楼</a> <a href='post?id={post/@id}&amp;a=p'>上楼</a> <xsl:if test='post/@id!=@gid'><a href='post?id={@gid}'>顶楼</a></xsl:if> <xsl:apply-templates select='post'/> </xsl:template> <xsl:template match='post'> <div class='post'> <div class='post_h'> <p><span>发信人: </span><a href='user?name={owner}'><xsl:value-of select='owner'/></a> (<xsl:value-of select='nick'/>), 信区: <a href='board?name={board}'><xsl:value-of select='board'/></a></p> <p><span>标 题: </span><xsl:value-of select='title'/></p> <p><span>发信站: </span>复旦泉 (<xsl:value-of select='date'/>), 站内信件</p> </div> <xsl:for-each select='pa'> <div class='post_{@m}'> <xsl:for-each select='p'> <p><xsl:apply-templates select='.'/></p> </xsl:for-each> </div> </xsl:for-each> </div> </xsl:template> <xsl:template match='c'> <span class='a{@h}{@f} a{@b}'><xsl:value-of select='.'/></span> </xsl:template> <xsl:template match='a'> <a href='{@href}'><xsl:choose><xsl:when test='@i'><img src='{@href}'/></xsl:when><xsl:otherwise><xsl:value-of select='@href'/></xsl:otherwise></xsl:choose></a> </xsl:template> </xsl:stylesheet>
zzlydm-fbbs
html/xsl/bbs.xsl
XSLT
gpl3
2,846
<?xml version='1.0' encoding='gb2312'?> <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:import href='bbs.xsl' /> <xsl:output method='html' encoding='gb2312' doctype-public='-//W3C//DTD HTML 4.01//EN' doctype-system='http://www.w3.org/TR/html4/strict.dtd'/> <xsl:template match='/'> <xsl:choose> <xsl:when test='count(bbssel/brd)=1'><html><head><meta http-equiv="refresh"><xsl:attribute name='content'>0; url=<xsl:choose><xsl:when test='bbssel/brd/@dir="1"'>boa?board=<xsl:value-of select='bbssel/brd/@title'/></xsl:when><xsl:otherwise>doc?board=<xsl:value-of select='bbssel/brd/@title'/></xsl:otherwise></xsl:choose></xsl:attribute></meta></head><body></body></html></xsl:when> <xsl:otherwise><xsl:apply-imports/></xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
zzlydm-fbbs
html/xsl/bbssel.xsl
XSLT
gpl3
823
<?xml version='1.0' encoding='gb2312'?> <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:import href='bbs.xsl' /> <xsl:import href='showpost.xsl' /> <xsl:output method='html' encoding='gb2312' doctype-public='-//W3C//DTD HTML 4.01//EN' doctype-system='http://www.w3.org/TR/html4/strict.dtd' /> <xsl:template match='/'> <html> <head> <title><xsl:value-of select='rss/channel/title'/> - <xsl:call-template name='bbsname' /></title> <meta http-equiv="content-type" content="text/html; charset=gb2312" /> <xsl:call-template name='include-css' /> </head> <body><div id='wrap'> <div id='main'><xsl:apply-templates /></div> </div></body> </html> </xsl:template> <xsl:template match='rss/channel'> <h2><a><xsl:attribute name='href'><xsl:value-of select='link'/></xsl:attribute><xsl:value-of select='description'/>[<xsl:value-of select='title'/>]</a></h2> <xsl:for-each select='item'> <div class='post'> <h3><a><xsl:attribute name='href'><xsl:value-of select='link'/></xsl:attribute><xsl:value-of select='title'/></a></h3> <span class='time'><xsl:value-of select='pubDate'/></span><hr/> <xsl:call-template name='showpost'><xsl:with-param name='content' select='description'/></xsl:call-template> </div> </xsl:for-each> </xsl:template> </xsl:stylesheet>
zzlydm-fbbs
html/xsl/bbsrss.xsl
XSLT
gpl3
1,346
// Ver: 4.1.30228 var nOP=0,nOP5=0,nIE=0,nIE4=0,nIE5=0,nNN=0,nNN4=0,nNN6=0,nMAC=0,nIEM=0,nIEW=0,nDM=0,nVER=0.0,st_delb=0,st_addb=0,st_reg=1;stnav();var st_ttb=nIE||nOP&&(nVER>=6&&nVER<7); var stT2P=["static","absolute","absolute"],stHAL=["left","center","right"],stVAL=["top","middle","bottom"],stREP=["no-repeat","repeat-x","repeat-y","repeat"],stBDS=["none","solid","double","dotted","dashed","groove","ridge"]; var st_max=10,st_ht="",st_gc=0,st_rl=null,st_cl,st_ct,st_cw,st_ch,st_cm=0,st_cp,st_ci,st_ri=/Stm([0-9]*)p([0-9]*)i([0-9]*)e/,st_rp=/Stm([0-9]*)p([0-9]*)i/,st_ims=[],st_ms=[],st_load=0,st_scr=null; var st_rsp=new RegExp(" +"); if(nNN4){stitovn=stevfn('stitov',1);stitoun=stevfn('stitou',1);stitckn=stevfn('stitck',1);stppovn=stevfn('stppov',0);stppoun=stevfn('stppou',0);} //if(nIE4||nNN4)onerror=function(m,u,l){return !confirm("Java Script Error\n"+"\nDescription:"+m+"\nSource:"+u+"\nLine:"+l+"\n\nSee more details?");} if(nIE4||nNN4)onerror=function(m,u,l){return false;} if(nDM)onload=st_onload; if(nIEM||nOP5)onunload=function(){if(st_rl){clearInterval(st_rl);st_rl=null;}for(var i=0;i<st_ms.length;++i)st_ms[i].cfrm=0;return true;} if(typeof(st_js)=='undefined'){ if(nDM&&!nNN4) { var s="<STYLE>\n.st_tbcss,.st_tdcss,.st_divcss,.st_ftcss{border:none;padding:0px;margin:0px;}\n</STYLE>"; for(var i=0;i<st_max;i++) s+="<FONT ID=st_gl"+i+"></FONT>"; if(nIEW&&nVER>=5.0&&document.body) document.body.insertAdjacentHTML("AfterBegin",s); else document.write(s); }st_js=1;} function stm_bm(a) { st_ms[st_cm]= { ps:[], mei:st_cm, ids:"Stm"+st_cm+"p", hdid:null, cked:0, cfrm:0, tfrm:window, sfrm:window, mcff:"", mcfd:0, mcfn:0, mcfb:1, mcfx:0, mcfy:0, mnam:a[0], mver:a[1], mweb:a[2], mbnk:stbuf(a[2]+a[3]), mtyp:a[4], mcox:a[5], mcoy:a[6], maln:stHAL[a[7]], mcks:a[8], msdv:a[9], msdh:a[10], mhdd:nNN4?Math.max(100,a[11]):a[11], mhds:a[12], mhdo:a[13], mhdi:a[14], args:a.slice(0) }; } function stm_bp(l,a) { var op=st_cp;var oi=st_ci;st_cp=st_ms[st_cm].ps.length;st_ci=0; var m=st_ms[st_cm]; m.ps[st_cp]= { is:[], mei:st_cm, ppi:st_cp, ids:"Stm"+st_cm+"p"+st_cp+"i", par:(st_cp?[st_cm,op,oi]:null), tmid:null, citi:-1, issh:0, isst:!st_cp&&m.mtyp==0, isck:!st_cp&&m.mcks, exed:0, pver:a[0], pdir:a[1], poffx:a[2], poffy:a[3], pspc:a[4], ppad:a[5], plmw:a[6], prmw:a[7], popc:a[8], pesh:a[9]?a[9]:"Normal", pesi:a[10], pehd:a[11]?a[11]:"Normal", pehi:a[12], pesp:a[13], pstp:a[14], psds:nIEW?a[15]:0, pscl:a[16], pbgc:a[17], pbgi:stbuf(stgsrc(a[18],m,0)), pbgr:stREP[a[19]], pbds:stBDS[a[20]], ipbw:a[21], pbdc:(!nDM||nNN4)?a[22].split(st_rsp)[0]:a[22], args:a.slice(0) }; var p=m.ps[st_cp]; if(st_cp) stgpar(p).sub=[st_cm,st_cp]; p.zind=!st_cp?1000:stgpar(stgpar(p)).zind+10; p.pbgd=stgbg(p.pbgc,p.pbgi,p.pbgr); if(nIEW&&nVER>=5.5) { p.efsh=p.pesh=="Normal"?"stnm":"stft"; p.efhd=p.pehd=="Normal"?"stnm":"stft"; } else if(nIEW&&(nVER>=5.0||nVER>=4.0&&!p.isst)) { p.efsh=p.pesi>=0?"stft":"stnm"; p.efhd=p.pehi>=0?"stft":"stnm"; } else p.efsh=p.efhd="stnm"; eval(l+"=p;"); } function stm_bpx(l,r,a) { var p=eval(r); stm_bp(l,a.concat(p.args.slice(a.length))); } function stm_ai(l,a) { st_ci=st_ms[st_cm].ps[st_cp].is.length; var m=st_ms[st_cm]; var p=m.ps[st_cp]; if(a[0]==6) p.is[st_ci]= { ssiz:a[1], ibgc:[a[2]], simg:stbuf(stgsrc(a[3],m,1)), simw:a[4], simh:a[5], simb:a[6], args:a.slice(0) }; else p.is[st_ci]= { itex:a[0]?a[1]:a[1].replace(new RegExp(" ","g"),"&nbsp;"), iimg:[stbuf(stgsrc(a[2],m,0)),stbuf(stgsrc(a[3],m,0))], iimw:a[4], iimh:a[5], iimb:a[6], iurl:a[7], itgt:a[8], istt:a[9], itip:a[10], iicn:[stbuf(stgsrc(a[11],m,1)),stbuf(stgsrc(a[12],m,1))], iicw:a[13], iich:a[14], iicb:a[15], iarr:[stbuf(stgsrc(a[16],m,1)),stbuf(stgsrc(a[17],m,1))], iarw:a[18], iarh:a[19], iarb:a[20], ihal:stHAL[a[21]], ival:stVAL[a[22]], ibgc:nOP5&&nVER<7.0&&a[24]&&a[26]?["transparent","transparent"]:[nOP5&&nVER<7.0||!a[24]?a[23]:"transparent",nOP5&&nVER<7.0||!a[26]?a[25]:"transparent"], ibgi:[stbuf(stgsrc(a[27],m,0)),stbuf(stgsrc(a[28],m,0))], ibgr:[stREP[a[29]],stREP[a[30]]], ibds:stBDS[a[31]], ipbw:a[32], ibdc:(!nDM||nNN4)?[a[33].split(st_rsp)[0],a[34].split(st_rsp)[0]]:[a[33],a[34]], itxc:[a[35],a[36]], itxf:[a[37],a[38]], itxd:[stgdec(a[39]),stgdec(a[40])], args:a.slice(0) }; var it=st_ms[st_cm].ps[st_cp].is[st_ci]; it.ityp=a[0]; it.mei=st_cm; it.ppi=st_cp; it.iti=st_ci; it.ids=p.ids+st_ci+"e"; it.sub=null; it.tmid=null; if(it.ityp!=6) it.ibgd=[stgbg(it.ibgc[0],it.ibgi[0],it.ibgr[0]),stgbg(it.ibgc[1],it.ibgi[1],it.ibgr[1])]; eval(l+"=it;"); } function stm_aix(l,r,a) { var i=eval(r); stm_ai(l,a.concat(i.args.slice(a.length))); } function stm_ep() { var m=st_ms[st_cm]; var p=m.ps[st_cp]; var i=stgpar(p); if(i) { st_cm=i.mei; st_cp=i.ppi; st_ci=i.iti; } if(p.is.length==0) { m.ps.length--; if(i) i.sub=null; } } function stm_em() { var m=st_ms[st_cm]; if(m.ps.length==0) { st_ms.length--; return; } var mh=""; var mc="<STYLE TYPE='text/css'>\n"; var l=nDM?m.ps.length:1; for(var ppi=0;ppi<l;ppi++) { var p=m.ps[ppi]; var ph=stpbtx(p); if(p.isst&&m.maln!="left") ph="<TABLE STYLE='border:none;padding:0px;' CELLPADDING=0 CELLSPACING=0 ALIGN="+m.maln+"><TD class=st_tdcss>"+ph; for(var iti=0;iti<p.is.length;iti++) { var i=p.is[iti]; var ih=""; ih+=p.pver ? "<TR ID="+i.ids+"TR>" : ""; ih+=stittx(i); ih+=(p.pver ? "</TR>" : ""); ph+=ih; if(i.ityp!=6) { mc+="."+i.ids+"TX0{"+sttcss(i,0)+"}\n"; mc+="."+i.ids+"TX1{"+sttcss(i,1)+"}\n"; } } ph+=stpetx(p); if(p.isst&&m.maln!="left") ph+="</TD></TABLE>"; if(p.isst||nNN4||!nDM) mh+=ph; else st_ht+=ph; } mc+="</STYLE>"; if(!nDM||nNN4) document.write(mc); if(mh) document.write(mh); if(nDM&&!(nIEM||(nIEW&&nVER<5.0))) { if(st_ht) { var o=stgobj('st_gl'+st_gc); if(nNN6) o.innerHTML=st_ht; else if(nIE&&nVER>=5.0) o.insertAdjacentHTML("BeforeEnd",st_ht); else o.document.write(st_ht); st_gc++; st_ht=''; } if(!nOP&&!nNN) stpre(m); } st_cm++;st_cp=0;st_ci=0; } function stpbtx(p) { var s=""; if(nNN4||!nDM) { s+=p.isst?"<ILAYER":"<LAYER"; s+=" VISIBILITY=hide"; s+=" ID="+p.ids; s+=" Z-INDEX="+p.zind; s+="><LAYER>"; s+="<TABLE BORDER=0 CELLSPACING=0 CELLPADDING="+p.pspc; s+=" BACKGROUND='"+p.pbgi+"'"; s+=" BGCOLOR="+(p.pbgi||p.pbgc=="transparent"?"''":p.pbgc); s+=">"; } else { var ds="position:"+stT2P[p.ppi?1:stgme(p).mtyp]+";"; ds+="z-index:"+p.zind+";"; ds+="visibility:hidden;"; s+=st_ttb ? "<TABLE class=st_tbcss CELLPADDING=0 CELLSPACING=0" : "<DIV class=st_divcss"; s+=stppev(p); s+=" ID="+p.ids; s+=" STYLE='"; if(nIEM) s+="width:1px;"; else if(nIE) s+="width:0px;"; s+=stfcss(p); s+=ds; s+="'>"; if(st_ttb) s+="<TD class=st_tdcss ID="+p.ids+"TTD>"; s+="<TABLE class=st_tbcss CELLSPACING=0 CELLPADDING=0"; s+=" ID="+p.ids+"TB"; s+=" STYLE='"; s+=stpcss(p); if(nIEW) s+="margin:"+p.psds+"px;"; s+="'>"; } return s; } function stpetx(p) { var s="</TABLE>"; if(nNN4||!nDM) s+="</LAYER></LAYER>"; else if(st_ttb) s+="</TD></TABLE>"; else s+="</DIV>"; return s; } function stittx(i) { var s=""; var p=stgpar(i); if(nNN4||!nDM) { s+="<TD WIDTH=1 NOWRAP>"; s+="<FONT STYLE='font-size:1pt;'>"; s+="<ILAYER ID="+i.ids+"><LAYER"; if(i.ipbw&&i.ityp!=6) s+=" BGCOLOR="+i.ibdc[0]; s+=">"; for(var l=0;l<(nNN4?2:1);l++) { if(i.ityp==6&&l) break; s+="<LAYER Z-INDEX=10 VISIBILITY="+(l?"HIDE":"SHOW"); if(i.ityp!=6) { s+=" LEFT="+i.ipbw+" TOP="+i.ipbw; } s+=">"; s+="<TABLE ALIGN=LEFT WIDTH=100% BORDER=0 CELLSPACING=0 CELLPADDING="+(i.ityp==6 ? 0 : p.ppad); s+=" BACKGROUND='"+(i.ityp!=6?i.ibgi[l]:"")+"'"; s+=" BGCOLOR="+(i.ityp!=6&&i.ibgi[l]||i.ibgc[l]=="transparent"?"''":i.ibgc[l]) s+=">"; if(i.ityp==6) { s+="<TD NOWRAP VALIGN=TOP"+ " HEIGHT="+(p.pver ? i.ssiz : "100%")+ " WIDTH="+(p.pver ? "100%" : i.ssiz)+ " STYLE='font-size:0pt;'"+ ">"; s+=stgimg(i.simg,i.ids+"LINE",i.simw,i.simh,0); s+="</TD>"; } else { if(p.pver&&p.plmw||!p.pver&&i.iicw) { s+="<TD ALIGN=CENTER VALIGN=MIDDLE"; s+=stgiws(i); s+=">"; s+=stgimg(i.iicn[l],"",i.iicw,i.iich,i.iicb); s+="</TD>"; } s+="<TD WIDTH=100% NOWRAP ALIGN="+i.ihal+" VALIGN="+i.ival+">"; s+="<A "+stgurl(i)+" CLASS='"+(i.ids+"TX"+l)+"'>"; if(i.ityp==2) s+=stgimg(i.iimg[l],i.ids+"IMG",i.iimw,i.iimh,i.iimb); else { s+="<IMG SRC=\""+stgme(i).mbnk+"\" WIDTH=1 HEIGHT=1 BORDER=0 ALIGN=ABSMIDDLE>"; s+=i.itex; } s+="</A>"; s+="</TD>"; if(p.pver&&p.prmw||!p.pver&&i.iarw) { s+="<TD ALIGN=CENTER VALIGN=MIDDLE"; s+=stgaws(i); s+=">"; s+=stgimg(i.iarr[l],"",i.iarw,i.iarh,i.iarb); s+="</TD>"; } } s+="</TABLE>"; if(i.ipbw&&i.ityp!=6) s+="<BR CLEAR=ALL><SPACER HEIGHT=1 WIDTH="+i.ipbw+"></SPACER><SPACER WIDTH=1 HEIGHT="+i.ipbw+"></SPACER>"; s+="</LAYER>"; } if(i.ityp!=6) s+="<LAYER Z-INDEX=20></LAYER>"; s+="</LAYER></ILAYER>" s+="</FONT>"; s+="</TD>"; } else { s+="<TD class=st_tdcss NOWRAP VALIGN="+(nIE ? "MIDDLE" : "TOP"); s+=" STYLE='" s+="padding:"+p.pspc+"px;"; s+="'"; s+=" ID="+p.ids+i.iti; if(nIEW) s+=" HEIGHT=100%"; s+=">"; if(!nOP&&!nIE) { s+="<DIV class=st_divcss ID="+i.ids; s+=stitev(i); s+=" STYLE=\""+sticss(i,0); s+="\""; s+=">"; } s+="<TABLE class=st_tbcss CELLSPACING=0 CELLPADDING=0"; if(!nOP) s+=" HEIGHT=100%"; s+=" STYLE=\""; if(nOP||nIE) s+=sticss(i,0); s+="\""; if(nOP||nIE) s+=stitev(i); if(p.pver||nIEM) s+=" WIDTH=100%"; s+=" ID="+(nOP||nIE ? i.ids : (i.ids+"TB")); if(!nOP) s+=" TITLE="+stquo(i.ityp!=6 ? i.itip : ""); s+=">"; if(i.ityp==6) { s+="<TD class=st_tdcss NOWRAP VALIGN=TOP"+ " ID="+i.ids+"MTD"+ " HEIGHT="+(p.pver ? i.ssiz : "100%")+ " WIDTH="+(p.pver ? "100%" : i.ssiz)+ ">"; s+=stgimg(i.simg,i.ids+"LINE",i.simw,i.simh,0); s+="</TD>"; } else { if(p.pver&&p.plmw||!p.pver&&i.iicw) { s+="<TD class=st_tdcss NOWRAP ALIGN=CENTER VALIGN=MIDDLE HEIGHT=100%"; s+=" STYLE=\"padding:"+p.ppad+"px\""; s+=" ID="+i.ids+"LTD"; s+=stgiws(i); s+=">"; s+=stgimg(i.iicn[0],i.ids+"ICON",i.iicw,i.iich,i.iicb); s+="</TD>"; } s+="<TD class=st_tdcss NOWRAP HEIGHT=100% STYLE=\""; s+="color:"+i.itxc[0]+";"; s+="padding:"+p.ppad+"px;"; s+="\""; s+=" ID="+i.ids+"MTD"; s+=" ALIGN="+i.ihal; s+=" VALIGN="+i.ival+">"; s+="<FONT class=st_ftcss ID="+i.ids+"TX STYLE=\""+sttcss(i,0)+"\">"; if(i.ityp==2) s+=stgimg(i.iimg[0],i.ids+"IMG",i.iimw,i.iimh,i.iimb); else { s+=i.itex; } s+="</FONT>"; s+="</TD>"; if(p.pver&&p.prmw||!p.pver&&i.iarw) { s+="<TD class=st_tdcss NOWRAP ALIGN=CENTER VALIGN=MIDDLE HEIGHT=100%"; s+=" STYLE=\"padding:"+p.ppad+"px\""; s+=" ID="+i.ids+"RTD"; s+=stgaws(i); s+=">"; s+=stgimg(i.iarr[0],i.ids+"ARROW",i.iarw,i.iarh,i.iarb); s+="</TD>"; } } s+="</TABLE>"; if(!nOP&&!nIE) s+="</DIV>"; s+="</TD>"; } return s; } function stpcss(p) { var s=""; s+="border-style:"+p.pbds+";"; s+="border-width:"+p.ipbw+"px;"; s+="border-color:"+p.pbdc+";"; if(nIE) s+="background:"+p.pbgd+";"; else { s+="background-color:"+(p.pbgc)+";"; if(p.pbgi) { s+="background-image:url("+p.pbgi+");"; s+="background-repeat:"+p.pbgr+";"; } } return s; } function stfcss(p) { var s=""; if(nIEW&&(nVER>=5.0||!p.isst)) { var dx=nVER>=5.5?"progid:DXImageTransform.Microsoft." : ""; s+="filter:"; if(nVER>=5.5) { if(p.pesh!="Normal") s+=p.pesh+" "; } else { if(p.pesi<24&&p.pesi>=0) s+="revealTrans(Transition="+p.pesi+",Duration="+((110-p.pesp)/100)+") "; } s+=dx+"Alpha(opacity="+p.popc+") "; if(p.psds) { if(p.pstp==1) s+=dx+"dropshadow(color="+p.pscl+",offx="+p.psds+",offy="+p.psds+",positive=1) "; else s+=dx+"Shadow(color="+p.pscl+",direction=135,strength="+p.psds+") "; } if(nVER>=5.5) { if(p.pehd!="Normal") s+=p.pehd+" "; } else { if(p.pehi<24&&p.pehi>=0) s+="revealTrans(Transition="+p.pehi+",Duration="+((110-p.pesp)/100)+") "; } s+=";"; } return s; } function sticss(i,n) { var s=""; if(i.ityp!=6) { s+="border-style:"+i.ibds+";"; s+="border-width:"+i.ipbw+"px;"; s+="border-color:"+i.ibdc[n]+";"; if(!nIEM&&i.ibgi[n]) { s+="background-image:url("+i.ibgi[n]+");"; s+="background-repeat:"+i.ibgr[n]+";"; } } if(nIEM&&i.ityp!=6) s+="background:"+i.ibgd[n]+";"; else s+="background-color:"+i.ibgc[n]+";"; s+="cursor:"+stgcur(i)+";"; return s; } function sttcss(i,n) { var s=""; s+="cursor:"+stgcur(i)+";"; s+="font:"+i.itxf[n]+";"; s+="text-decoration:"+i.itxd[n]+";"; if(!nDM||nNN4) s+="background-color:transparent;color:"+i.itxc[n]; return s; } function stitov(e,o,i) { var p=stgpar(i); if(nIEW) { if(!i.layer) i.layer=o; if(!p.issh||(e.fromElement&&o.contains(e.fromElement))) return; } else { if(!p.issh||(!nNN&&(e.fromElement&&e.fromElement.id&&e.fromElement.id.indexOf(i.ids)>=0))) return; } if(nNN4) stglay(i).document.layers[0].captureEvents(Event.CLICK); var m=stgme(i); stfrm(m); var w=m.sfrm; if(w!=window) m=w.stmenu(m.mnam); if(m.hdid) { w.clearTimeout(m.hdid); m.hdid=null; } var cii=p.citi; var ci=null; if(cii>=0) ci=p.is[cii]; if(!p.isck||stgme(i).cked) { if(p.citi!=i.iti&&p.citi>=0) sthdit(p.is[p.citi]); stshit(i); p.citi=i.iti; } if(i.istt) status=i.istt; } function stitou(e,o,i) { if(nIEW) { if(!stgpar(i).issh||e.toElement&&o.contains(e.toElement)) return; } else { if(!stgpar(i).issh||(!nNN&&(e.toElement&&e.toElement.id&&e.toElement.id.indexOf(i.ids)>=0))) return; } if(nNN4) stglay(i).document.layers[0].releaseEvents(Event.CLICK); stfrm(stgme(i)); var p=stgtsub(i); if(!p||!p.issh) { stshst(i,0); stgpar(i).citi=-1; } else if(p&&p.issh&&!p.exed) sthdit(i); status=""; } function stitck(e,o,i) { if(e.button&&e.button>=2) return; var m=stgme(i); stfrm(m); var p=stgpar(i); if(p.isck) { m.cked=!m.cked; if(m.cked) { stshit(i); p.citi=i.iti; } else { sthdit(i); p.citi=-1; } } if(!nNN4&&!(p.isck&&stgsub(i))&&i.iurl) { if(i.ppi&&m.sfrm!=window) hideMenu(m.mnam); if(i.iurl.toLowerCase().indexOf("javascript:")==0) eval(i.iurl.substring(11,i.iurl.length)); else { var w=stgtgt(i); if(w) w.location.href=i.iurl; else open(i.iurl,i.itgt); } } } function stppov(e,o,p) { if(nIEW) { if(!p.layer) p.layer=o; if(!p.issh||(e.fromElement&&o.contains(e.fromElement))) return; } else { if(!p.issh||(!nNN&&(e.fromElement&&e.fromElement.id&&e.fromElement.id.indexOf(p.ids)>=0))) return; } var m=stgme(p); stfrm(m); var w=m.sfrm; if(w!=window) m=w.stmenu(m.mnam); if(m.hdid) { w.clearTimeout(m.hdid); m.hdid=null; } } function stppou(e,o,p) { if(nIEW) { if(!p.issh||(e.toElement&&o.contains(e.toElement))) return; } else { if(!p.issh||(!nNN&&(e.toElement&&e.toElement.id&&e.toElement.id.indexOf(p.ids)>=0))) return; } var m=stgme(p); stfrm(m); var w=m.sfrm; if(w!=window) m=w.stmenu(m.mnam); if(m.hdid) w.clearTimeout(m.hdid); m.hdid=w.setTimeout("sthdall(st_ms['"+m.mei+"'],0);",m.mhdd); } function stshst(i,n) { if(nNN4) { var ls=stgstlay(i); ls[n].parentLayer.bgColor=i.ibdc[n]; ls[n].visibility="show"; ls[1-n].visibility="hide"; } else { var o=stglay(i); var os=o.style; if(nIEM) { if(i.ibgd[0]!=i.ibgd[1]) os.background=i.ibgd[n]; } else { if(i.ibgc[0]!=i.ibgc[1]) { if(nOP&&nVER<6) os.background=i.ibgc[n]; else os.backgroundColor=i.ibgc[n]; } if(i.ibgi[0]!=i.ibgi[1]) os.backgroundImage="url("+(i.ibgi[n]?i.ibgi[n]:stgme(i).mbnk)+")"; if(i.ibgr[0]!=i.ibgr[1]) os.backgroundRepeat=i.ibgr[n]; } if(i.ibdc[0]!=i.ibdc[1]) os.borderColor=i.ibdc[n]; var t; if(i.iicn[0]!=i.iicn[1]) { t=nNN6?stgobj(i.ids+"ICON"):o.all[i.ids+"ICON"]; if(t) t.src=i.iicn[n]; } if(i.iarr[0]!=i.iarr[1]) { t=nNN6?stgobj(i.ids+"ARROW"):o.all[i.ids+"ARROW"]; if(t) t.src=i.iarr[n]; } if(i.ityp==2&&i.iimg[0]!=i.iimg[1]) { t=nNN6?stgobj(i.ids+"IMG"):o.all[i.ids+"IMG"]; if(t) t.src=i.iimg[n]; } if (!i.txstyle) i.txstyle=nNN6?stgobj(i.ids+"TX"):o.all[i.ids+"TX"].style; t=i.txstyle; if(i.itxf[0]!=i.itxf[1]) t.font=i.itxf[n]; if(i.itxd[0]!=i.itxd[1]) t.textDecoration=i.itxd[n]; if(nOP) o.all[i.ids+'MTD'].style.color=i.itxc[n]; else t.color=i.itxc[n]; } } function stshpp(p) { stshow(p); } function sthdpp(p) { if(p.citi>=0) { var t=stgsub(p.is[p.citi]); if(t&&t.issh) sthdpp(t); stshst(p.is[p.citi],0); p.citi=-1; } sthide(p); } function stshit(i) { var w=stgme(i).tfrm; var p=stgtsub(i); if(p&&!p.issh) w.stshpp(p); stshst(i,1); } function sthdit(i) { var w=stgme(i).tfrm; var p=stgtsub(i); if(p&&p.issh) w.sthdpp(p); stshst(i,0); } function stshow(p) { var d=p.ppi&&stgpar(stgpar(p)).pver ? stgme(p).msdv : stgme(p).msdh; p.exed=0; if(!p.rc) stgxy(p); if(p.tmid) { clearTimeout(p.tmid); p.tmid=null; stwels(1,p) } if(d>0) p.tmid=setTimeout(stsdstr(p,1),d); p.issh=1; if(d<=0) eval(stsdstr(p,1)); } function sthide(p) { if(p.tmid) { clearTimeout(p.tmid); p.tmid=null; } if(p.issh&&!p.exed) { p.exed=0; p.issh=0; } else { p.exed=0; p.issh=0; eval(stsdstr(p,0)); } } function stshx(p) { var ly=stglay(p); if(nNN4) { ly.visibility='show'; if(!p.fixed) { ly.resizeBy(p.ipbw*2,p.ipbw*2); ly=ly.document.layers[0]; ly.moveTo(p.ipbw,p.ipbw); ly.onmouseover=stppovn; ly.onmouseout=stppoun; for(var l=p.is.length-1;l>=0;l--) { var i=p.is[l]; if(i.ityp!=6) { var ls=stgstlay(i); ls[2].resizeTo(ls[0].parentLayer.clip.width,ls[0].parentLayer.clip.height); if(stgcur(i)=="hand") { with(ls[2].document) { open(); write("<A"+stgurl(i)+"><IMG BORDER=0 SRC='"+stgme(i).mbnk+"' WIDTH="+ls[2].clip.width+" HEIGHT="+ls[2].clip.height+"></A>"); close(); } } ls[0].resizeBy(-i.ipbw,-i.ipbw); ls[1].resizeBy(-i.ipbw,-i.ipbw); ly=stglay(i).document.layers[0]; ly.onmouseover=stitovn; ly.onmouseout=stitoun; ly.onclick=stitckn; } } if(p.ipbw) setTimeout("var pp=st_ms["+p.mei+"].ps["+p.ppi+"];stglay(pp).bgColor=pp.pbdc;",1); p.fixed=1; } } else { ly.style.visibility='visible'; if(nIE5) ly.filters['Alpha'].opacity=p.popc; } } function sthdx(p) { var ly=stglay(p); if(nNN4) ly.visibility='hide'; else { if(nIE5) ly.filters['Alpha'].opacity=0; ly.style.visibility='hidden'; } } function sthdall(m,f) { var w=m.sfrm; var s=w==window?m:w.stmenu(m.mnam); s.cked=0; var p=s.ps[0]; if(p.issh) { if(p.citi>=0) { w.sthdit(p.is[p.citi]); p.citi=-1; } if(s.mtyp==2&&f) w.sthide(p); } s.hdid=null; } function stnmsh(p) { stmvto(stgxy(p),p); stwels(-1,p); stshx(p); } function stnmhd(p) { sthdx(p); stwels(1,p); stmvto([-999,-999],p); } function stftsh(p) { if(nVER<5.5) stshfx(p); else if(st_reg) eval("try{stshfx(p);} catch(er){st_reg=0;stnmsh(p);}"); else stnmsh(p); } function stfthd(p) { if(nVER<5.5) sthdfx(p); else if(st_reg) eval("try{sthdfx(p);}catch(er){st_reg=0;stnmhd(p);}"); else stnmhd(p); } function stshfx(p) { var t=stglay(p).filters[0]; if(nVER>=5.5) t.enabled=1; if(t.Status!=0) t.stop(); stmvto(stgxy(p),p); stwels(-1,p); t.apply(); stshx(p); t.play(); } function sthdfx(p) { var t=stglay(p).filters[stglay(p).filters.length-1]; if(nVER>=5.5) t.enabled=1; if(t.Status!=0) t.stop(); t.apply(); sthdx(p); stwels(1,p); stmvto([-999,-999],p); t.play(); } function ststxy(m,xy) { m.mcox=xy[0]; m.mcoy=xy[1]; } function stnav() { var v=navigator.appVersion; var a=navigator.userAgent; nMAC=v.indexOf("Mac")>=0; nOP=a.indexOf("Opera")>=0; if(nOP) { nVER=parseFloat(a.substring(a.indexOf("Opera ")+6,a.length)); nOP5=nVER>=5.12&&!nMAC&&a.indexOf("MSIE 5.0")>=0; if(nVER>=7) nOP5=1; } else { nIE=document.all ? 1 : 0; if(nIE) { nIE4=(eval(v.substring(0,1)>=4)); nVER=parseFloat(a.substring(a.indexOf("MSIE ")+5,a.length)); nIE5=nVER>=5.0&&nVER<5.5&&!nMAC; nIEM=nIE4&&nMAC; nIEW=nIE4&&!nMAC; } else { nNN4=navigator.appName.toLowerCase()=="netscape"&&v.substring(0,1)=="4" ? 1 : 0; if(!nNN4) { nNN6=(document.getElementsByTagName("*") && a.indexOf("Gecko")!=-1); if(nNN6) { nVER=parseInt(navigator.productSub); if(a.indexOf("Netscape")>=0) { st_delb=nVER<20001108+1; st_addb=nVER>20020512-1; } else { st_delb=nVER<20010628+1; st_addb=nVER>20011221-1; } } } else nVER=parseFloat(v); nNN=nNN4||nNN6; } } nDM=nOP5||nIE4||nNN; } function stckpg() { var w=st_cw; var h=st_ch; var l=st_cl; var t=st_ct; st_cw=stgcw(); st_ch=stgch(); st_cl=stgcl(); st_ct=stgct(); if(((nOP&&nVER<7.0)||nNN4)&&(st_cw-w||st_ch-h)) document.location.reload(); else if(st_cl-l||st_ct-t) stscr(); } function st_onload() { if(nIEM||nOP5||nNN||(nIEW&&nVER<5.0)) { if(st_ht) document.body.insertAdjacentHTML('BeforeEnd',st_ht); for(i=0;i<st_ms.length;i++) stpre(st_ms[i]); } st_load=1; if(!nNN4) { for(var i=0;i<st_ms.length;i++) { var m=st_ms[i]; for(var j=0;j<m.ps.length;j++) { var p=m.ps[j]; if(p.issh&&p.exed) stwels(-1,p); } } } } function stpre(m) { var p=m.ps[m.ps.length-1]; var i=p.is[p.is.length-1]; while(1) if(stglay(i)) break; if(!nNN4) stfix(m); if(m.mtyp!=2) stshow(m.ps[0]); if(nIE) onscroll=new Function("if(st_scr)clearTimeout(st_scr);st_scr=setTimeout('stscr();',nIEM ?500:0);"); else if(!st_rl) { st_cw=stgcw(); st_ch=stgch(); st_cl=stgcl(); st_ct=stgct(); st_rl=setInterval("stckpg();",500); } m.ready=1; } function stfix(m) { for(var l=0;l<m.ps.length;l++) { var p=m.ps[l]; if(nOP&&nVER<6.0) stglay(p).style.pixelWidth=parseInt(stgobj(p.ids+"TB").style.pixelWidth); if(nIE5) stglay(p).style.width=stglay(p).offsetWidth; else if(nIEM||!nIE) { if(!p.pver) { var ii=0; var fi=stgobj(p.ids+ii); var h=parseInt(nOP ? fi.style.pixelHeight : fi.offsetHeight); if(h) { for(ii=0;ii<p.is.length;ii++) { var i=p.is[ii]; var lys=stglay(i).style; var th=h-2*p.pspc; if(nOP) lys.pixelHeight=th; else if(i.ityp==6||nIE) lys.height=th+'px'; else lys.height=th-2*i.ipbw+'px'; if(nIEM) { var fh=h-2*p.pspc; var lt=stgobj(i.ids+"LTD"); var rt=stgobj(i.ids+"RTD"); if(lt) lt.style.height=fh+'px'; stgobj(i.ids+"MTD").style.height=fh+'px'; if(rt) rt.style.height=fh+'px'; } } } } else if(nOP) { for(var ii=0;ii<p.is.length;ii++) { var i=p.is[ii]; if(i.ityp!=6) { var fi=stgobj(p.ids+ii); var it=stglay(i); var w=parseInt(fi.style.pixelWidth); var h=parseInt(it.style.pixelHeight); if(w) it.style.pixelWidth=w-2*p.pspc; if(h) it.style.pixelHeight=h; } } } } } } function stscr() { for(var l=0;l<st_ms.length;l++) { var m=st_ms[l]; stfrm(m); sthdall(m,0); if(m.mtyp==1) { var p=m.ps[0]; stwels(1,p); stmvto(stgxy(m.ps[0]),p); stwels(-1,p); } } } function stwels(c,p) { var m=stgme(p); if(!st_load||nNN4||nOP||p.isst) return; if(m.mhds&&!nNN6) stwtag("SELECT",c,p); if(m.mhdo) stwtag("OBJECT",c,p); if(m.mhdi&&!nNN6&&!(nIEW&&nVER>=5.5)) stwtag("IFRAME",c,p); } function stwtag(tg,c,o) { var es=nNN6 ? document.getElementsByTagName(tg) : document.all.tags(tg); var l; for(l=0;l<es.length;l++) { var e=es.item(l); var f=0; for(var t=e.offsetParent;t;t=t.offsetParent) if(t.id&&t.id.indexOf("Stm")>=0) f=1; if(f) continue; else if(stwover(e,o)) { if(e.visLevel) e.visLevel+=c; else e.visLevel=c; if(e.visLevel==-1) { if(typeof(e.visSave)=='undefined') e.visSave=e.style.visibility; e.style.visibility="hidden"; } else if(e.visLevel==0) e.style.visibility=e.visSave; } } } function stmvto(xy,p) { if(xy&&(p.ppi||stgme(p).mtyp!=0)) { var l=stglay(p); if(nNN4) l.moveToAbsolute(xy[0],xy[1]); else if(nOP) { var ls=l.style; ls.pixelLeft=xy[0]; ls.pixelTop=xy[1]; } else { var ls=l.style; ls.left=xy[0]+'px'; ls.top=xy[1]+'px'; } p.rc=[xy[0],xy[1],p.rc[2],p.rc[3]]; } } function stsdstr(p,iss) { return "var pp=st_ms["+p.mei+"].ps["+p.ppi+"];pp.tmid=null;"+(iss? p.efsh+"sh(" : p.efhd+"hd(")+"pp);pp.exed=1;" } function stwover(e,o) { var l=0; var t=0; var w=e.offsetWidth; var h=e.offsetHeight; if(w) e._wd=w; else w=e._wd; if(h) e._ht=h; else h=e._ht; while(e) { l+=e.offsetLeft; t+=e.offsetTop; e=e.offsetParent; } return ((l<o.rc[2]+o.rc[0]) && (l+w>o.rc[0]) && (t<o.rc[3]+o.rc[1]) && (t+h>o.rc[1])); } function stevfn(pr,isi) { var s=isi ? 'st_ri' : 'st_rp'; s+='.exec(this.parentLayer.id);mei=RegExp.$1;ppi=parseInt(RegExp.$2);'; if(isi) s+='iti=parseInt(RegExp.$3);return '+pr+'(e,this,st_ms[mei].ps[ppi].is[iti]);'; else s+='return '+pr+'(e,this,st_ms[mei].ps[ppi]);'; return new Function('e',s); } function stppev(p) { var s=" onMouseOver='stppov(event,this,st_ms["+p.mei+"].ps["+p.ppi+"]);'"; s+=" onMouseOut='stppou(event,this,st_ms["+p.mei+"].ps["+p.ppi+"]);'"; return s; } function stitev(i) { if(i.ityp==6) return ''; var s=" onMouseOver='stitov(event,this,st_ms["+i.mei+"].ps["+i.ppi+"].is["+i.iti+"]);'"; s+=" onMouseOut='stitou(event,this,st_ms["+i.mei+"].ps["+i.ppi+"].is["+i.iti+"]);'"; s+=" onClick='stitck(event,this,st_ms["+i.mei+"].ps["+i.ppi+"].is["+i.iti+"]);'"; return s; } function stquo(n) { return "\""+n+"\""; } function stgurl(i) { return " HREF=" + stquo(i.iurl=="" ? "#" : i.iurl.replace(new RegExp("\"","g"),"&quot;")) + " TARGET=" + stquo(i.iurl==""||i.iurl.toLowerCase().indexOf('javascript:')==0 ? "_self" : i.itgt); } function stgdec(v) { if(v) { var s=''; if(v&1) s+='underline '; if(v&2) s+='line-through '; if(v&4) s+='overline'; return s; } else return 'none'; } function stgimg(src,id,w,h,b) { var s='<IMG SRC='; s+=stquo(src); if(id) s+=' ID='+id; if(w>0) s+=' WIDTH='+w; else if(nNN) s+=' WIDTH=0'; if(h>0) s+=' HEIGHT='+h; else if(nNN) s+=' HEIGHT=0'; s+=' BORDER='+b+'>'; return s; } function stgbg(c,im,r) { var s=c; if(im) s+=" url("+im+") "+r; return s; } function stgcur(i) { if(nNN6) return "default"; return i.ityp!=6&&((i.ppi==0&&stgme(i).mcks&&stgsub(i))||i.iurl) ? "hand" : "default"; } function stgiws(o) { if(stgpar(o).pver) return stgpar(o).plmw>0 ? " WIDTH="+(stgpar(o).plmw+2) : ""; else return o.iicw>0 ? " WIDTH="+(o.iicw+2) : ""; } function stgaws(o) { if(stgpar(o).pver) return stgpar(o).prmw>0 ? " WIDTH="+(stgpar(o).prmw+2) : ""; else return o.iarw>0 ? " WIDTH="+(o.iarw+2) : ""; } function stgme(ip) { return st_ms[ip.mei]; } function stgpar(ip) { if(typeof(ip.iti)!="undefined") return st_ms[ip.mei].ps[ip.ppi]; else return !ip.par ? null : st_ms[ip.par[0]].ps[ip.par[1]].is[ip.par[2]]; } function stgsub(i) { return !i.sub ? null : st_ms[i.sub[0]].ps[i.sub[1]]; } function stgcl() { return parseInt(nNN||nOP ? pageXOffset : document.body.scrollLeft); } function stgct() { return parseInt(nNN||nOP ? pageYOffset : document.body.scrollTop); } function stgcw() { return parseInt(nNN||nOP ? innerWidth : (nIEW&&document.compatMode=="CSS1Compat" ? document.documentElement.clientWidth : document.body.clientWidth)); } function stgch() { return parseInt(nNN||nOP ? innerHeight : (nIEW&&document.compatMode=="CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight)); } function stgobj(id) { if(nIE&&nVER<5) return document.all[id]; if(nNN4) return document.layers[id]; return document.getElementById(id); } function stglay(ip) { if(!ip.layer) { if(typeof(ip.iti)=='undefined') ip.layer=stgobj(ip.ids); else if(nNN4) ip.layer=stglay(stgpar(ip)).document.layers[0].document.layers[ip.ids]; else if(nNN6) ip.layer=stgobj(ip.ids); else ip.layer=stglay(stgpar(ip)).all.tags("table")[ip.ids]; } return ip.layer; } function stgstlay(i) { return stglay(i).document.layers[0].document.layers; } function stgrc(ip) { if(nNN4) { var ly=stglay(ip); return [ly.pageX,ly.pageY,ly.clip.width,ly.clip.height]; } else { var l=0,t=0; var ly=stglay(ip); var w=typeof(ip.rc)=="undefined"?parseInt(nOP&&nVER<7?ly.style.pixelWidth:ly.offsetWidth):ip.rc[2]; var h=typeof(ip.rc)=="undefined"?parseInt(nOP&&nVER<7?ly.style.pixelHeight:ly.offsetHeight):ip.rc[3]; while(ly) { l+=parseInt(ly.offsetLeft); t+=parseInt(ly.offsetTop); ly=ly.offsetParent; } if(nIEM) { l+=parseInt(document.body.leftMargin); l-=ip.ipbw; t-=ip.ipbw; } if(typeof(ip.iti)!='undefined') { if(st_delb) { l-=ip.ipbw; t-=ip.ipbw; } if(st_addb) { l+=stgpar(ip).ipbw; t+=stgpar(ip).ipbw; } } return [l,t,w,h]; } } function stgxy(p) { var x=p.poffx; var y=p.poffy; var sr=stgrc(p); p.rc=sr; if(p.ppi==0) { if(stgme(p).mtyp==2) return [stgme(p).mcox,stgme(p).mcoy]; else if(stgme(p).mtyp==1) return [eval(stgme(p).mcox),eval(stgme(p).mcoy)]; else return [sr[0],sr[1]]; } var ir=stgirc(stgpar(p)); var cl=stgcl(); var ct=stgct(); var cr=cl+stgcw(); var cb=ct+stgch(); if(p.pdir==1) x=p.poffx+ir[0]-sr[2]+p.psds; else if(p.pdir==2) x=p.poffx+ir[0]+ir[2]-p.psds; else x=p.poffx+ir[0]-p.psds; if(x+sr[2]>cr) x=cr-sr[2]; if(x<cl) x=cl; if(p.pdir==3) y=p.poffy+ir[1]-sr[3]+p.psds; else if(p.pdir==4) y=p.poffy+ir[1]+ir[3]-p.psds; else y=p.poffy+ir[1]-p.psds; if(y+sr[3]>cb) y=cb-sr[3]; if(y<ct) y=ct; return [x,y]; } function stbuf(s) { if(s) { var i=new Image(); st_ims[st_ims.length]=i; i.src=s; } return s; } function stgsrc(s,m,f) { if(s=='') return f ? m.mbnk : ''; var sr=s.toLowerCase(); if(sr.indexOf('http://')==0||(sr.indexOf(':')==1&&sr.charCodeAt(0)>96&&sr.charCodeAt(0)<123)||sr.indexOf('ftp://')==0||sr.indexOf('/')==0||sr.indexOf('gopher')==0) return s; else return m.mweb+s; } function showFloatMenuAt(n,x,y) { if(nDM) { var m=stmenu(n); if(m&&typeof(m.ready)!="undefined"&&m.mtyp==2&&m.ps.length&&!m.ps[0].issh) { ststxy(m,[x,y]); stshow(m.ps[0]); } } } function hideMenu(n) { var m=stmenu(n); var w=m.sfrm; if(w!=window) m=w.stmenu(n); if(m.hdid) { w.clearTimeout(m.hdid); m.hdid=null; } w.sthdall(m,1); } function stmenu(n) { for(var l=st_ms.length-1;l>=0;l--) if(st_ms[l].mnam==n) return st_ms[l]; return null; } function stgtsub(i) { var m=stgme(i); if(m.mcfb) { var w=m.tfrm; if(i.ppi||w==window) return stgsub(i); if(typeof(w.stmenu)!="undefined"&&typeof(w.stgsub)!="undefined") { m=w.stmenu(m.mnam); return w.stgsub(m.ps[i.ppi].is[i.iti]); } } return null; } function stgirc(i) { var m=stgme(i); var w=m.sfrm; if(i.ppi||w==window) return stgrc(i); m=w.stmenu(m.mnam); var rc=w.stgrc(m.ps[0].is[i.iti]); var x=rc[0]-w.stgcl(); var y=rc[1]-w.stgct(); switch(m.mcfd) { case 0:y-=w.stgch();break; case 1:y+=stgch();break; case 2:x-=w.stgcw();break; case 3:x+=stgcw();break; } x+=stgcl()+m.mcfx; y+=stgct()+m.mcfy; return [x,y,rc[2],rc[3]]; } function stgtgt(i) { if(i.itgt=="_self") return window; else if(i.itgt=="_parent") return parent; else if(i.itgt=="_top") return top; else for(var co=window;co!=co.parent;co=co.parent) if(typeof(co.parent.frames[i.itgt])!="undefined") return co.parent.frames[i.itgt]; return null; } function stgfrm(m) { var a=m.mcff.split("."); var w="top"; for(var l=0;l<a.length;l++) if(typeof(eval(w+"."+a[l]))=="undefined") return null; return eval("top."+m.mcff); } function stfrm(m) { if(m.mcff) { var w=stgfrm(m); if(w&&typeof(w.st_load)!="undefined"&&w.st_load) { var t=w.stmenu(m.mnam); if(typeof(t)=="object"&&t) { if(!m.cfrm||!t.cfrm) { if(t.mhdd<1000) m.mhdd=t.mhdd=1000; hideMenu(m.mnam); m.sfrm=t.sfrm=window; m.tfrm=t.tfrm=w; m.cfrm=t.cfrm=1; } m.mcfb=1; return; } } m.mcfb=m.mcfn; m.tfrm=window; } else { var w=m.sfrm; if(w==window) return; else if(typeof(w.st_load)!="undefined"&&w.st_load) { var s=w.stmenu(m.mnam); if(typeof(s)=="object"&&s) if(s.cfrm) return; } m.sfrm=window; var p=m.ps[0]; for(var l=0;l<p.is.length;++l) sthdit(p.is[l]); } }
zzlydm-fbbs
html/images/stm31.js
JavaScript
gpl3
33,019
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic -Werror") add_definitions(-D_XOPEN_SOURCE=500) add_library(fbbs STATIC util.c string.c file.c hash.c mmap.c socket.c pass.c cache.c cfg.c pool.c user.c time.c)
zzlydm-fbbs
lib/CMakeLists.txt
CMake
gpl3
218
#include <wchar.h> #include <string.h> #include "fbbs/string.h" #if 0 /** * Convert string to lower case. * @param dst result string. * @param src the string to convert. * @return the converted string. * @note 'dst' should have enough space to hold 'src'. */ char *strtolower(char *dst, const char *src) { char *ret = dst; if (dst == NULL || src == NULL) return NULL; while (*src != '\0') *dst++ = tolower(*src++); *dst = '\0'; return ret; } /** * Convert string to upper case. * @param dst result string. * @param src the string to convert. * @return the converted string. * @note 'dst' should have enough space to hold 'src'. */ char *strtoupper(char *dst, const char *src) { char *ret = dst; if (dst == NULL || src == NULL) return NULL; while (*src != '\0') *dst++ = toupper(*src++); *dst = '\0'; return ret; } // Compare string 's1' against 's2' and differences in case are ignored. // No more than 'n' characters are compared. // This function supports zh_CN.GBK. int strncasecmp_gbk(const char *s1, const char *s2, int n) { register int c1, c2, l = 0; while (*s1 && *s2 && l < n) { c1 = tolower(*s1++); c2 = tolower(*s2++); if (c1 != c2) return (c1 - c2); ++l; if (c1 & 0x80) { if (*s1++ == *s2++) ++l; else return (*--s1 - *--s2); } } if (l == n) return 0; else return -1; } // Search string 'haystack' for a substring 'needle' // and differences in case are ignored. // This function supports zh_CN.GBK. char *strcasestr_gbk(const char *haystack, const char *needle) { int i, nlength, hlength; if (haystack == NULL || needle == NULL) return NULL; nlength = strlen(needle); hlength = strlen(haystack); if (nlength > hlength) return NULL; if (hlength <= 0) return NULL; if (nlength <= 0) return (char *)haystack; for (i = 0; i <= (hlength - nlength); i++) { if (strncasecmp_gbk(haystack + i, needle, nlength) == 0) return (char *)(haystack + i); if (haystack[i] & 0x80) i++; } return NULL; } // Eliminate ANSI escape codes from 'src' and store it in 'dst'. // 'src' and 'dst' can be the same. char *ansi_filter(char *dst, const char *src) { char *ret = dst; int flag = 0; if (dst == NULL || src == NULL) return NULL; for (; *src != '\0'; src++) { if (*src == '\033') flag = 1; else if (flag == 0) *dst++ = *src; else if (isalpha(*src)) flag = 0; } *dst = '\0'; return ret; } // Truncates 'str' to 'len' chars ended with ".." or "...". // Do nothing if 'str' is less than or equal to 'len' chars. int ellipsis(char *str, int len) { int i = 0, inGBK = 0; char *ptr = str; if (len < 0 || str == NULL) return 0; if (len < 3) { str[len] = '\0'; return 1; } i = len - 3; while (*ptr != '\0' && i) { if (inGBK) { inGBK = 0; } else if (*ptr & 0x80) inGBK = 1; ++ptr; --i; } i = 3; while(*ptr++ != '\0' && --i) ; if(*ptr != '\0' && !i){ str[len] = '\0'; *--ptr = '.'; *--ptr = '.'; if(!inGBK && *--ptr & 0x80) *ptr = '.'; } return 1; } // Removes trailing chars whose ASCII code is less than 0x20. char *rtrim(char *str){ if (str == NULL) return NULL; size_t len = strlen(str); unsigned char *ustr = (unsigned char *)str; unsigned char *ptr = ustr + len; while (*ptr <= 0x20 && ptr >= ustr) { --ptr; } *++ptr = '\0'; return str; } #endif // Removes both leading and trailing chars // whose ASCII code is less than 0x20. char *trim(char *str) { if (str == NULL) return NULL; size_t len = strlen(str); unsigned char *ustr = (unsigned char *)str; unsigned char *right = ustr + len; while (*right <= 0x20 && right >= ustr) { --right; } *++right = '\0'; unsigned char *left = ustr; while (*left <= 0x20 && *left != '\0') ++left; if (left != ustr) memmove(ustr, left, right - left + 1); return str; } /** * Safe string copy. * @param[out] dst The destination string. * @param[in] src The source string. * @param[in] size At most size-1 characters will be copied. * @return Characters copied, excluding terminating NUL. */ size_t strlcpy(char *dst, const char *src, size_t size) { size_t n = size; while (*src != '\0' && --n != 0) { *dst++ = *src++; } *dst = '\0'; if (n == size) return 0; return size - n - 1; } #if 0 void strtourl(char *url, const char *str) { char c, h; while ((c = *str) != '\0') { if (isprint(c) && c != ' ' && c!= '%') { *url++ = c; } else { *url++ = '%'; // hexadecimal representation h = c / 16; *url++ = h > 9 ? 'A' - 10 + h : '0' + h; h = c % 16; *url++ = h > 9 ? 'A' - 10 + h : '0' + h; } ++str; } *url = '\0'; } void strappend(char **dst, size_t *size, const char *src) { size_t len = strlcpy(*dst, src, *size); if (len >= *size) len = *size; *dst += len; *size -= len; } #endif /** * Get number of column positions of a multibyte string. * Non-printable characters are treated as zero-width. * @param s The multibyte string. * @return Number of columns of the string. */ size_t mbwidth(const char *s) { int ret, w; size_t width = 0; wchar_t wc; mbstate_t state; memset(&state, 0, sizeof(state)); while (*s != '\0') { ret = mbrtowc(&wc, s, MB_CUR_MAX, &state); if (ret >= (size_t)-2) { return width; } else { w = wcwidth(wc); if (w == -1) w = 0; width += w; s += ret; } } return width; }
zzlydm-fbbs
lib/string.c
C
gpl3
5,327
#include <stdio.h> #include <string.h> #include "fbbs/cfg.h" #include "fbbs/string.h" enum { CONFIG_MAX_KEYS = 64, CONFIG_MAX_LINE_LEN = 256, CONFIG_BUFFER_SIZE = 3584, }; int config_init(config_t *cfg) { void *ptr = malloc((sizeof(*cfg->keys) + sizeof(*cfg->vals)) * CONFIG_MAX_KEYS + CONFIG_BUFFER_SIZE); if (!ptr) return -1; cfg->keys = ptr; cfg->vals = cfg->keys + CONFIG_MAX_KEYS; cfg->buf = (char *)(cfg->vals + CONFIG_MAX_KEYS); cfg->pairs = 0; cfg->cur = 0; return 0; } void config_destroy(config_t *cfg) { if (cfg->keys) free(cfg->keys); } static int _config_add(config_t *cfg, const char *key, const char *val) { if (!key || !val) return -1; int klen = strlen(key); int vlen = strlen(val); if (cfg->cur + klen + vlen + 2 > CONFIG_BUFFER_SIZE) return -1; cfg->keys[cfg->pairs] = cfg->cur; strcpy(cfg->buf + cfg->cur, key); cfg->cur += klen + 1; cfg->vals[cfg->pairs] = cfg->cur; strcpy(cfg->buf + cfg->cur, val); cfg->cur += vlen + 1; ++cfg->pairs; return 0; } int config_load(config_t *cfg, const char *file) { FILE *fp = fopen(file, "r"); if (!fp) return -1; char buf[CONFIG_MAX_LINE_LEN]; while (fgets(buf, sizeof(buf), fp)) { if (buf[0] == '#') continue; const char *key = trim(strtok(buf, "=\n")); const char *val = trim(strtok(NULL, "=\n")); _config_add(cfg, key, val); } fclose(fp); return 0; } const char *config_get(const config_t *cfg, const char *key) { for (int i = 0; i < cfg->pairs; ++i) { if (streq(cfg->buf + cfg->keys[i], key)) return cfg->buf + cfg->vals[i]; } return NULL; }
zzlydm-fbbs
lib/cfg.c
C
gpl3
1,578
#include <stdlib.h> #include <unistd.h> #include "fbbs/pool.h" #include "fbbs/util.h" enum { ALIGNMENT = sizeof(unsigned long), }; static int _max_pool_alloc = 0; /** * Align pointer. * @param ptr The pointer to be aligned. * @return The aligned pointer. */ static inline void *_align_ptr(void *ptr) { return (void *)(((uintptr_t)ptr + ALIGNMENT - 1) & ~(ALIGNMENT - 1)); } /** * Create a memory pool. * @param size Size of each memory block. * @return A pointer to created pool, NULL on error. */ pool_t *pool_create(size_t size) { if (!_max_pool_alloc) _max_pool_alloc = sysconf(_SC_PAGESIZE); if (size <= sizeof(pool_block_t)) return NULL; pool_block_t *b = malloc(size); if (!b) return NULL; b->last = _align_ptr((uchar_t *)b + sizeof(*b)); b->end = (uchar_t *)b + size; b->next = NULL; pool_t *p = (pool_t *) b->last; b->last = (uchar_t *)p + sizeof(*p); p->head = b; p->large = NULL; return p; } /** * Clear memory pool. * Large memories are freed. Blocks are cleared. * @param p The memory pool. */ void pool_clear(pool_t *p) { for (pool_large_t *l = p->large; l; l = l->next) { if (l->ptr) free(l->ptr); } p->large = NULL; for (pool_block_t *b = p->head->next; b; b = b->next) { b->last = (uchar_t *)b + sizeof(*b); } p->head->last = _align_ptr((uchar_t *)(p->head) + sizeof(pool_block_t)); p->head->last += sizeof(*p); } /** * Destroy memory pool. * @param p The memory pool. */ void pool_destroy(pool_t *p) { for (pool_large_t *l = p->large; l; l = l->next) { if (l->ptr) free(l->ptr); } p->large = NULL; pool_block_t *b = p->head, *next; while (b) { next = b->next; free(b); b = next; } } /** * Allocate memory from pool by creating a new block. * @param p The pool to allocate from. * @param size Required memory size. * @return On success, a pointer to allocated space, NULL otherwise. */ static void *_pool_alloc_block(pool_t *p, size_t size) { size_t bsize = p->head->end - (uchar_t *)(p->head); pool_block_t *b = malloc(bsize); if (!b) return NULL; b->last = (uchar_t *)b + sizeof(*b); b->end = (uchar_t *)b + bsize; b->next = p->head->next; p->head->next = b; uchar_t *ret = _align_ptr(b->last); b->last = ret + size; return ret; } /** * Allocate a large memory directly. * @param p The memory pool. * @param size Required memory size. * @return On success, a pointer to allocated space, NULL otherwise. */ static void *_pool_alloc_large(pool_t *p, size_t size) { pool_large_t *l; l = pool_alloc(p, sizeof(*l)); if (!l) return NULL; l->next = p->large; p->large = l; l->ptr = malloc(size); return l->ptr; } /** * Allocate memory from pool. * @param p The pool to allocate from. * @param size Required memory size. * @return On success, a pointer to allocated space, NULL otherwise. */ void *pool_alloc(pool_t *p, size_t size) { uchar_t *ret; pool_block_t *b; if (size < _max_pool_alloc) { b = p->head; do { ret = _align_ptr(b->last); if (b->end - ret >= size) { b->last = (uchar_t *)ret + size; return ret; } b = b->next; } while (b); return _pool_alloc_block(p, size); } return _pool_alloc_large(p, size); }
zzlydm-fbbs
lib/pool.c
C
gpl3
3,182
#include <stdlib.h> #include <string.h> #include "fbbs/hash.h" /** * Default hash funtion (djb algorithm). * @param [in] key The key. * @param [in,out] klen The length of the key. See ::hash_func_t. * @return The calculated hash value. */ unsigned int hash_func_default(const char *key, unsigned int *klen) { unsigned int value = 0; if (*klen == HASH_KEY_STRING) { const char *str = key; while (*str != '\0') { value += value * 33 + *str++; } *klen = str - key; } else { unsigned int len = *klen; while (len-- > 0) { value += value * 33 + *key++; } } return value; } /** * Create a new hash table. * @param [out] ht Hash table to create. * @param [in] max Max slot number (0-based). Set to default if 0. * @param [in] func hash function. Use default if NULL. * @return 0 on success, -1 on error. * @note max must be 2^n - 1, n = 1, 2, 3, ... */ int hash_create(hash_t *ht, unsigned int max, hash_func_t func) { if (max == 0) max = HASH_DEFAULT_MAX; size_t bytes = sizeof(hash_entry_t *) * (max + 1); hash_entry_t **array = malloc(bytes); if (array == NULL) return -1; memset(array, 0, bytes); ht->count = 0; ht->max = max; ht->array = array; ht->free = NULL; if (func == NULL) ht->func = hash_func_default; else ht->func = func; return 0; } /** * Expand an existing hash table. * @param [in, out] ht Hash table to be expanded. * @return 0 on success, -1 on error. */ static int hash_expand(hash_t *ht) { unsigned int max = 2 * ht->max + 1; size_t bytes = sizeof(hash_entry_t *) * (max + 1); hash_entry_t **array = malloc(bytes); if (array == NULL) return -1; memset(array, 0, bytes); unsigned int i; for (i = 0; i <= ht->max; ++i) { hash_entry_t *entry = ht->array[i]; while (entry) { hash_entry_t **ptr = array + (entry->hash & max); hash_entry_t *next = entry->next; entry->next = *ptr; *ptr = entry; entry = next; } } ht->max = max; free(ht->array); ht->array = array; return 0; } /** * Find an entry in a hash table. * @param [in,out] ht The hash table. * @param [in] key The key. * @param [in] klen The length of the key. See ::hash_func_t. * @param [in] val if there is no entry associated with the key and val is not * NULL, the function will allocate a new entry to store the key-value * pair. * @return Pointer to pointer to the entry if found or new entry allocated, * pointer to NULL otherwise. */ static hash_entry_t **find_entry(hash_t *ht, const char *key, unsigned int klen, const void *val) { unsigned int hash = (*ht->func)(key, &klen); hash_entry_t **ptr = ht->array + (hash & ht->max), *entry; for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr) { if (entry->klen == klen && entry->hash == hash && memcmp(entry->key, key, klen) == 0) break; } if (entry || !val) return ptr; if ((entry = ht->free) != NULL) ht->free = entry->next; else entry = malloc(sizeof(*entry)); if (!entry) return NULL; entry->next = NULL; entry->key = key; entry->klen = klen; entry->hash = hash; entry->val = val; *ptr = entry; ht->count++; return ptr; } /** * Put a key-value pair into a hash table. * @param [in,out] ht The hash table. * @param [in] key The key. * @param [in] klen The length of the key. See ::hash_func_t. * @param [in] val The value associated with the key. Delete the pair if NULL. * @return 0 on success, -1 on error. */ int hash_set(hash_t *ht, const void *key, unsigned int klen, const void *val) { hash_entry_t **ptr = find_entry(ht, key, klen, val); if (val) { if (!*ptr) return -1; (*ptr)->val = val; if (ht->count > ht->max) { return hash_expand(ht); } } else { if (*ptr) { // deletion. hash_entry_t *old = *ptr; *ptr = old->next; old->next = ht->free; ht->free = old; ht->count--; } } return 0; } /** * Look up the value associated with a key in a hash table. * @param [in] ht The hash table. * @param [in] key The key. * @param [in] klen The length of the key. See ::hash_func_t. * @return The value associated with the key, NULL if not found. */ void *hash_get(hash_t *ht, const void *key, unsigned int klen) { hash_entry_t **ptr = find_entry(ht, key, klen, NULL); if (*ptr) return (void *)((*ptr)->val); return NULL; } /** * Destroy a hash table. * @param [in,out] ht The hash table. */ void hash_destroy(hash_t *ht) { unsigned int i; hash_entry_t *entry, *next; for (i = 0; i < ht->max; ++i) { entry = ht->array[i]; while (entry) { next = entry->next; free(entry); entry = next; } } entry = ht->free; while (entry) { next = entry->next; free(entry); entry = next; } free(ht->array); } hash_iter_t *hash_next(hash_iter_t *iter) { iter->entry = iter->next; while (!iter->entry) { if (iter->index > iter->ht->max) { free(iter); return NULL; } iter->entry = iter->ht->array[iter->index++]; } iter->next = iter->entry->next; return iter; } hash_iter_t *hash_begin(const hash_t *ht) { hash_iter_t *iter = malloc(sizeof(*iter)); if (!iter) return NULL; iter->ht = ht; iter->index = 0; iter->entry = NULL; iter->next = NULL; return hash_next(iter); }
zzlydm-fbbs
lib/hash.c
C
gpl3
5,170
#include <unistd.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include "fbbs/util.h" #ifndef NSIG #ifdef _NSIG #define NSIG _NSIG #else #define NSIG 65 #endif #endif /** * Daemonize the process. */ void start_daemon(void) { int n, pid; umask(0); // Clear file creation mask. n = getdtablesize(); // Get maximum number of file descriptors. // Fork to ensure not being a process group leader. if ((pid = fork()) < 0) { printf("Cannot fork.\n"); exit(1); } else if (pid != 0) { exit(0); } if (setsid() == -1) exit(1); // Fork again. if ((pid = fork()) < 0) { exit(1); } else if (pid != 0) { exit(0); } // Close all open file descriptors. while (n) close(--n); // Ignore all signals. for (n = 1; n <= NSIG; n++) signal(n, SIG_IGN); } /** * BSD semantic signal(). * @param signum The signal number. * @param handler The signal handler. * @return The signal handler on success, SIG_ERR on error. */ sighandler_t fb_signal(int signum, sighandler_t handler) { struct sigaction act, oact; act.sa_handler = handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (signum == SIGALRM) { #ifdef SA_INTERRUPT act.sa_flags |= SA_INTERRUPT; #endif } else { #ifdef SA_RESTART act.sa_flags |= SA_RESTART; #endif } if (sigaction(signum, &act, &oact) < 0) return SIG_ERR; return oact.sa_handler; } void *fb_malloc(size_t size) { void *ptr = malloc(size); if (!ptr) exit(0); return ptr; }
zzlydm-fbbs
lib/util.c
C
gpl3
1,504
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stddef.h> #include <sys/socket.h> #include <sys/un.h> #include "fbbs/string.h" /** * Create a unix domain dgram socket and then connect to a server. * @param basename The basename of the created socket. * The actual path is suffixed with pid. * @param server The server path. * @return fd if OK, -1 on error. */ int unix_dgram_connect(const char *basename, const char *server) { int fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (fd < 0) return -1; struct sockaddr_un un; memset(&un, 0, sizeof(un)); un.sun_family = AF_UNIX; snprintf(un.sun_path, sizeof(un.sun_path), "%s-%d", basename, getpid()); unlink(un.sun_path); int len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path); if (bind(fd, (struct sockaddr *)&un, len) < 0) { close(fd); return -1; } memset(&un, 0, sizeof(un)); un.sun_family = AF_UNIX; strlcpy(un.sun_path, server, sizeof(un.sun_path)); len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path); if (connect(fd, (struct sockaddr *)&un, len) < 0) { close(fd); return -1; } return fd; } /** * Create and bind a unix datagram socket. * @param name The name of the socket. * @param qlen The maximum length of queue of pending requests. * @return fd if OK, -1 on error. */ int unix_dgram_bind(const char *name, int qlen) { int fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (fd < 0) return -1; unlink(name); struct sockaddr_un un; memset(&un, 0, sizeof(un)); un.sun_family = AF_UNIX; strlcpy(un.sun_path, name, sizeof(un.sun_path)); int len = offsetof(struct sockaddr_un, sun_path) + strlen(name); if (bind(fd, (struct sockaddr *)&un, len) < 0) { close(fd); return -1; } return fd; }
zzlydm-fbbs
lib/socket.c
C
gpl3
1,756
#include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #include <crypt.h> #include <sys/time.h> #include "fbbs/site.h" #ifndef MD5 #ifndef DES /* nor DES, MD5, fatal error!! */ #error "(pass.c) you've not define DES nor MD5, fatal error!!" #endif #endif /** Used in integer-string conversion. */ static const unsigned char itoa64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; /** * Convert a long integer to string. * Every 6 bits of the integer is mapped to a char. * @param s The resulting string. * @param v The long integer. * @param n Number of converted characters. */ static void to64(char *s, long v, int n) { while (--n >= 0) { *s++ = itoa64[v & 0x3f]; v >>= 6; } } /** * Encrypt string. * When using DES, only the first 8 chars in the string are significant. * @param pw The string to be encrypted. * @return The encrypted string. */ const char *generate_passwd(const char *pw) { char salt[10]; struct timeval tv; if (pw == NULL || pw[0] == '\0') return ""; gettimeofday(&tv, NULL); srand(tv.tv_sec % getpid()); #ifdef MD5 /* use MD5 salt */ strncpy(&salt[0], "$1$", 3); to64(&salt[3], random(), 3); to64(&salt[6], tv.tv_usec, 3); salt[8] = '\0'; #endif #ifdef DES /* use DES salt */ to64(&salt[0], random(), 3); to64(&salt[3], tv.tv_usec, 3); to64(&salt[6], tv.tv_sec, 2); salt[8] = '\0'; #endif // When using DES, only the first 8 chars in 'pw' are significant. return crypt(pw, salt); } /** * Checks if the given plain text could be the original text * of encrypted string. * @param pw_crypted The encrypted string. * @param pw_try The plain text. * @return True if match, false otherwise. */ bool check_passwd(const char *pw_crypted, const char *pw_try) { return !strcmp(crypt(pw_try, pw_crypted), pw_crypted); }
zzlydm-fbbs
lib/pass.c
C
gpl3
1,835
#include "fbbs/dbi.h" int get_user_id(db_conn_t *c, const char *name) { db_param_t param[1] = { PARAM_TEXT(name) }; db_res_t *res = db_exec_params(c, "SELECT id FROM users WHERE name = $1", 1, param, true); if (db_res_status(res) != DBRES_TUPLES_OK) return -1; if (db_num_rows(res) > 0) return db_get_integer(res, 0, 0); return 0; }
zzlydm-fbbs
lib/user.c
C
gpl3
347
#include <stdio.h> #include "fbbs/time.h" /** * Convert time to string in specified format. * @param time time to convert. * @param mode The format. * @return converted string. */ const char *date2str(time_t time, int mode) { const char *weeknum[] = { "天", "一", "二", "三", "四", "五", "六" }; const char *engweek[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char str[40] = { '\0' }; struct tm *t = localtime(&time); switch (mode) { case DATE_ZH: snprintf(str, sizeof(str), "%4d年%02d月%02d日%02d:%02d:%02d 星期%s", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, weeknum[t->tm_wday]); break; case DATE_EN: snprintf(str, sizeof(str), "%02d/%02d/%02d %02d:%02d:%02d", t->tm_mon + 1, t->tm_mday, t->tm_year - 100, t->tm_hour, t->tm_min, t->tm_sec); break; case DATE_SHORT: snprintf(str, sizeof(str), "%02d.%02d %02d:%02d", t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min); break; case DATE_ENWEEK: snprintf(str, sizeof(str), "%02d/%02d/%02d %02d:%02d:%02d %3s", t->tm_mon + 1, t->tm_mday, t->tm_year - 100, t->tm_hour, t->tm_min, t->tm_sec, engweek[t->tm_wday]); break; case DATE_RSS: strftime(str, sizeof(str), "%a,%d %b %Y %H:%M:%S %z", t); break; case DATE_XML: default: snprintf(str, sizeof(str), "%4d-%02d-%02dT%02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); break; } return str; }
zzlydm-fbbs
lib/time.c
C
gpl3
1,516
#include <unistd.h> #include "fbbs/cache.h" #include "fbbs/socket.h" #include "fbbs/string.h" typedef struct cache_server_t { int fd; } cache_server_t; static cache_server_t server; /** * Initialize a cache client. * @return 0 if OK, -1 on error. */ int cache_client_init(void) { int fd = unix_dgram_connect(CACHE_CLIENT, CACHE_SERVER); if (fd < 0) return -1; server.fd = fd; return 0; } /** * Submit a cache query and fetch the result. * @param query The query. * @param len Length of the query. * @param result Buffer for the result. * @param size The size of the buffer. * @return Length of the result, -1 on error. */ static int submit_cache_query(const void *query, int len, void *result, int size) { if (write(server.fd, query, len) < 0) return 0; return read(server.fd, result, size); } /** * Client call to verify user password. * @param user User name. * @param passwd The password. * @return True if no error occurs the two match, false otherwise. */ bool verify_user_passwd(const char *user, const char *passwd) { password_query_t query = { .type = PASSWORD_QUERY }; strlcpy(query.username, user, sizeof(query.username)); strlcpy(query.passwd, passwd, sizeof(query.passwd)); password_result_t res; int len = submit_cache_query(&query, sizeof(query), &res, sizeof(res)); if (len == sizeof(res)) return res.match; return false; }
zzlydm-fbbs
lib/cache.c
C
gpl3
1,381
/** @file * Memory mapped I/O. */ #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/file.h> #include "fbbs/file.h" #include "fbbs/mmap.h" enum { MMAP_MINSIZE = 4096, ///< Minimum memory mapped region size. }; /** * Map file associated with file descriptor to memory. * @param[in,out] m pointer to an ::mmap_t struct (should be set properly). * @return 0 on success, -1 on error. * @attention This function is exported only for compatability. It will be * made private sooner or later. */ static int mmap_open_fd(mmap_t *m) { struct stat st; if (m->fd < 0) return -1; if (fb_flock(m->fd, m->lock) < 0) { close(m->fd); return -1; } // Return error if 'file' is not a regular file or has a wrong size. if (fstat(m->fd, &st) < 0 || !S_ISREG(st.st_mode) || st.st_size < 0) { fb_flock(m->fd, LOCK_UN); close(m->fd); return -1; } m->size = st.st_size; m->mflag = MAP_SHARED; // Prevent 0-length mapping error. m->msize = st.st_size > MMAP_MINSIZE ? st.st_size : MMAP_MINSIZE; // Map whole file to memory. m->ptr = mmap(NULL, m->msize, m->prot, m->mflag, m->fd, 0); if (m->ptr != MAP_FAILED) return 0; fb_flock(m->fd, LOCK_UN); close(m->fd); return -1; } /** * Map file to memory and set appropriate lock on it. * @param[in] file file to be mmap'ed. * @param[in,out] m mmap struct pointer. * @return 0 on success, -1 on error. * @note m->oflag should be properly set in advance. */ int mmap_open(const char *file, mmap_t *m) { // Set mmap and lock flags. m->lock = LOCK_EX; if (m->oflag & O_RDWR) { m->prot = PROT_READ | PROT_WRITE; } else if (m->oflag & O_WRONLY) { m->prot = PROT_WRITE; } else { m->prot = PROT_READ; m->lock = LOCK_SH; } m->fd = open(file, m->oflag); return mmap_open_fd(m); } /** * Unmap memory-mapped file. * Related lock is released and file descriptor is closed. * @param[in] m pointer to an ::mmap_t struct. * @return 0 on success, -1 on error. */ int mmap_close(mmap_t *m) { if (m == NULL) return 0; munmap(m->ptr, m->msize); if (m->lock != LOCK_UN) fb_flock(m->fd, LOCK_UN); return close(m->fd); } /** * Change lock on a memory mapped file. * @param[in,out] m pointer to an ::mmap_t struct. * @param[in] lock new lock state. (LOCK_EX LOCK_SH LOCK_UN) */ int mmap_lock(mmap_t *m, int lock) { if (lock == m->lock) return 0; m->lock = lock; return fb_flock(m->fd, lock); }
zzlydm-fbbs
lib/mmap.c
C
gpl3
2,466
#!/usr/bin/env python from setuptools import setup import os import re v = open(os.path.join(os.path.dirname(__file__), 'ibm_db_sa', '__init__.py')) VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1) v.close() readme = os.path.join(os.path.dirname(__file__), 'README.rst') setup( name='ibm_db_sa', version=VERSION, license='Apache License 2.0', description='SQLAlchemy support for IBM Data Servers', author='IBM Application Development Team', author_email='opendev@us.ibm.com', url='http://github.com/zzzeek/ibm_db_sa', keywords='sqlalchemy database interface IBM Data Servers DB2 Informix IDS', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache License 2.0', 'Operating System :: OS Independent', 'Topic :: Databases :: Front-end, middle-tier' ], long_description=open(readme).read(), platforms='All', install_requires=['sqlalchemy>=0.7.3'], packages=['ibm_db_sa'], entry_points={ 'sqlalchemy.dialects': [ 'db2=ibm_db_sa.ibm_db:DB2Dialect_ibm_db', 'db2.ibm_db=ibm_db_sa.ibm_db:DB2Dialect_ibm_db', 'db2.zxjdbc=ibm_db_sa.zxjdbc:DB2Dialect_zxjdbc', 'db2.pyodbc=ibm_db_sa.pyodbc:DB2Dialect_pyodbc', 'db2.zxjdbc400=ibm_db_sa.zxjdbc:AS400Dialect_zxjdbc', 'db2.pyodbc400=ibm_db_sa.pyodbc:AS400Dialect_pyodbc', # older "ibm_db_sa://" style for backwards # compatibility 'ibm_db_sa=ibm_db_sa.ibm_db:DB2Dialect_ibm_db', 'ibm_db_sa.zxjdbc=ibm_db_sa.zxjdbc:DB2Dialect_zxjdbc', 'ibm_db_sa.pyodbc=ibm_db_sa.pyodbc:DB2Dialect_pyodbc', 'ibm_db_sa.zxjdbc400=ibm_db_sa.zxjdbc:AS400Dialect_zxjdbc', 'ibm_db_sa.pyodbc400=ibm_db_sa.pyodbc:AS400Dialect_pyodbc', ] }, zip_safe=False, tests_require=['nose >= 0.11'], )
zzzeek-ibm-db-sa
ibm_db_sa/setup.py
Python
asf20
2,220
# +--------------------------------------------------------------------------+ # | Licensed Materials - Property of IBM | # | | # | (C) Copyright IBM Corporation 2008, 2013. | # +--------------------------------------------------------------------------+ # | This module complies with SQLAlchemy 0.8 and is | # | Licensed under the Apache License, Version 2.0 (the "License"); | # | you may not use this file except in compliance with the License. | # | You may obtain a copy of the License at | # | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable | # | law or agreed to in writing, software distributed under the License is | # | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | # | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Authors: Jaimy Azle, Rahul Priyadarshi | # | Contributors: Mike Bayer | # | Version: 0.3.x | # +--------------------------------------------------------------------------+ from sqlalchemy import util import urllib from sqlalchemy.connectors.pyodbc import PyODBCConnector from .base import _SelectLastRowIDMixin, DB2ExecutionContext, DB2Dialect class DB2ExecutionContext_pyodbc(_SelectLastRowIDMixin, DB2ExecutionContext): pass class DB2Dialect_pyodbc(PyODBCConnector, DB2Dialect): supports_unicode_statements = False supports_native_decimal = True supports_char_length = True supports_native_decimal = False execution_ctx_cls = DB2ExecutionContext_pyodbc pyodbc_driver_name = "IBM DB2 ODBC DRIVER" def create_connect_args(self, url): opts = url.translate_connect_args(username='user') opts.update(url.query) keys = opts query = url.query connect_args = {} for param in ('ansi', 'unicode_results', 'autocommit'): if param in keys: connect_args[param] = util.asbool(keys.pop(param)) if 'odbc_connect' in keys: connectors = [urllib.unquote_plus(keys.pop('odbc_connect'))] else: dsn_connection = 'dsn' in keys or \ ('host' in keys and 'database' not in keys) if dsn_connection: connectors = ['dsn=%s' % (keys.pop('host', '') or \ keys.pop('dsn', ''))] else: port = '' if 'port' in keys and not 'port' in query: port = '%d' % int(keys.pop('port')) database = keys.pop('database', '') connectors = ["DRIVER={%s}" % keys.pop('driver', self.pyodbc_driver_name), 'hostname=%s;port=%s' % (keys.pop('host', ''), port), 'database=%s' % database] user = keys.pop("user", None) if user: connectors.append("uid=%s" % user) connectors.append("pwd=%s" % keys.pop('password', '')) else: connectors.append("trusted_connection=yes") # if set to 'yes', the odbc layer will try to automagically # convert textual data from your database encoding to your # client encoding. this should obviously be set to 'no' if # you query a cp1253 encoded database from a latin1 client... if 'odbc_autotranslate' in keys: connectors.append("autotranslate=%s" % keys.pop("odbc_autotranslate")) connectors.extend(['%s=%s' % (k, v) for k, v in keys.iteritems()]) return [[";".join(connectors)], connect_args] class AS400Dialect_pyodbc(PyODBCConnector, DB2Dialect): supports_unicode_statements = False supports_sane_rowcount = False supports_sane_multi_rowcount = False supports_native_decimal = True supports_char_length = True supports_native_decimal = False pyodbc_driver_name = "IBM DB2 ODBC DRIVER"
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/pyodbc.py
Python
asf20
4,704
# +--------------------------------------------------------------------------+ # | Licensed Materials - Property of IBM | # | | # | (C) Copyright IBM Corporation 2008, 2013. | # +--------------------------------------------------------------------------+ # | This module complies with SQLAlchemy 0.8 and is | # | Licensed under the Apache License, Version 2.0 (the "License"); | # | you may not use this file except in compliance with the License. | # | You may obtain a copy of the License at | # | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable | # | law or agreed to in writing, software distributed under the License is | # | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | # | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Authors: Alex Pitigoi, Abhigyan Agrawal | # | Contributors: Jaimy Azle, Mike Bayer | # | Version: 0.3.x | # +--------------------------------------------------------------------------+ from .base import DB2ExecutionContext, DB2Dialect from sqlalchemy import processors, types as sa_types, util class _IBM_Numeric_ibm_db(sa_types.Numeric): def result_processor(self, dialect, coltype): if self.asdecimal: return None else: return processors.to_float class DB2ExecutionContext_ibm_db(DB2ExecutionContext): def get_lastrowid(self): return self.cursor.last_identity_val class DB2Dialect_ibm_db(DB2Dialect): driver = 'ibm_db_sa' supports_unicode_statements = False supports_sane_rowcount = True supports_sane_multi_rowcount = False supports_native_decimal = False supports_char_length = True execution_ctx_cls = DB2ExecutionContext_ibm_db colspecs = util.update_copy( DB2Dialect.colspecs, { sa_types.Numeric: _IBM_Numeric_ibm_db } ) @classmethod def dbapi(cls): """ Returns: the underlying DBAPI driver module """ import ibm_db_dbi as module return module def _get_server_version_info(self, connection): return connection.connection.server_info() def create_connect_args(self, url): # DSN support through CLI configuration (../cfg/db2cli.ini), # while 2 connection attributes are mandatory: database alias # and UID (in support to current schema), all the other # connection attributes (protocol, hostname, servicename) are # provided through db2cli.ini database catalog entry. Example # 1: ibm_db_sa:///<database_alias>?UID=db2inst1 or Example 2: # ibm_db_sa:///?DSN=<database_alias>;UID=db2inst1 if not url.host: dsn = url.database uid = url.username pwd = url.password return ((dsn, uid, pwd, '', ''), {}) else: # Full URL string support for connection to remote data servers dsn_param = ['DRIVER={IBM DB2 ODBC DRIVER}'] dsn_param.append('DATABASE=%s' % url.database) dsn_param.append('HOSTNAME=%s' % url.host) dsn_param.append('PROTOCOL=TCPIP') if url.port: dsn_param.append('PORT=%s' % url.port) if url.username: dsn_param.append('UID=%s' % url.username) if url.password: dsn_param.append('PWD=%s' % url.password) dsn = ';'.join(dsn_param) dsn += ';' return ((dsn, url.username, '', '', ''), {}) # Retrieves current schema for the specified connection object def _get_default_schema_name(self, connection): return self.normalize_name(connection.connection.get_current_schema()) # Checks if the DB_API driver error indicates an invalid connection def is_disconnect(self, ex, connection, cursor): if isinstance(ex, (self.dbapi.ProgrammingError, self.dbapi.OperationalError)): return 'Connection is not active' in str(ex) or \ 'connection is no longer active' in str(ex) or \ 'Connection Resource cannot be found' in str(ex) else: return False dialect = DB2Dialect_ibm_db
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/ibm_db.py
Python
asf20
4,851
# +--------------------------------------------------------------------------+ # | Licensed Materials - Property of IBM | # | | # | (C) Copyright IBM Corporation 2008, 2013. | # +--------------------------------------------------------------------------+ # | This module complies with SQLAlchemy 0.8 and is | # | Licensed under the Apache License, Version 2.0 (the "License"); | # | you may not use this file except in compliance with the License. | # | You may obtain a copy of the License at | # | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable | # | law or agreed to in writing, software distributed under the License is | # | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | # | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Authors: Alex Pitigoi, Abhigyan Agrawal | # | Contributors: Jaimy Azle, Mike Bayer | # | Version: 0.3.x | # +--------------------------------------------------------------------------+ """Support for IBM DB2 database """ import datetime from sqlalchemy import types as sa_types from sqlalchemy import schema as sa_schema from sqlalchemy import util from sqlalchemy.sql import compiler from sqlalchemy.engine import default from . import reflection as ibm_reflection from sqlalchemy.types import BLOB, CHAR, CLOB, DATE, DATETIME, INTEGER,\ SMALLINT, BIGINT, DECIMAL, NUMERIC, REAL, TIME, TIMESTAMP,\ VARCHAR # as documented from: # http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0001095.htm RESERVED_WORDS = set( ['activate', 'disallow', 'locale', 'result', 'add', 'disconnect', 'localtime', 'result_set_locator', 'after', 'distinct', 'localtimestamp', 'return', 'alias', 'do', 'locator', 'returns', 'all', 'double', 'locators', 'revoke', 'allocate', 'drop', 'lock', 'right', 'allow', 'dssize', 'lockmax', 'rollback', 'alter', 'dynamic', 'locksize', 'routine', 'and', 'each', 'long', 'row', 'any', 'editproc', 'loop', 'row_number', 'as', 'else', 'maintained', 'rownumber', 'asensitive', 'elseif', 'materialized', 'rows', 'associate', 'enable', 'maxvalue', 'rowset', 'asutime', 'encoding', 'microsecond', 'rrn', 'at', 'encryption', 'microseconds', 'run', 'attributes', 'end', 'minute', 'savepoint', 'audit', 'end-exec', 'minutes', 'schema', 'authorization', 'ending', 'minvalue', 'scratchpad', 'aux', 'erase', 'mode', 'scroll', 'auxiliary', 'escape', 'modifies', 'search', 'before', 'every', 'month', 'second', 'begin', 'except', 'months', 'seconds', 'between', 'exception', 'new', 'secqty', 'binary', 'excluding', 'new_table', 'security', 'bufferpool', 'exclusive', 'nextval', 'select', 'by', 'execute', 'no', 'sensitive', 'cache', 'exists', 'nocache', 'sequence', 'call', 'exit', 'nocycle', 'session', 'called', 'explain', 'nodename', 'session_user', 'capture', 'external', 'nodenumber', 'set', 'cardinality', 'extract', 'nomaxvalue', 'signal', 'cascaded', 'fenced', 'nominvalue', 'simple', 'case', 'fetch', 'none', 'some', 'cast', 'fieldproc', 'noorder', 'source', 'ccsid', 'file', 'normalized', 'specific', 'char', 'final', 'not', 'sql', 'character', 'for', 'null', 'sqlid', 'check', 'foreign', 'nulls', 'stacked', 'close', 'free', 'numparts', 'standard', 'cluster', 'from', 'obid', 'start', 'collection', 'full', 'of', 'starting', 'collid', 'function', 'old', 'statement', 'column', 'general', 'old_table', 'static', 'comment', 'generated', 'on', 'stay', 'commit', 'get', 'open', 'stogroup', 'concat', 'global', 'optimization', 'stores', 'condition', 'go', 'optimize', 'style', 'connect', 'goto', 'option', 'substring', 'connection', 'grant', 'or', 'summary', 'constraint', 'graphic', 'order', 'synonym', 'contains', 'group', 'out', 'sysfun', 'continue', 'handler', 'outer', 'sysibm', 'count', 'hash', 'over', 'sysproc', 'count_big', 'hashed_value', 'overriding', 'system', 'create', 'having', 'package', 'system_user', 'cross', 'hint', 'padded', 'table', 'current', 'hold', 'pagesize', 'tablespace', 'current_date', 'hour', 'parameter', 'then', 'current_lc_ctype', 'hours', 'part', 'time', 'current_path', 'identity', 'partition', 'timestamp', 'current_schema', 'if', 'partitioned', 'to', 'current_server', 'immediate', 'partitioning', 'transaction', 'current_time', 'in', 'partitions', 'trigger', 'current_timestamp', 'including', 'password', 'trim', 'current_timezone', 'inclusive', 'path', 'type', 'current_user', 'increment', 'piecesize', 'undo', 'cursor', 'index', 'plan', 'union', 'cycle', 'indicator', 'position', 'unique', 'data', 'inherit', 'precision', 'until', 'database', 'inner', 'prepare', 'update', 'datapartitionname', 'inout', 'prevval', 'usage', 'datapartitionnum', 'insensitive', 'primary', 'user', 'date', 'insert', 'priqty', 'using', 'day', 'integrity', 'privileges', 'validproc', 'days', 'intersect', 'procedure', 'value', 'db2general', 'into', 'program', 'values', 'db2genrl', 'is', 'psid', 'variable', 'db2sql', 'isobid', 'query', 'variant', 'dbinfo', 'isolation', 'queryno', 'vcat', 'dbpartitionname', 'iterate', 'range', 'version', 'dbpartitionnum', 'jar', 'rank', 'view', 'deallocate', 'java', 'read', 'volatile', 'declare', 'join', 'reads', 'volumes', 'default', 'key', 'recovery', 'when', 'defaults', 'label', 'references', 'whenever', 'definition', 'language', 'referencing', 'where', 'delete', 'lateral', 'refresh', 'while', 'dense_rank', 'lc_ctype', 'release', 'with', 'denserank', 'leave', 'rename', 'without', 'describe', 'left', 'repeat', 'wlm', 'descriptor', 'like', 'reset', 'write', 'deterministic', 'linktype', 'resignal', 'xmlelement', 'diagnostics', 'local', 'restart', 'year', 'disable', 'localdate', 'restrict', 'years', '', 'abs', 'grouping', 'regr_intercept', 'are', 'int', 'regr_r2', 'array', 'integer', 'regr_slope', 'asymmetric', 'intersection', 'regr_sxx', 'atomic', 'interval', 'regr_sxy', 'avg', 'large', 'regr_syy', 'bigint', 'leading', 'rollup', 'blob', 'ln', 'scope', 'boolean', 'lower', 'similar', 'both', 'match', 'smallint', 'ceil', 'max', 'specifictype', 'ceiling', 'member', 'sqlexception', 'char_length', 'merge', 'sqlstate', 'character_length', 'method', 'sqlwarning', 'clob', 'min', 'sqrt', 'coalesce', 'mod', 'stddev_pop', 'collate', 'module', 'stddev_samp', 'collect', 'multiset', 'submultiset', 'convert', 'national', 'sum', 'corr', 'natural', 'symmetric', 'corresponding', 'nchar', 'tablesample', 'covar_pop', 'nclob', 'timezone_hour', 'covar_samp', 'normalize', 'timezone_minute', 'cube', 'nullif', 'trailing', 'cume_dist', 'numeric', 'translate', 'current_default_transform_group', 'octet_length', 'translation', 'current_role', 'only', 'treat', 'current_transform_group_for_type', 'overlaps', 'true', 'dec', 'overlay', 'uescape', 'decimal', 'percent_rank', 'unknown', 'deref', 'percentile_cont', 'unnest', 'element', 'percentile_disc', 'upper', 'exec', 'power', 'var_pop', 'exp', 'real', 'var_samp', 'false', 'recursive', 'varchar', 'filter', 'ref', 'varying', 'float', 'regr_avgx', 'width_bucket', 'floor', 'regr_avgy', 'window', 'fusion', 'regr_count', 'within']) class _IBM_Boolean(sa_types.Boolean): def result_processor(self, dialect, coltype): def process(value): if value is None: return None else: return bool(value) return process def bind_processor(self, dialect): def process(value): if value is None: return None elif bool(value): return '1' else: return '0' return process class _IBM_Date(sa_types.Date): def result_processor(self, dialect, coltype): def process(value): if value is None: return None if isinstance(value, datetime.datetime): value = datetime.date(value.year, value.month, value.day) return value return process def bind_processor(self, dialect): def process(value): if value is None: return None if isinstance(value, datetime.datetime): value = datetime.date(value.year, value.month, value.day) return str(value) return process class DOUBLE(sa_types.Numeric): __visit_name__ = 'DOUBLE' class LONGVARCHAR(sa_types.VARCHAR): __visit_name_ = 'LONGVARCHAR' class DBCLOB(sa_types.CLOB): __visit_name__ = "DBCLOB" class GRAPHIC(sa_types.CHAR): __visit_name__ = "GRAPHIC" class VARGRAPHIC(sa_types.Unicode): __visit_name__ = "VARGRAPHIC" class LONGVARGRAPHIC(sa_types.UnicodeText): __visit_name__ = "LONGVARGRAPHIC" class XML(sa_types.Text): __visit_name__ = "XML" colspecs = { sa_types.Boolean: _IBM_Boolean, sa_types.Date: _IBM_Date, # really ? # sa_types.Unicode: DB2VARGRAPHIC } ischema_names = { 'BLOB': BLOB, 'CHAR': CHAR, 'CHARACTER': CHAR, 'CLOB': CLOB, 'DATE': DATE, 'DATETIME': DATETIME, 'INTEGER': INTEGER, 'SMALLINT': SMALLINT, 'BIGINT': BIGINT, 'DECIMAL': DECIMAL, 'NUMERIC': NUMERIC, 'REAL': REAL, 'DOUBLE': DOUBLE, 'TIME': TIME, 'TIMESTAMP': TIMESTAMP, 'VARCHAR': VARCHAR, 'LONGVARCHAR': LONGVARCHAR, 'XML': XML, 'GRAPHIC': GRAPHIC, 'VARGRAPHIC': VARGRAPHIC, 'LONGVARGRAPHIC': LONGVARGRAPHIC, 'DBCLOB': DBCLOB } class DB2TypeCompiler(compiler.GenericTypeCompiler): def visit_TIMESTAMP(self, type_): return "TIMESTAMP" def visit_DATE(self, type_): return "DATE" def visit_TIME(self, type_): return "TIME" def visit_DATETIME(self, type_): return self.visit_TIMESTAMP(type_) def visit_SMALLINT(self, type_): return "SMALLINT" def visit_INT(self, type_): return "INT" def visit_BIGINT(self, type_): return "BIGINT" def visit_REAL(self, type_): return "REAL" def visit_XML(self, type_): return "XML" def visit_CLOB(self, type_): return "CLOB" def visit_BLOB(self, type_): return "BLOB(1M)" if type_.length in (None, 0) else \ "BLOB(%(length)s)" % {'length': type_.length} def visit_DBCLOB(self, type_): return "DBCLOB(1M)" if type_.length in (None, 0) else \ "DBCLOB(%(length)s)" % {'length': type_.length} def visit_VARCHAR(self, type_): return "VARCHAR(%(length)s)" % {'length': type_.length} def visit_LONGVARCHAR(self, type_): return "LONG VARCHAR" def visit_VARGRAPHIC(self, type_): return "VARGRAPHIC(%(length)s)" % {'length': type_.length} def visit_LONGVARGRAPHIC(self, type_): return "LONG VARGRAPHIC" def visit_CHAR(self, type_): return "CHAR" if type_.length in (None, 0) else \ "CHAR(%(length)s)" % {'length': type_.length} def visit_GRAPHIC(self, type_): return "GRAPHIC" if type_.length in (None, 0) else \ "GRAPHIC(%(length)s)" % {'length': type_.length} def visit_DECIMAL(self, type_): if not type_.precision: return "DECIMAL(31, 0)" elif not type_.scale: return "DECIMAL(%(precision)s, 0)" % {'precision': type_.precision} else: return "DECIMAL(%(precision)s, %(scale)s)" % { 'precision': type_.precision, 'scale': type_.scale} def visit_numeric(self, type_): return self.visit_DECIMAL(type_) def visit_datetime(self, type_): return self.visit_TIMESTAMP(type_) def visit_date(self, type_): return self.visit_DATE(type_) def visit_time(self, type_): return self.visit_TIME(type_) def visit_integer(self, type_): return self.visit_INT(type_) def visit_boolean(self, type_): return self.visit_SMALLINT(type_) def visit_float(self, type_): return self.visit_REAL(type_) def visit_unicode(self, type_): return self.visit_VARGRAPHIC(type_) def visit_unicode_text(self, type_): return self.visit_LONGVARGRAPHIC(type_) def visit_string(self, type_): return self.visit_VARCHAR(type_) def visit_TEXT(self, type_): return self.visit_CLOB(type_) def visit_large_binary(self, type_): return self.visit_BLOB(type_) class DB2Compiler(compiler.SQLCompiler): def visit_now_func(self, fn, **kw): return "CURRENT_TIMESTAMP" def visit_mod_binary(self, binary, operator, **kw): return "mod(%s, %s)" % (self.process(binary.left), self.process(binary.right)) def limit_clause(self, select): if select._limit is not None: return " FETCH FIRST %s ROWS ONLY" % select._limit else: return "" def visit_sequence(self, sequence): return "NEXT VALUE FOR %s" % sequence.name def default_from(self): # DB2 uses SYSIBM.SYSDUMMY1 table for row count return " FROM SYSIBM.SYSDUMMY1" #def visit_function(self, func, result_map=None, **kwargs): # TODO: this is wrong but need to know what DB2 is expecting here # if func.name.upper() == "LENGTH": # return "LENGTH('%s')" % func.compile().params[func.name + '_1'] # else: # return compiler.SQLCompiler.visit_function(self, func, **kwargs) def visit_cast(self, cast, **kw): type_ = cast.typeclause.type # TODO: verify that CAST shouldn't be called with # other types, I was able to CAST against VARCHAR # for example if isinstance(type_, ( sa_types.DateTime, sa_types.Date, sa_types.Time, sa_types.DECIMAL)): return super(DB2Compiler, self).visit_cast(cast, **kw) else: return self.process(cast.clause) def get_select_precolumns(self, select): if isinstance(select._distinct, basestring): return select._distinct.upper() + " " elif select._distinct: return "DISTINCT " else: return "" def visit_join(self, join, asfrom=False, **kwargs): # NOTE: this is the same method as that used in mysql/base.py # to render INNER JOIN return ''.join( (self.process(join.left, asfrom=True, **kwargs), (join.isouter and " LEFT OUTER JOIN " or " INNER JOIN "), self.process(join.right, asfrom=True, **kwargs), " ON ", self.process(join.onclause, **kwargs))) class DB2DDLCompiler(compiler.DDLCompiler): def get_column_specification(self, column, **kw): col_spec = [self.preparer.format_column(column)] col_spec.append(self.dialect.type_compiler.process(column.type)) # column-options: "NOT NULL" if not column.nullable or column.primary_key: col_spec.append('NOT NULL') # default-clause: default = self.get_column_default_string(column) if default is not None: col_spec.append('WITH DEFAULT') col_spec.append(default) if column is column.table._autoincrement_column: col_spec.append('GENERATED BY DEFAULT') col_spec.append('AS IDENTITY') col_spec.append('(START WITH 1)') column_spec = ' '.join(col_spec) return column_spec def define_constraint_cascades(self, constraint): text = "" if constraint.ondelete is not None: text += " ON DELETE %s" % constraint.ondelete if constraint.onupdate is not None: util.warn( "DB2 does not support UPDATE CASCADE for foreign keys.") return text def visit_drop_index(self, drop, **kw): return "\nDROP INDEX %s" % ( self.preparer.quote( self._index_identifier(drop.element.name), drop.element.quote) ) def visit_drop_constraint(self, drop, **kw): constraint = drop.element if isinstance(constraint, sa_schema.ForeignKeyConstraint): qual = "FOREIGN KEY " const = self.preparer.format_constraint(constraint) elif isinstance(constraint, sa_schema.PrimaryKeyConstraint): qual = "PRIMARY KEY " const = "" elif isinstance(constraint, sa_schema.UniqueConstraint): qual = "INDEX " const = self.preparer.format_constraint(constraint) else: qual = "" const = self.preparer.format_constraint(constraint) return "ALTER TABLE %s DROP %s%s" % \ (self.preparer.format_table(constraint.table), qual, const) class DB2IdentifierPreparer(compiler.IdentifierPreparer): reserved_words = RESERVED_WORDS illegal_initial_characters = set(xrange(0, 10)).union(["_", "$"]) class DB2ExecutionContext(default.DefaultExecutionContext): def fire_sequence(self, seq, type_): return self._execute_scalar("SELECT NEXTVAL FOR " + self.dialect.identifier_preparer.format_sequence(seq) + " FROM SYSIBM.SYSDUMMY1", type_) class _SelectLastRowIDMixin(object): _select_lastrowid = False _lastrowid = None def getlastrowid(self): return self._lastrowid def pre_exec(self): if self.isinsert: tbl = self.compiled.statement.table seq_column = tbl._autoincrement_column insert_has_sequence = seq_column is not None self._select_lastrowid = insert_has_sequence and \ not self.compiled.returning and \ not self.compiled.inline def post_exec(self): conn = self.root_connection if self._select_lastrowid: conn._cursor_execute(self.cursor, "SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1", (), self) row = self.cursor.fetchall()[0] if row[0] is not None: self._lastrowid = int(row[0]) class DB2Dialect(default.DefaultDialect): name = 'db2' max_identifier_length = 128 encoding = 'utf-8' default_paramstyle = 'named' colspecs = colspecs ischema_names = ischema_names supports_char_length = False supports_unicode_statements = False supports_unicode_binds = False returns_unicode_strings = False postfetch_lastrowid = True supports_sane_rowcount = False supports_sane_multi_rowcount = False supports_native_decimal = True preexecute_sequences = False supports_alter = True supports_sequences = True sequences_optional = True requires_name_normalize = True supports_default_values = False supports_empty_insert = False statement_compiler = DB2Compiler ddl_compiler = DB2DDLCompiler type_compiler = DB2TypeCompiler preparer = DB2IdentifierPreparer execution_ctx_cls = DB2ExecutionContext _reflector_cls = ibm_reflection.DB2Reflector def __init__(self, **kw): super(DB2Dialect, self).__init__(**kw) self._reflector = self._reflector_cls(self) # reflection: these all defer to an BaseDB2Reflector # object which selects between DB2 and AS/400 schemas def normalize_name(self, name): return self._reflector.normalize_name(name) def denormalize_name(self, name): return self._reflector.denormalize_name(name) def _get_default_schema_name(self, connection): return self._reflector._get_default_schema_name(connection) def has_table(self, connection, table_name, schema=None): return self._reflector.has_table(connection, table_name, schema=schema) def has_sequence(self, connection, sequence_name, schema=None): return self._reflector.has_sequence(connection, sequence_name, schema=schema) def get_schema_names(self, connection, **kw): return self._reflector.get_schema_names(connection, **kw) def get_table_names(self, connection, schema=None, **kw): return self._reflector.get_table_names(connection, schema=schema, **kw) def get_view_names(self, connection, schema=None, **kw): return self._reflector.get_view_names(connection, schema=schema, **kw) def get_view_definition(self, connection, viewname, schema=None, **kw): return self._reflector.get_view_definition( connection, viewname, schema=schema, **kw) def get_columns(self, connection, table_name, schema=None, **kw): return self._reflector.get_columns( connection, table_name, schema=schema, **kw) def get_primary_keys(self, connection, table_name, schema=None, **kw): return self._reflector.get_primary_keys( connection, table_name, schema=schema, **kw) def get_foreign_keys(self, connection, table_name, schema=None, **kw): return self._reflector.get_foreign_keys( connection, table_name, schema=schema, **kw) def get_indexes(self, connection, table_name, schema=None, **kw): return self._reflector.get_indexes( connection, table_name, schema=schema, **kw) # legacy naming IBM_DBCompiler = DB2Compiler IBM_DBDDLCompiler = DB2DDLCompiler IBM_DBIdentifierPreparer = DB2IdentifierPreparer IBM_DBExecutionContext = DB2ExecutionContext IBM_DBDialect = DB2Dialect dialect = DB2Dialect
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/base.py
Python
asf20
22,382
# +--------------------------------------------------------------------------+ # | Licensed Materials - Property of IBM | # | | # | (C) Copyright IBM Corporation 2008, 2013. | # +--------------------------------------------------------------------------+ # | This module complies with SQLAlchemy 0.8 and is | # | Licensed under the Apache License, Version 2.0 (the "License"); | # | you may not use this file except in compliance with the License. | # | You may obtain a copy of the License at | # | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable | # | law or agreed to in writing, software distributed under the License is | # | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | # | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Author: Jaimy Azle | # | Contributor: Mike Bayer | # | Version: 0.3.x | # +--------------------------------------------------------------------------+ raise NotImplementedError( "The zxjdbc dialect is not implemented at this time.") # NOTE: it appears that to use zxjdbc, the "RETURNING" syntax # must be installed in DB2, which appears to be optional. It would # be best if the RETURNING support were built into the base dialect # and not be local to zxjdbc here. from decimal import Decimal as _python_Decimal from sqlalchemy import sql, util from sqlalchemy import types as sa_types from sqlalchemy.engine.base import FullyBufferedResultProxy, ResultProxy from sqlalchemy.connectors.zxJDBC import ZxJDBCConnector from .base import DB2Dialect, DB2ExecutionContext, DB2Compiler class ReturningResultProxy(FullyBufferedResultProxy): """ResultProxy backed by the RETURNING ResultSet results.""" def __init__(self, context, returning_row): self._returning_row = returning_row super(ReturningResultProxy, self).__init__(context) def _cursor_description(self): ret = [] for c in self.context.compiled.returning_cols: if hasattr(c, 'name'): ret.append((c.name, c.type)) else: ret.append((c.anon_label, c.type)) return ret def _buffer_rows(self): return [self._returning_row] class ReturningParam(object): """A bindparam value representing a RETURNING parameter. """ def __init__(self, type): self.type = type def __eq__(self, other): if isinstance(other, ReturningParam): return self.type == other.type return NotImplemented def __ne__(self, other): if isinstance(other, ReturningParam): return self.type != other.type return NotImplemented def __repr__(self): kls = self.__class__ return '<%s.%s object at 0x%x type=%s>' % ( kls.__module__, kls.__name__, id(self), self.type) class DB2ExecutionContext_zxjdbc(DB2ExecutionContext): def pre_exec(self): if hasattr(self.compiled, 'returning_parameters'): self.statement = self.cursor.prepare(self.statement) def get_result_proxy(self): if hasattr(self.compiled, 'returning_parameters'): rrs = None try: try: rrs = self.statement.__statement__.getReturnResultSet() rrs.next() except SQLException, sqle: msg = '%s [SQLCode: %d]' % (sqle.getMessage(), sqle.getErrorCode()) if sqle.getSQLState() is not None: msg += ' [SQLState: %s]' % sqle.getSQLState() raise zxJDBC.Error(msg) else: row = tuple(self.cursor.datahandler.getPyObject(rrs, index, dbtype) for index, dbtype in self.compiled.returning_parameters) return ReturningResultProxy(self, row) finally: if rrs is not None: try: rrs.close() except SQLException: pass self.statement.close() return ResultProxy(self) def create_cursor(self): cursor = self._dbapi_connection.cursor() cursor.datahandler = self.dialect.DataHandler(cursor.datahandler) return cursor class DB2Compiler_zxjdbc(DB2Compiler): def returning_clause(self, stmt, returning_cols): self.returning_cols = list(expression._select_iterables(returning_cols)) # within_columns_clause=False so that labels (foo AS bar) don't render columns = [self.process(c, within_columns_clause=False, result_map=self.result_map) for c in self.returning_cols] if not hasattr(self, 'returning_parameters'): self.returning_parameters = [] binds = [] for i, col in enumerate(self.returning_cols): dbtype = col.type.dialect_impl(self.dialect).get_dbapi_type(self.dialect.dbapi) self.returning_parameters.append((i + 1, dbtype)) bindparam = sql.bindparam("ret_%d" % i, value=ReturningParam(dbtype)) self.binds[bindparam.key] = bindparam binds.append(self.bindparam_string(self._truncate_bindparam(bindparam))) return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds) class DB2Dialect_zxjdbc(ZxJDBCConnector, DB2Dialect): supports_unicode_statements = supports_unicode_binds = \ returns_unicode_strings = supports_unicode = False supports_sane_rowcount = False supports_sane_multi_rowcount = False jdbc_db_name = 'db2' jdbc_driver_name = 'com.ibm.db2.jcc.DB2Driver' statement_compiler = DB2Compiler_zxjdbc execution_ctx_cls = DB2ExecutionContext_zxjdbc @classmethod def dbapi(cls): global SQLException, zxJDBC from java.sql import SQLException, Types as java_Types from com.ziclix.python.sql import zxJDBC from com.ziclix.python.sql import FilterDataHandler # TODO: this should be somewhere else class IBM_DB2DataHandler(FilterDataHandler): def setJDBCObject(self, statement, index, object, dbtype=None): if type(object) is ReturningParam: statement.registerReturnParameter(index, object.type) elif dbtype is None: if (isinstance(object, int)): statement.setObject(index, str(object), java_Types.BIGINT) elif (isinstance(object, _python_Decimal)): statement.setObject(index, str(object), java_Types.DECIMAL) else: statement.setObject(index, object) else: FilterDataHandler.setJDBCObject(self, statement, index, object, dbtype) cls.DataHandler = IBM_DB2DataHandler return zxJDBC class AS400Dialect_zxjdbc(DB2Dialect_zxjdbc): jdbc_db_name = 'as400' jdbc_driver_name = 'com.ibm.as400.access.AS400JDBCDriver'
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/zxjdbc.py
Python
asf20
7,808
# +--------------------------------------------------------------------------+ # | Licensed Materials - Property of IBM | # | | # | (C) Copyright IBM Corporation 2008, 2013. | # +--------------------------------------------------------------------------+ # | This module complies with SQLAlchemy 0.8 and is | # | Licensed under the Apache License, Version 2.0 (the "License"); | # | you may not use this file except in compliance with the License. | # | You may obtain a copy of the License at | # | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable | # | law or agreed to in writing, software distributed under the License is | # | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | # | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Authors: Alex Pitigoi, Abhigyan Agrawal | # | Contributors: Jaimy Azle, Mike Bayer | # | Version: 0.3.x | # +--------------------------------------------------------------------------+ from sqlalchemy import types as sa_types from sqlalchemy import sql, util from sqlalchemy import Table, MetaData, Column from sqlalchemy.engine import reflection import re class CoerceUnicode(sa_types.TypeDecorator): impl = sa_types.Unicode def process_bind_param(self, value, dialect): if isinstance(value, str): value = value.decode(dialect.encoding) return value class BaseReflector(object): def __init__(self, dialect): self.dialect = dialect self.ischema_names = dialect.ischema_names self.identifier_preparer = dialect.identifier_preparer def normalize_name(self, name): if isinstance(name, str): name = name.decode(self.dialect.encoding) elif name != None: return name.lower() if name.upper() == name and \ not self.identifier_preparer._requires_quotes(name.lower()) \ else name return name def denormalize_name(self, name): if name is None: return None elif name.lower() == name and \ not self.identifier_preparer._requires_quotes(name.lower()): name = name.upper() if not self.dialect.supports_unicode_binds: name = name.encode(self.dialect.encoding) else: name = unicode(name) return name def _get_default_schema_name(self, connection): """Return: current setting of the schema attribute""" default_schema_name = connection.execute( u'SELECT CURRENT_SCHEMA FROM SYSIBM.SYSDUMMY1').scalar() if isinstance(default_schema_name, str): default_schema_name = default_schema_name.strip() return self.normalize_name(default_schema_name) @property def default_schema_name(self): return self.dialect.default_schema_name class DB2Reflector(BaseReflector): ischema = MetaData() sys_schemas = Table("SCHEMATA", ischema, Column("SCHEMANAME", CoerceUnicode, key="schemaname"), Column("OWNER", CoerceUnicode, key="owner"), Column("OWNERTYPE", CoerceUnicode, key="ownertype"), Column("DEFINER", CoerceUnicode, key="definer"), Column("DEFINERTYPE", CoerceUnicode, key="definertype"), Column("REMARK", CoerceUnicode, key="remark"), schema="SYSCAT") sys_tables = Table("TABLES", ischema, Column("TABSCHEMA", CoerceUnicode, key="tabschema"), Column("TABNAME", CoerceUnicode, key="tabname"), Column("OWNER", CoerceUnicode, key="owner"), Column("OWNERTYPE", CoerceUnicode, key="ownertype"), Column("TYPE", CoerceUnicode, key="type"), Column("STATUS", CoerceUnicode, key="status"), schema="SYSCAT") sys_indexes = Table("INDEXES", ischema, Column("TABSCHEMA", CoerceUnicode, key="tabschema"), Column("TABNAME", CoerceUnicode, key="tabname"), Column("INDNAME", CoerceUnicode, key="indname"), Column("COLNAMES", CoerceUnicode, key="colnames"), Column("UNIQUERULE", CoerceUnicode, key="uniquerule"), schema="SYSCAT") sys_foreignkeys = Table("SQLFOREIGNKEYS", ischema, Column("FK_NAME", CoerceUnicode, key="fkname"), Column("FKTABLE_SCHEM", CoerceUnicode, key="fktabschema"), Column("FKTABLE_NAME", CoerceUnicode, key="fktabname"), Column("FKCOLUMN_NAME", CoerceUnicode, key="fkcolname"), Column("PK_NAME", CoerceUnicode, key="pkname"), Column("PKTABLE_SCHEM", CoerceUnicode, key="pktabschema"), Column("PKTABLE_NAME", CoerceUnicode, key="pktabname"), Column("PKCOLUMN_NAME", CoerceUnicode, key="pkcolname"), Column("KEY_SEQ", sa_types.Integer, key="colno"), schema="SYSIBM") sys_columns = Table("COLUMNS", ischema, Column("TABSCHEMA", CoerceUnicode, key="tabschema"), Column("TABNAME", CoerceUnicode, key="tabname"), Column("COLNAME", CoerceUnicode, key="colname"), Column("COLNO", sa_types.Integer, key="colno"), Column("TYPENAME", CoerceUnicode, key="typename"), Column("LENGTH", sa_types.Integer, key="length"), Column("SCALE", sa_types.Integer, key="scale"), Column("DEFAULT", CoerceUnicode, key="defaultval"), Column("NULLS", CoerceUnicode, key="nullable"), schema="SYSCAT") sys_views = Table("VIEWS", ischema, Column("VIEWSCHEMA", CoerceUnicode, key="viewschema"), Column("VIEWNAME", CoerceUnicode, key="viewname"), Column("TEXT", CoerceUnicode, key="text"), schema="SYSCAT") sys_sequences = Table("SEQUENCES", ischema, Column("SEQSCHEMA", CoerceUnicode, key="seqschema"), Column("SEQNAME", CoerceUnicode, key="seqname"), schema="SYSCAT") def has_table(self, connection, table_name, schema=None): current_schema = self.denormalize_name( schema or self.default_schema_name) table_name = self.denormalize_name(table_name) if current_schema: whereclause = sql.and_(self.sys_tables.c.tabschema == current_schema, self.sys_tables.c.tabname == table_name) else: whereclause = self.sys_tables.c.tabname == table_name s = sql.select([self.sys_tables.c.tabname], whereclause) c = connection.execute(s) return c.first() is not None def has_sequence(self, connection, sequence_name, schema=None): current_schema = self.denormalize_name(schema or self.default_schema_name) sequence_name = self.denormalize_name(sequence_name) if current_schema: whereclause = sql.and_(self.sys_sequences.c.seqschema == current_schema, self.sys_sequences.c.seqname == sequence_name) else: whereclause = self.sys_sequences.c.seqname == sequence_name s = sql.select([self.sys_sequences.c.seqname], whereclause) c = connection.execute(s) return c.first() is not None def get_schema_names(self, connection, **kw): sysschema = self.sys_schemas query = sql.select([sysschema.c.schemaname], sql.not_(sysschema.c.schemaname.like('SYS%')), order_by=[sysschema.c.schemaname] ) return [self.normalize_name(r[0]) for r in connection.execute(query)] @reflection.cache def get_table_names(self, connection, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) systbl = self.sys_tables query = sql.select([systbl.c.tabname]).\ where(systbl.c.type == 'T').\ where(systbl.c.tabschema == current_schema).\ order_by(systbl.c.tabname) return [self.normalize_name(r[0]) for r in connection.execute(query)] @reflection.cache def get_view_names(self, connection, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) query = sql.select([self.sys_views.c.viewname], self.sys_views.c.viewschema == current_schema, order_by=[self.sys_views.c.viewname] ) return [self.normalize_name(r[0]) for r in connection.execute(query)] @reflection.cache def get_view_definition(self, connection, viewname, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) viewname = self.denormalize_name(viewname) query = sql.select([self.sys_views.c.text], self.sys_views.c.viewschema == current_schema, self.sys_views.c.viewname == viewname ) return connection.execute(query).scalar() @reflection.cache def get_columns(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) table_name = self.denormalize_name(table_name) syscols = self.sys_columns query = sql.select([syscols.c.colname, syscols.c.typename, syscols.c.defaultval, syscols.c.nullable, syscols.c.length, syscols.c.scale], sql.and_( syscols.c.tabschema == current_schema, syscols.c.tabname == table_name ), order_by=[syscols.c.colno] ) sa_columns = [] for r in connection.execute(query): coltype = r[1].upper() if coltype in ['DECIMAL', 'NUMERIC']: coltype = self.ischema_names.get(coltype)(int(r[4]), int(r[5])) elif coltype in ['CHARACTER', 'CHAR', 'VARCHAR', 'GRAPHIC', 'VARGRAPHIC']: coltype = self.ischema_names.get(coltype)(int(r[4])) else: try: coltype = self.ischema_names[coltype] except KeyError: util.warn("Did not recognize type '%s' of column '%s'" % (coltype, r[0])) coltype = coltype = sa_types.NULLTYPE sa_columns.append({ 'name': self.normalize_name(r[0]), 'type': coltype, 'nullable': r[3] == 'Y', 'default': r[2] or None, }) return sa_columns @reflection.cache def get_primary_keys(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) table_name = self.denormalize_name(table_name) sysindexes = self.sys_indexes col_finder = re.compile("(\w+)") query = sql.select([sysindexes.c.colnames], sql.and_( sysindexes.c.tabschema == current_schema, sysindexes.c.tabname == table_name, sysindexes.c.uniquerule == 'P' ), order_by=[sysindexes.c.tabschema, sysindexes.c.tabname] ) pk_columns = [] for r in connection.execute(query): cols = col_finder.findall(r[0]) pk_columns.extend(cols) return [self.normalize_name(col) for col in pk_columns] @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) table_name = self.denormalize_name(table_name) sysfkeys = self.sys_foreignkeys query = sql.select([sysfkeys.c.fkname, sysfkeys.c.fktabschema, \ sysfkeys.c.fktabname, sysfkeys.c.fkcolname, \ sysfkeys.c.pkname, sysfkeys.c.pktabschema, \ sysfkeys.c.pktabname, sysfkeys.c.pkcolname], sql.and_( sysfkeys.c.fktabschema == current_schema, sysfkeys.c.fktabname == table_name ), order_by=[sysfkeys.c.colno] ) fschema = {} for r in connection.execute(query): if not fschema.has_key(r[0]): referred_schema = self.normalize_name(r[5]) # if no schema specified and referred schema here is the # default, then set to None if schema is None and \ referred_schema == self.default_schema_name: referred_schema = None fschema[r[0]] = { 'name': self.normalize_name(r[0]), 'constrained_columns': [self.normalize_name(r[3])], 'referred_schema': referred_schema, 'referred_table': self.normalize_name(r[6]), 'referred_columns': [self.normalize_name(r[7])]} else: fschema[r[0]]['constrained_columns'].append(self.normalize_name(r[3])) fschema[r[0]]['referred_columns'].append(self.normalize_name(r[7])) return [value for key, value in fschema.iteritems()] @reflection.cache def get_indexes(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name(schema or self.default_schema_name) table_name = self.denormalize_name(table_name) sysidx = self.sys_indexes query = sql.select([sysidx.c.indname, sysidx.c.colnames, sysidx.c.uniquerule], sql.and_( sysidx.c.tabschema == current_schema, sysidx.c.tabname == table_name ), order_by=[sysidx.c.tabname] ) indexes = [] col_finder = re.compile("(\w+)") for r in connection.execute(query): if r[2] != 'P': indexes.append({ 'name': self.normalize_name(r[0]), 'column_names': [self.normalize_name(col) for col in col_finder.findall(r[1])], 'unique': r[2] == 'U' }) return indexes class AS400Reflector(BaseReflector): ischema = MetaData() sys_schemas = Table("SQLSCHEMAS", ischema, Column("TABLE_SCHEM", CoerceUnicode, key="schemaname"), schema="SYSIBM") sys_tables = Table("SYSTABLES", ischema, Column("TABLE_SCHEMA", CoerceUnicode, key="tabschema"), Column("TABLE_NAME", CoerceUnicode, key="tabname"), Column("TABLE_TYPE", CoerceUnicode, key="tabtype"), schema="QSYS2") sys_table_constraints = Table("SYSCST", ischema, Column("CONSTRAINT_SCHEMA", CoerceUnicode, key="conschema"), Column("CONSTRAINT_NAME", CoerceUnicode, key="conname"), Column("CONSTRAINT_TYPE", CoerceUnicode, key="contype"), Column("TABLE_SCHEMA", CoerceUnicode, key="tabschema"), Column("TABLE_NAME", CoerceUnicode, key="tabname"), Column("TABLE_TYPE", CoerceUnicode, key="tabtype"), schema="QSYS2") sys_key_constraints = Table("SYSKEYCST", ischema, Column("CONSTRAINT_SCHEMA", CoerceUnicode, key="conschema"), Column("CONSTRAINT_NAME", CoerceUnicode, key="conname"), Column("TABLE_SCHEMA", CoerceUnicode, key="tabschema"), Column("TABLE_NAME", CoerceUnicode, key="tabname"), Column("COLUMN_NAME", CoerceUnicode, key="colname"), Column("ORDINAL_POSITION", sa_types.Integer, key="colno"), schema="QSYS2") sys_columns = Table("SYSCOLUMNS", ischema, Column("TABLE_SCHEMA", CoerceUnicode, key="tabschema"), Column("TABLE_NAME", CoerceUnicode, key="tabname"), Column("COLUMN_NAME", CoerceUnicode, key="colname"), Column("ORDINAL_POSITION", sa_types.Integer, key="colno"), Column("DATA_TYPE", CoerceUnicode, key="typename"), Column("LENGTH", sa_types.Integer, key="length"), Column("NUMERIC_SCALE", sa_types.Integer, key="scale"), Column("IS_NULLABLE", sa_types.Integer, key="nullable"), Column("COLUMN_DEFAULT", CoerceUnicode, key="defaultval"), Column("HAS_DEFAULT", CoerceUnicode, key="hasdef"), schema="QSYS2") sys_indexes = Table("SYSINDEXES", ischema, Column("TABLE_SCHEMA", CoerceUnicode, key="tabschema"), Column("TABLE_NAME", CoerceUnicode, key="tabname"), Column("INDEX_SCHEMA", CoerceUnicode, key="indschema"), Column("INDEX_NAME", CoerceUnicode, key="indname"), Column("IS_UNIQUE", CoerceUnicode, key="uniquerule"), schema="QSYS2") sys_keys = Table("SYSKEYS", ischema, Column("INDEX_SCHEMA", CoerceUnicode, key="indschema"), Column("INDEX_NAME", CoerceUnicode, key="indname"), Column("COLUMN_NAME", CoerceUnicode, key="colname"), Column("ORDINAL_POSITION", sa_types.Integer, key="colno"), Column("ORDERING", CoerceUnicode, key="ordering"), schema="QSYS2") sys_foreignkeys = Table("SQLFOREIGNKEYS", ischema, Column("FK_NAME", CoerceUnicode, key="fkname"), Column("FKTABLE_SCHEM", CoerceUnicode, key="fktabschema"), Column("FKTABLE_NAME", CoerceUnicode, key="fktabname"), Column("FKCOLUMN_NAME", CoerceUnicode, key="fkcolname"), Column("PK_NAME", CoerceUnicode, key="pkname"), Column("PKTABLE_SCHEM", CoerceUnicode, key="pktabschema"), Column("PKTABLE_NAME", CoerceUnicode, key="pktabname"), Column("PKCOLUMN_NAME", CoerceUnicode, key="pkcolname"), Column("KEY_SEQ", sa_types.Integer, key="colno"), schema="SYSIBM") sys_views = Table("SYSVIEWS", ischema, Column("TABLE_SCHEMA", CoerceUnicode, key="viewschema"), Column("TABLE_NAME", CoerceUnicode, key="viewname"), Column("VIEW_DEFINITION", CoerceUnicode, key="text"), schema="QSYS2") sys_sequences = Table("SYSSEQUENCES", ischema, Column("SEQUENCE_SCHEMA", CoerceUnicode, key="seqschema"), Column("SEQUENCE_NAME", CoerceUnicode, key="seqname"), schema="QSYS2") def has_table(self, connection, table_name, schema=None): current_schema = self.denormalize_name( schema or self.default_schema_name) table_name = self.denormalize_name(table_name) if current_schema: whereclause = sql.and_( self.sys_tables.c.tabschema == current_schema, self.sys_tables.c.tabname == table_name) else: whereclause = self.sys_tables.c.tabname == table_name s = sql.select([self.sys_tables], whereclause) c = connection.execute(s) return c.first() is not None def has_sequence(self, connection, sequence_name, schema=None): current_schema = self.denormalize_name( schema or self.default_schema_name) sequence_name = self.denormalize_name(sequence_name) if current_schema: whereclause = sql.and_( self.sys_sequences.c.seqschema == current_schema, self.sys_sequences.c.seqname == sequence_name) else: whereclause = self.sys_sequences.c.seqname == sequence_name s = sql.select([self.sys_sequences.c.seqname], whereclause) c = connection.execute(s) return c.first() is not None @reflection.cache def get_schema_names(self, connection, **kw): sysschema = self.sys_schemas query = sql.select([sysschema.c.schemaname], sql.not_(sysschema.c.schemaname.like('SYS%')), sql.not_(sysschema.c.schemaname.like('Q%')), order_by=[sysschema.c.schemaname] ) return [self.normalize_name(r[0]) for r in connection.execute(query)] # Retrieves a list of table names for a given schema @reflection.cache def get_table_names(self, connection, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) systbl = self.sys_tables query = sql.select([systbl.c.tabname], systbl.c.tabschema == current_schema, order_by=[systbl.c.tabname] ) return [self.normalize_name(r[0]) for r in connection.execute(query)] @reflection.cache def get_view_names(self, connection, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) query = sql.select([self.sys_views.c.viewname], self.sys_views.c.viewschema == current_schema, order_by=[self.sys_views.c.viewname] ) return [self.normalize_name(r[0]) for r in connection.execute(query)] @reflection.cache def get_view_definition(self, connection, viewname, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) viewname = self.denormalize_name(viewname) query = sql.select([self.sys_views.c.text], self.sys_views.c.viewschema == current_schema, self.sys_views.c.viewname == viewname ) return connection.execute(query).scalar() @reflection.cache def get_columns(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) table_name = self.denormalize_name(table_name) syscols = self.sys_columns query = sql.select([syscols.c.colname, syscols.c.typename, syscols.c.defaultval, syscols.c.nullable, syscols.c.length, syscols.c.scale], sql.and_( syscols.c.tabschema == current_schema, syscols.c.tabname == table_name ), order_by=[syscols.c.tabschema, syscols.c.tabname, syscols.c.colname, syscols.c.colno] ) sa_columns = [] for r in connection.execute(query): coltype = r[1].upper() if coltype in ['DECIMAL', 'NUMERIC']: coltype = self.ischema_names.get(coltype)(int(r[4]), int(r[5])) elif coltype in ['CHARACTER', 'CHAR', 'VARCHAR', 'GRAPHIC', 'VARGRAPHIC']: coltype = self.ischema_names.get(coltype)(int(r[4])) else: try: coltype = self.ischema_names[coltype] except KeyError: util.warn("Did not recognize type '%s' of column '%s'" % (coltype, r[0])) coltype = coltype = sa_types.NULLTYPE sa_columns.append({ 'name': self.normalize_name(r[0]), 'type': coltype, 'nullable': r[3] == 'Y', 'default': r[2], 'autoincrement': r[2] is None, }) return sa_columns @reflection.cache def get_primary_keys(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) table_name = self.denormalize_name(table_name) sysconst = self.sys_table_constraints syskeyconst = self.sys_key_constraints query = sql.select([syskeyconst.c.colname, sysconst.c.tabname], sql.and_( syskeyconst.c.conschema == sysconst.c.conschema, syskeyconst.c.conname == sysconst.c.conname, sysconst.c.tabschema == current_schema, sysconst.c.tabname == table_name, sysconst.c.contype == 'PRIMARY KEY' ), order_by=[syskeyconst.c.colno]) return [self.normalize_name(key[0]) for key in connection.execute(query)] @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) table_name = self.denormalize_name(table_name) sysfkeys = self.sys_foreignkeys query = sql.select([sysfkeys.c.fkname, sysfkeys.c.fktabschema, \ sysfkeys.c.fktabname, sysfkeys.c.fkcolname, \ sysfkeys.c.pkname, sysfkeys.c.pktabschema, \ sysfkeys.c.pktabname, sysfkeys.c.pkcolname], sql.and_( sysfkeys.c.fktabschema == current_schema, sysfkeys.c.fktabname == table_name ), order_by=[sysfkeys.c.colno] ) fschema = {} for r in connection.execute(query): if not fschema.has_key(r[0]): fschema[r[0]] = {'name': self.normalize_name(r[0]), 'constrained_columns': [self.normalize_name(r[3])], 'referred_schema': self.normalize_name(r[5]), 'referred_table': self.normalize_name(r[6]), 'referred_columns': [self.normalize_name(r[7])]} else: fschema[r[0]]['constrained_columns'].append( self.normalize_name(r[3])) fschema[r[0]]['referred_columns'].append( self.normalize_name(r[7])) return [value for key, value in fschema.iteritems()] # Retrieves a list of index names for a given schema @reflection.cache def get_indexes(self, connection, table_name, schema=None, **kw): current_schema = self.denormalize_name( schema or self.default_schema_name) table_name = self.denormalize_name(table_name) sysidx = self.sys_indexes syskey = self.sys_keys query = sql.select([sysidx.c.indname, sysidx.c.uniquerule, syskey.c.colname], sql.and_( syskey.c.indschema == sysidx.c.indschema, syskey.c.indname == sysidx.c.indname, sysidx.c.tabschema == current_schema, sysidx.c.tabname == table_name ), order_by=[syskey.c.indname, syskey.c.colno] ) indexes = {} for r in connection.execute(query): key = r[0].upper() if key in indexes: indexes[key]['column_names'].append(self.normalize_name(r[2])) else: indexes[key] = { 'name': self.normalize_name(r[0]), 'column_names': [self.normalize_name(r[2])], 'unique': r[1] == 'Y' } return [value for key, value in indexes.iteritems()]
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/reflection.py
Python
asf20
27,456
"""requirements.py This file is used by the SQLAlchemy 0.8 testing suite to mark various optional behaviors as non-supported. """ from sqlalchemy.testing.requirements import SuiteRequirements from sqlalchemy.testing import exclusions class Requirements(SuiteRequirements): @property def on_update_cascade(self): """"target database must support ON UPDATE..CASCADE behavior in foreign keys.""" return exclusions.closed() @property def datetime_microseconds(self): """target dialect supports representation of Python datetime.datetime() with microsecond objects.""" return exclusions.closed() @property def time_microseconds(self): """target dialect supports representation of Python datetime.time() with microsecond objects.""" return exclusions.closed() @property def unbounded_varchar(self): """Target database must support VARCHAR with no length""" return exclusions.closed() @property def offset(self): return exclusions.closed() @property def window_functions(self): """Target database must support window functions.""" return exclusions.open() @property def precision_numerics_enotation_small(self): """target backend supports Decimal() objects using E notation to represent very small values.""" return exclusions.open() @property def precision_numerics_enotation_large(self): """target backend supports Decimal() objects using E notation to represent very large values.""" return exclusions.closed() @property def precision_numerics_many_significant_digits(self): """target backend supports values with many digits on both sides, such as 319438950232418390.273596, 87673.594069654243 """ return exclusions.fails_if(lambda: True, "Throws error SQL0604N, regarding Decimal(38, 12)" ) @property def precision_numerics_retains_significant_digits(self): """A precision numeric type will return empty significant digits, i.e. a value such as 10.000 will come back in Decimal form with the .000 maintained.""" return exclusions.open()
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/requirements.py
Python
asf20
2,292
# +--------------------------------------------------------------------------+ # | Licensed Materials - Property of IBM | # | | # | (C) Copyright IBM Corporation 2008, 2013. | # +--------------------------------------------------------------------------+ # | This module complies with SQLAlchemy 0.8 and is | # | Licensed under the Apache License, Version 2.0 (the "License"); | # | you may not use this file except in compliance with the License. | # | You may obtain a copy of the License at | # | http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable | # | law or agreed to in writing, software distributed under the License is | # | distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | # | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Authors: Alex Pitigoi, Abhigyan Agrawal | # | Contributors: Jaimy Azle, Mike Bayer | # | Version: 0.3.x | # +--------------------------------------------------------------------------+ __version__ = '0.3.0' from . import ibm_db, pyodbc, base # zxjdbc # default dialect base.dialect = ibm_db.dialect from .base import \ BIGINT, BLOB, CHAR, CLOB, DATE, DATETIME, \ DECIMAL, DOUBLE, DECIMAL,\ GRAPHIC, INTEGER, INTEGER, LONGVARCHAR, \ NUMERIC, SMALLINT, REAL, TIME, TIMESTAMP, \ VARCHAR, VARGRAPHIC, dialect #__all__ = ( # TODO: (put types here) # 'dialect' #)
zzzeek-ibm-db-sa
ibm_db_sa/ibm_db_sa/__init__.py
Python
asf20
1,948
from sqlalchemy.dialects import registry registry.register("db2", "ibm_db_sa.ibm_db", "DB2Dialect_ibm_db") registry.register("db2.ibm_db", "ibm_db_sa.ibm_db", "DB2Dialect_ibm_db") registry.register("db2.pyodbc", "ibm_db_sa.pyodbc", "DB2Dialect_pyodbc") registry.register("db2.zxjdbc", "ibm_db_sa.zxjdbc", "DB2Dialect_zxjdbc") registry.register("db2.pyodbc400", "ibm_db_sa.pyodbc", "AS400Dialect_pyodbc") registry.register("db2.zxjdbc400", "ibm_db_sa.zxjdbc", "AS400Dialect_zxjdbc") from sqlalchemy.testing import runner runner.main()
zzzeek-ibm-db-sa
ibm_db_sa/run_tests.py
Python
asf20
538
package com.swtdesigner; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; /** * Utility class for managing OS resources associated with SWT controls such as colors, fonts, images, etc. * <p> * !!! IMPORTANT !!! Application code must explicitly invoke the <code>dispose()</code> method to release the * operating system resources managed by cached objects when those objects and OS resources are no longer * needed (e.g. on application shutdown) * <p> * This class may be freely distributed as part of any application or plugin. * <p> * Copyright (c) 2003 - 2007, Instantiations, Inc. <br> * All Rights Reserved * * @author scheglov_ke * @author Dan Rubel */ public class SWTResourceManager { //////////////////////////////////////////////////////////////////////////// // // Color // //////////////////////////////////////////////////////////////////////////// private static Map<RGB, Color> m_colorMap = new HashMap<RGB, Color>(); /** * Returns the system {@link Color} matching the specific ID. * * @param systemColorID * the ID value for the color * @return the system {@link Color} matching the specific ID */ public static Color getColor(int systemColorID) { Display display = Display.getCurrent(); return display.getSystemColor(systemColorID); } /** * Returns a {@link Color} given its red, green and blue component values. * * @param r * the red component of the color * @param g * the green component of the color * @param b * the blue component of the color * @return the {@link Color} matching the given red, green and blue component values */ public static Color getColor(int r, int g, int b) { return getColor(new RGB(r, g, b)); } /** * Returns a {@link Color} given its RGB value. * * @param rgb * the {@link RGB} value of the color * @return the {@link Color} matching the RGB value */ public static Color getColor(RGB rgb) { Color color = m_colorMap.get(rgb); if (color == null) { Display display = Display.getCurrent(); color = new Color(display, rgb); m_colorMap.put(rgb, color); } return color; } /** * Dispose of all the cached {@link Color}'s. */ public static void disposeColors() { for (Color color : m_colorMap.values()) { color.dispose(); } m_colorMap.clear(); } //////////////////////////////////////////////////////////////////////////// // // Image // //////////////////////////////////////////////////////////////////////////// /** * Maps image paths to images. */ private static Map<String, Image> m_imageMap = new HashMap<String, Image>(); /** * Returns an {@link Image} encoded by the specified {@link InputStream}. * * @param stream * the {@link InputStream} encoding the image data * @return the {@link Image} encoded by the specified input stream */ public static Image getImageForPath(String name) { InputStream stream = null; try { if(name.contains("image")){ stream = SWTResourceManager.class.getClassLoader().getResourceAsStream("com/taobao/resource/"+name); } else { stream = SWTResourceManager.class.getClassLoader().getResourceAsStream("com/taobao/resource/"+name); } Display display = Display.getCurrent(); ImageData data = new ImageData(stream); if (data.transparentPixel > 0) { return new Image(display, data, data.getTransparencyMask()); } return new Image(display, data); } finally { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Style constant for placing decorator image in top left corner of base image. */ public static final int TOP_LEFT = 1; /** * Style constant for placing decorator image in top right corner of base image. */ public static final int TOP_RIGHT = 2; /** * Style constant for placing decorator image in bottom left corner of base image. */ public static final int BOTTOM_LEFT = 3; /** * Style constant for placing decorator image in bottom right corner of base image. */ public static final int BOTTOM_RIGHT = 4; /** * Internal value. */ protected static final int LAST_CORNER_KEY = 5; /** * Maps images to decorated images. */ @SuppressWarnings("unchecked") private static Map<Image, Map<Image, Image>>[] m_decoratedImageMap = new Map[LAST_CORNER_KEY]; /** * Returns an {@link Image} composed of a base image decorated by another image. * * @param baseImage * the base {@link Image} that should be decorated * @param decorator * the {@link Image} to decorate the base image * @return {@link Image} The resulting decorated image */ public static Image decorateImage(Image baseImage, Image decorator) { return decorateImage(baseImage, decorator, BOTTOM_RIGHT); } /** * Returns an {@link Image} composed of a base image decorated by another image. * * @param baseImage * the base {@link Image} that should be decorated * @param decorator * the {@link Image} to decorate the base image * @param corner * the corner to place decorator image * @return the resulting decorated {@link Image} */ public static Image decorateImage(final Image baseImage, final Image decorator, final int corner) { if (corner <= 0 || corner >= LAST_CORNER_KEY) { throw new IllegalArgumentException("Wrong decorate corner"); } Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[corner]; if (cornerDecoratedImageMap == null) { cornerDecoratedImageMap = new HashMap<Image, Map<Image, Image>>(); m_decoratedImageMap[corner] = cornerDecoratedImageMap; } Map<Image, Image> decoratedMap = cornerDecoratedImageMap.get(baseImage); if (decoratedMap == null) { decoratedMap = new HashMap<Image, Image>(); cornerDecoratedImageMap.put(baseImage, decoratedMap); } // Image result = decoratedMap.get(decorator); if (result == null) { Rectangle bib = baseImage.getBounds(); Rectangle dib = decorator.getBounds(); // result = new Image(Display.getCurrent(), bib.width, bib.height); // GC gc = new GC(result); gc.drawImage(baseImage, 0, 0); if (corner == TOP_LEFT) { gc.drawImage(decorator, 0, 0); } else if (corner == TOP_RIGHT) { gc.drawImage(decorator, bib.width - dib.width, 0); } else if (corner == BOTTOM_LEFT) { gc.drawImage(decorator, 0, bib.height - dib.height); } else if (corner == BOTTOM_RIGHT) { gc.drawImage(decorator, bib.width - dib.width, bib.height - dib.height); } gc.dispose(); // decoratedMap.put(decorator, result); } return result; } /** * Dispose all of the cached {@link Image}'s. */ public static void disposeImages() { // dispose loaded images { for (Image image : m_imageMap.values()) { image.dispose(); } m_imageMap.clear(); } // dispose decorated images for (int i = 0; i < m_decoratedImageMap.length; i++) { Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i]; if (cornerDecoratedImageMap != null) { for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) { for (Image image : decoratedMap.values()) { image.dispose(); } decoratedMap.clear(); } cornerDecoratedImageMap.clear(); } } } //////////////////////////////////////////////////////////////////////////// // // Font // //////////////////////////////////////////////////////////////////////////// /** * Maps font names to fonts. */ private static Map<String, Font> m_fontMap = new HashMap<String, Font>(); /** * Maps fonts to their bold versions. */ private static Map<Font, Font> m_fontToBoldFontMap = new HashMap<Font, Font>(); /** * Returns a {@link Font} based on its name, height and style. * * @param name * the name of the font * @param height * the height of the font * @param style * the style of the font * @return {@link Font} The font matching the name, height and style */ public static Font getFont(String name, int height, int style) { return getFont(name, height, style, false, false); } /** * Returns a {@link Font} based on its name, height and style. Windows-specific strikeout and underline * flags are also supported. * * @param name * the name of the font * @param size * the size of the font * @param style * the style of the font * @param strikeout * the strikeout flag (warning: Windows only) * @param underline * the underline flag (warning: Windows only) * @return {@link Font} The font matching the name, height, style, strikeout and underline */ public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline) { String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline; Font font = m_fontMap.get(fontName); if (font == null) { FontData fontData = new FontData(name, size, style); if (strikeout || underline) { try { Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); //$NON-NLS-1$ Object logFont = FontData.class.getField("data").get(fontData); //$NON-NLS-1$ if (logFont != null && logFontClass != null) { if (strikeout) { logFontClass.getField("lfStrikeOut").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$ } if (underline) { logFontClass.getField("lfUnderline").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$ } } } catch (Throwable e) { System.err.println("Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$ } } font = new Font(Display.getCurrent(), fontData); m_fontMap.put(fontName, font); } return font; } /** * Returns a bold version of the given {@link Font}. * * @param baseFont * the {@link Font} for which a bold version is desired * @return the bold version of the given {@link Font} */ public static Font getBoldFont(Font baseFont) { Font font = m_fontToBoldFontMap.get(baseFont); if (font == null) { FontData fontDatas[] = baseFont.getFontData(); FontData data = fontDatas[0]; font = new Font(Display.getCurrent(), data.getName(), data.getHeight(), SWT.BOLD); m_fontToBoldFontMap.put(baseFont, font); } return font; } /** * Dispose all of the cached {@link Font}'s. */ public static void disposeFonts() { // clear fonts for (Font font : m_fontMap.values()) { font.dispose(); } m_fontMap.clear(); // clear bold fonts for (Font font : m_fontToBoldFontMap.values()) { font.dispose(); } m_fontToBoldFontMap.clear(); } //////////////////////////////////////////////////////////////////////////// // // Cursor // //////////////////////////////////////////////////////////////////////////// /** * Maps IDs to cursors. */ private static Map<Integer, Cursor> m_idToCursorMap = new HashMap<Integer, Cursor>(); /** * Returns the system cursor matching the specific ID. * * @param id * int The ID value for the cursor * @return Cursor The system cursor matching the specific ID */ public static Cursor getCursor(int id) { Integer key = Integer.valueOf(id); Cursor cursor = m_idToCursorMap.get(key); if (cursor == null) { cursor = new Cursor(Display.getDefault(), id); m_idToCursorMap.put(key, cursor); } return cursor; } /** * Dispose all of the cached cursors. */ public static void disposeCursors() { for (Cursor cursor : m_idToCursorMap.values()) { cursor.dispose(); } m_idToCursorMap.clear(); } //////////////////////////////////////////////////////////////////////////// // // General // //////////////////////////////////////////////////////////////////////////// /** * Dispose of cached objects and their underlying OS resources. This should only be called when the cached * objects are no longer needed (e.g. on application shutdown). */ public static void dispose() { disposeColors(); disposeImages(); disposeFonts(); disposeCursors(); } }
zzupdate
trunk/Update/src/com/swtdesigner/SWTResourceManager.java
Java
asf20
14,601
package com.taobao.update; import javax.xml.namespace.QName; import org.apache.axis.client.Call; import org.apache.axis.client.Service; public class WebService { public String getVersion() { String version = null; try { String endpoint = "http://shua.zhuzhuxc.com/soft/SoftService.asmx"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName("http://shua.zhuzhuxc.com/", "Version")); call.setSOAPActionURI("http://shua.zhuzhuxc.com/Version"); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING); version = call.invoke(new Object[] {}).toString(); } catch (Exception e) { e.printStackTrace(); } return version; } public String getMaintenanceMessage() { String msg = null; try { String endpoint = "http://shua.zhuzhuxc.com/soft/SoftService.asmx"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName("http://shua.zhuzhuxc.com/", "MaintenanceMessage")); call.setSOAPActionURI("http://shua.zhuzhuxc.com/MaintenanceMessage"); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING); msg = call.invoke(new Object[] {}).toString(); } catch (Exception e) { e.printStackTrace(); } return msg; } public String getPeriod(String name) { String period = null; try { Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(new java.net.URL("http://shua.zhuzhuxc.com/soft/SoftService.asmx")); call.setOperationName(new QName("http://shua.zhuzhuxc.com/", "Period")); call.setSOAPActionURI("http://shua.zhuzhuxc.com/Period"); call.addParameter("ASn", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("AUserName", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING); period = (String) call.invoke(new Object[] {"2735e811f859e1293fb45e99ce3dbdd6", name}); } catch (Exception e) { e.printStackTrace(); } return period; } public String getPageHomeUrl() { String url = null; try { String endpoint = "http://shua.zhuzhuxc.com/soft/SoftService.asmx"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName("http://shua.zhuzhuxc.com/", "PageHomeUrl")); call.setSOAPActionURI("http://shua.zhuzhuxc.com/PageHomeUrl"); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING); url = call.invoke(new Object[] {}).toString(); } catch (Exception e) { e.printStackTrace(); } return url; } public static void main(String[] args) { System.out.println(new WebService().getVersion()); System.out.println(new WebService().getMaintenanceMessage()); System.out.println(new WebService().getPeriod("caicai_vip")); System.out.println(new WebService().getPageHomeUrl()); } }
zzupdate
trunk/Update/src/com/taobao/update/WebService.java
Java
asf20
3,734
package com.taobao.update; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; /** * @author Liupeng * @version CreateTime:2010-12-20 */ public class VersionService { private String[] charsets = new String[] { "UTF-8", "UTF-8" }; private static String[] urls = new String[] {"http://yjheeq.javaeye.com/blog/847011", "http://blog.sina.com.cn/s/blog_61313c620100nyg0.html"}; public int version() { int version = -1; for (int i = 0; i < urls.length; i++) { version = getVersion(urls[i], i); if (version != -1) { break; } } return version; } private int getVersion(String urlPath, int no) { int version = -1; try { URL url = new URL(urlPath); HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 ( .NET CLR 3.5.30729)"); InputStream l_urlStream = httpUrlConnection.getInputStream(); String sCurrentLine = ""; String msg = ""; BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream, charsets[no])); while ((sCurrentLine = l_reader.readLine()) != null) { msg += sCurrentLine + "\r\n"; } l_reader.close(); Document doc = Jsoup.parse(msg); String content = ""; if (no == 0) { content = doc.getElementsByClass("blog_content").html(); } else if (no == 1) { content = doc.getElementById("sina_keyword_ad_area2").html(); } if (!content.equals("")) { content = content.substring(content.indexOf(":") + 1); version = Integer.parseInt(content.replace(".", "")); } } catch (Exception e) { e.printStackTrace(); } return version; } public static void main(String[] args) { new VersionService().version(); } }
zzupdate
trunk/Update/src/com/taobao/update/VersionService.java
Java
asf20
2,033
package com.taobao.tools; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; public class GIF { private GC shellGC; private Color shellBackground; private ImageLoader loader; private ImageData[] imageDataArray; private Thread animateThread; private Image image; private final boolean useGIFBackground = false; public void gif(Control parent, final Shell shell, String fileName) { shellGC = new GC(parent); shellBackground = parent.getBackground(); String path = Property.java_path + "/image/" + fileName; if (fileName.substring(0, 1).equals("-")) { path = Property.java_path + "/command/" + fileName.substring(1); } if (path != null) { loader = new ImageLoader(); try { imageDataArray = loader.load(path); if (imageDataArray.length > 1) { animateThread = new Thread(fileName) { public void run() { Image offScreenImage = new Image(shell.getDisplay(), loader.logicalScreenWidth, loader.logicalScreenHeight); GC offScreenImageGC = new GC(offScreenImage); offScreenImageGC.setBackground(shellBackground); offScreenImageGC.fillRectangle(0, 0, loader.logicalScreenWidth, loader.logicalScreenHeight); try { int imageDataIndex = 0; ImageData imageData = imageDataArray[imageDataIndex]; if (image != null && !image.isDisposed()) { image.dispose(); } image = new Image(shell.getDisplay(), imageData); offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); int repeatCount = loader.repeatCount; while (loader.repeatCount == 0 || repeatCount > 0) { switch (imageData.disposalMethod) { case SWT.DM_FILL_BACKGROUND: Color bgColor = null; if (useGIFBackground) { bgColor = new Color(shell.getDisplay(), imageData.palette.getRGB(loader.backgroundPixel)); } offScreenImageGC.setBackground(bgColor != null ? bgColor : shellBackground); offScreenImageGC.fillRectangle(imageData.x, imageData.y, imageData.width, imageData.height); if (bgColor != null) bgColor.dispose(); break; case SWT.DM_FILL_PREVIOUS: /* * Restore the previous image before * drawing. */ offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); break; } imageDataIndex = (imageDataIndex + 1) % imageDataArray.length; imageData = imageDataArray[imageDataIndex]; image.dispose(); image = new Image(shell.getDisplay(), imageData); offScreenImageGC.drawImage(image, 0, 0, imageData.width, imageData.height, imageData.x, imageData.y, imageData.width, imageData.height); /* Draw the off-screen image to the shell. */ shellGC.drawImage(offScreenImage, 0, 0); /* * Sleep for the specified delay time * (adding commonly-used slow-down fudge * factors). */ try { int ms = imageData.delayTime * 10; if (ms < 20) ms += 30; if (ms < 30) ms += 10; Thread.sleep(ms); } catch (InterruptedException e) { } /* * If we have just drawn the last image, * decrement the repeat count and start * again. */ if (imageDataIndex == imageDataArray.length - 1) repeatCount--; } } catch (SWTException ex) { // ex.printStackTrace(); } finally { if (offScreenImage != null && !offScreenImage.isDisposed()) offScreenImage.dispose(); if (offScreenImageGC != null && !offScreenImageGC.isDisposed()) offScreenImageGC.dispose(); if (image != null && !image.isDisposed()) image.dispose(); } } }; animateThread.setDaemon(true); animateThread.start(); } else { Image bg = new Image(null, path); if (path.contains("degree")) { int w = bg.getImageData().width; int h = bg.getImageData().height; GridData data = (GridData) parent.getLayoutData(); data.heightHint = h; data.widthHint = w; parent.getParent().layout(true); } parent.setBackgroundImage(bg); } } catch (SWTException ex) { } } } }
zzupdate
trunk/Update/src/com/taobao/tools/GIF.java
Java
asf20
5,118
package com.taobao.tools; /** * @author Liupeng * @version CreateTime:2010-11-16 */ public class Property { public static String java_path = ""; public static String win_path = ""; static { win_path = System.getProperty("user.dir"); java_path = win_path.replaceAll("\\\\", "/"); } }
zzupdate
trunk/Update/src/com/taobao/tools/Property.java
Java
asf20
339