Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Casa abierta al tiempo es la frase que adoptada como lema institucional, expresa con profundo
sentido la visin y el espritu del proyecto acadmico de la Universidad Autnoma Metropolitana.
Convertida la frase el lema, apunta a los propsitos de la Universidad, que es Casa abierta al
tiempo portador de sentido, posibilidad de saber y de dilogo.
-2-
-3-
confidencialidad de la informacin del los clientes. Este mdulo ser configurable para poderse
usar o no, en base a las necesidades del negocio.
El sistema a desarrollar constara de dos componentes principales, el mdulo cliente y el mdulo
servidor TCP-Proxy, los cuales estn fundamentados en el manejo sockets TCP del protocolo TCPIP, garantizando un mejor enlace.
La construccin del proyecto estar basado en C++, para garantizar mayor performance, as
tambin nos permita poder tener la capacidad de realizar balanceo de cargas y tener la capacidad
de transportabilidad en otras plataformas.
Es entonces, que el mdulo cliente permitir el envo y recepcin de mensajes en formato PS9
(protocolo lgico de informacin estndar para comunicacin con el MainFrame), dando la
posibilidad de usar o no encripcin.
La parte del modulo de servidor TCP-Proxy, tendr como funcin la retransmisin de mensajes que
reciba del modulo cliente, para las empresas externas de call center. Este componente, contar
con la habilidad de ser multitarea (multithread), tambin se pretende que maneje la programacin
paralela y poder aprovechar la infraestructura del servidor o equipo que lo aloje, ms si cuenta con
procesadores multicore y/o multiprocesador.
-4-
Agradecimientos.
Doy gracias a mis padres, por el apoyo incondicional que siempre me han dado y por que siempre
creyeron en m.
Rodolfo Rosas Rico y Lucia Daz Herrera.
Mi sincero agradecimiento hacia mis hermanos: Maria, Sergio, Rodolfo y Vernica.
Por su apoyo y motivacin en mis estudios.
Agradezco el gran apoyo del Maestro Omar Lucio Cabrera como mi asesor
de proyecto.
Mi reconocimiento y agradecimiento a la Universidad Autnoma Metropolitana, por ser
la
Dedicatoria;
Dedico la presente obra a mi hermosa familia: mi esposa Celia, a mi nenita Lilian y al bebe
que estamos esperando.
-5-
Contenido
1 Introduccin.
2 Sistemas de Atencin Telefnica.
2.1
Introduccin.
2.2
3 MainFrame (Host).
3.1
Introduccin.
3.2
3.3
3.4
Protocolo PS-9.
Introduccin.
4.2
Programacin Multihilo.
4.3
4.4
5 Criptografa.
5.1
Introduccin
5.2
Requerimientos.
6.2
Anlisis.
6.3
Diseo.
6.4
Construccin.
6.5
Conclusiones y resultados.
7 Referencias
Anexo A. Cdigo fuente.
-6-
-7-
La parte del modulo de servidor TCP-Proxy, tendr como funcin la retransmisin de mensajes que
reciba del mdulo cliente, para las empresas externas de call center. Este componente contara con
la habilidad de ser multitarea (multithread), as como la posibilidad de usar programacin paralela,
teniendo la posibilidad de aprovechar la existencia de algn servidor con procesadores multicore
y/o multiprocesador.
2.1
Introduccin.
-8-
IVR Inicia
n con el
Interacci
Cliente y valida si es
Y
aplica Script Programado
nueva
Llamada
.
Convierte instrucciones del
cliente
En
Transacciones hacia el
HOST
6
1
AN
I
COMPAIA
TELEFONICA
PBX
env
Al
IVR
La llamada llega a
un
Grupo
de
n
Priorizaci
y
Se
transfiere al
IVR
Cliente
Marca
a llamada
SYMPOSIU
M
HOST
HOS
WA
N
AN
I
CTI
Server
Conmutador(es
PB
1
12
IV s
Compaa que proporciona
el servicio Telefnico
1
14 Realiza
113
Cliente Marca
8
8
Cliente
Solicita
Transferencia
con
Un
Agente
Transferencia
10
1
Symposiu
ne
as
Di
git
al
es
0
11
1
1
ACD Phon
CTI
Server
Agente
HOS
T
WA
N
PBX Transfiere
llamada
Al
ID
Disponible
R
ed
Et
he
rn
R
ed
V
oz
13
1
ACD Phon
e
Agente
15
1
El5asesor recibe screen pop del
Cliente y pasa info . A SDAT
r
SDAT
ACD Phon
e
Agente Servicio Tipo
1
16
1
6
Termina
la llamada
O transfiere a otro grupo (repite
10
ACD Phon
-15
)
Se guarda
informaci en
Llamada
BD.
-9-
n de
la
17
1
Tabla
CTI
Tig045_CT
I
I.
- 10 -
CT
I
Conmutador(e )
Interfase
Conmutador:
Interfase
DD
Sistema de
Rollin
Grabacn
CDNMonito
CDNColgad
Sistem
de aGrabacion
Interfase CTI-Deskto
IV s
R
GUI
App Distrib.
2.2
- 11 -
avanzado. Se contara con una interaccin con CTI a travs de una dll para el manejo de sockets
TCP de TCP/IP.
Configuracin propuesta de 3 sites, instalados en tres ciudades principales, que darn servicio a
todo el pas.
- 12 -
El men de robo extravo transfiere las llamadas de forma directa con los asesores
para el reporte de plsticos o cheques, que fueron extraviados o robados.
El men de transaccionalidad contiene la mayor parte de la aplicacin, en l se
pueden encontrar diferentes opciones las cuales se presentan en base a los productos
financieros que tenga contratados el cliente. Contamos con alrededor de 100
transacciones diferentes, las cuales se utilizan a travs de sockets de TCP/IP y tienen
el formato PS9. Mensualmente se generan ms de 10 millones de transacciones.
El men de servicios contiene la mayor parte de las opciones de transferencia.
Previo a la transferencia se realizan validaciones en los productos de los clientes, en
algunos casos se evita la transferencia informando al cliente, por ejemplo, el estatus
de una aclaracin, el envo de un plstico a domicilio, entre otros.
CENTRO1
576 PTS
81579111
27E1
CALL CENTER
EXTERNO
IVR S
CIA TEL
CALL CENTER
EXTERNO
SYMPOSIUM SERVIDOR
LINK
CTI
11E1
160CH/6E|
52262663
27E1
2E1
CIA TEL
5E1
3E1
562411XX
11E1
6E1
CIA TEL
CENTRO3
36690229
52262663
CONMUTADOR 2
CONMUTADOR 1
CENTRO2
9E1
13E1
CIA TEL
5E1
CIA TEL
2E1
SYMPOSIUM
SYMPOSIUM
LINK
LINK
SYMPOSIUM
AGTS
LINK
250 AGTES
350 AGTES
SERVIDOR
CTI
SERVIDOR
IVRS
172 PTS
SERVIDOR
CTI
IVRS
500 PTS
- 13 -
AGTS
CTI
IVRS
355 PTS
3 MainFrame (Host).
3.1
Introduccin.
- 14 -
Nosotros podemos decir que Cics acta como el z/OS y realiza muchas de las mismas operaciones
que el z/OS sistema operativo.
Una aplicacin Cics, es una coleccin de programas relacionados, los cuales juntos realizan una
operacin de negocio. Unos ejemplos pueden ser, el procesamiento de una solicitud de viaje o la
preparacin de una nmina de una empresa. Las aplicaciones de Cics, son ejecutadas bajo el
control de Cics, usando servicios de Cics y sus interfaces de acceso a programas y de archivos.
Las transacciones de cics son normalmente realizadas por ejecucin de un requerimiento de
transaccin. La transaccin ejecutada consiste en con correr una o mas programas de aplicacin
que implementan la funcin requerida.
3.2
3.3
El IBM CICS BRIDGE, es un conjunto de programas que forman parte de la interfase CICS
Sockets y que son instalados conjuntamente con los programas dedicados a tal fin en el CSD de la
regin CICS.
El objetivo del CICSBRIDGE es permitir que una aplicacin transaccional sncrona distribuida
pueda conseguir la ejecucin de un programa residente en una regin CICS OS/390 y obtener una
respuesta mediante el uso de MQ, Sockets, etc. sin necesidad de que el programa CICS tenga que
ser modificado para soportar dicha comunicacin.
Debido a las necesidades que se requieren en un banco determinado, es necesaria la
implementacin de una versin modificada de la versin original del Cics Bridge de IBM. En donde
a continuacin se menciona una versin propuesta que se puede usar en una empresa bancaria.
A diferencia del monitor de IBM (Transaccin CSKL), la versin propuesta est orientada al
aprovechamiento de las facilidades transaccionales sobre CICSPLEX, al distribuir la carga
transaccional en los AORes, evitando la concentracin de transacciones en el TOR y evitando
afinidades, y adicionando facilidades de sesiones y validaciones en RACF.
- 15 -
Aplicativo
TCP/
IP
Servi
ces
CICS
Sock
ets
API
START
QPTP
START
USERID GENERICO
QG1CSP
QTxx
START
USERID GENERICO
QG1CSER
TCP/
IP
Servi
ces
TCP/
IP
Serv
XYZ
WXCTL
YMQ
T
QOxx
LINK TRANSID
DFHMIR
S
CICS
TOR
QG1CS
BP2
A
R
Q
U
I
T
E
LINK
C
T
U
R
A
A
P
L
I
C
A
T
I
V
O
S
CICS
AOR
- 16 -
- 17 -
3.4
Protocolo PS-9.
El protocolo de comunicacin entre el distribuido y el host, esta dado por el Cics bridge
TCP debido a su desarrollo, aunque tiene un parmetro de protocolo que puede ser til en caso de
no querer utilizar el protocolo definido.
Teniendo en cuenta que es un sistema de comunicaciones de un cliente ya sea un distribuido o un
host hacia el equipo host de BBVA, atendiendo requerimientos principalmente de aplicaciones que
se encuentran bajo la arquitectura Altamira, el flujo comienza en con el cliente. Antes de comenzar
a describir el protocolo definiremos algunos de los formatos en los cuales se enviara la informacin.
) MESSAGE DESCRIPTOR DE TCP. Formato de informacin de 160 posiciones fijas, en el
cual se incluyen parmetros y datos propios de la aplicacin y del operador, este
formato tendr que ser enviado siempre. Los campos contenidos en este formato
son:
Tipo
X(04) <MD>
X(05) 1.0.0
9(05) 32584
X(24)
9(05) 00600
REQUERIMIENTO SOLICITADO de MD
TIPO DE USUARIO
NUMERO DE SESION
FECHA DE ENVIO
X(10) AAAA-MM-DD
HORA DE ENVIO
X(08) HH:MM:SS
DISPONIBLE
X(30) Espacios
X(05) </MD>
X(04) <IH>
- 18 -
NMERO DE SECUENCIA
CODIGO DE LA TRANSACCION
X(08) Transaccin
OPCIN
9(02)
9(05)
9(01)
TIPO DE MENSAJE
9(01)
TIPO DE PROCESO
X(01)
CANAL
INDICADOR DE PREFORMATEO
TERMINAL LOGICO
TERMINAL CONTABLE
USUARIO
LENGUAJE
TAG DE FIN DEL INPUT HEADER
Intro=00,F1=01,F2=02
...
Longitud PS9 desde <IH> a
</ME>
0 Sin commit 1 con
commit
1- New Request,
2- Authorization,
3- Conversation Scroll
Info.,
5- Conversation
Continuation,
6- Authorization in a
conversation
O On-line F Off-line
) INPUT MESSAGE. Este es el formato del mensaje que dependiendo del tipo de mensaje
descrito en el Input Header y dependiendo de la transaccin enviada ser de formato
y longitud variable. El formato ms comn que se utilizar bajo Cics bridge ser el
siguiente. Para mayor informacin sobre otro formato consultar el documento
informacin del protocolo PS-9.
Tipo
Valor Default
posibles
X(04) <ME>
9(04) Longitud del COPY
X(01) C si es COPY B
Si es BMS
X(---) Datos del copy
X(05) </ME>
El programa QG1CMTCP monitor bajo Sockets, una vez realizada la conexin a la IP y puerto
correspondiente mediante APIs de Sockets, empieza por validar los tres formatos. Dependiendo
del requerimiento del cliente es como se procesara la informacin.
- 19 -
a) Cuando parmetro de host TIPOREQUER es el valor default (espacios ****), nos indica que el
cliente no requiere de sesiones de Cics bridge. Por lo que por cada peticin del cliente tiene
que enviar la siguiente secuencia de formato:
<MD>
</MD><IH>
</IH><ME>
</ME>
Cuando se requiera operar alguna transaccin se tendr que enviar una trama de la
siguiente forma:
<MD>
</MD><IH>
</IH><ME>
</ME>,
Pero aqu en el MD se tendr que indicar el usuario, nmero de sesin y requerimiento igual a
VERY. El programa realizar el punto 1 posteriormente validar que exista la sesin y contenga
al usuario indicado, de tal forma que si es correcto realizara el punto 2 y 3, en caso de que no
exista la sesin que el usuario no corresponda a la sesin se regresar el error
correspondiente.
7. Para este esquema tambin existe una variante si el parmetro TIPOUSUARI es
USERRACF , TIPOVALIDA es RACF y REQUERIMIENTO del Message Descriptor es
LOGN, se tomar el usuario y password que venga en el Message descriptor y se
realizar la validacin en RACF si es correcto se proceder a generar la sesin y en
caso contrario se regresar el error correspondiente. Esto es solo en el momento del
LOGON ya que de esta forma solo hay una validacin en RACF y no una por cada
peticin.
- 20 -
- 21 -
Bytes
4
2
1
Meaning
Tag Indicating beginning of output header
Protocol Identification
Transaction / Service response
Process Control
- 22 -
Possible Values
<OH>
26 PS9 (this protocol)
1= OK with COMMIT. It means the Front
End should COMMIT the changes (if
the COMMIT indicator had the value
0 Altamira architecture is not
allowed to do so).
2 = NO OK with COMMIT. It means the
Front End should COMMIT the
changes even thougth an error has
ocurred.
3 = CONFIRMATION REQUESTED with
COMMIT (User must confirm an
action. Usually associated to a
Warning Map and a Next
Transaction map to indicate what is
the transaction we want to confirm.
The changes should be commited).
4= OK with ROLLBACK. It means the
Front End should ROLLBACK the
changes.
5 = NO OK with ROLLBACK. It means
the Front End should ROLLBACK
the changes.
6 = CONFIRMATION REQUESTED with
ROLLBACK.
0 Not processing errors detected.
1 Indicates that an architecture error
has ocurred. An output format
espedified in an <OC> map does not
exist (Only applicable in traditional
Altamira architecture).
2 Reserved Use.
'3' Indicates that an architecture error
has ocurred. The output message
has more than 32 Kb. The user
should advise CPD check the LOG.
'4' Indicates that an architecture error
has ocurred. The Output Copy map
or the Preformated Map information
has more than 20 Kb. The user
should advise CPD to check the
LOG.
'5' - Indicates that an architecture error
has ocurred. The application
program informs that the Output
Screen is the same that the Input
Screen and the Input format does
not exist.
The user should advise CPD to check
the LOG. (Only applicable in
Sequence number
NNNNN
TTTTT
</OH>
Bytes
4
7
Meaning
Tag for beginning of error map
Error code
NUMVAR
Number of variables
ERRVAR1
20
ERRVARN
20
TTTTT
Possible Values
<ER>
Any Alphanumeric set of characters
following Altamira standard for error
names
Any value >= 0. When NUMVAR is equal
to 0, the Variable fields wont be sent.
Any Alphanumeric set of characters
(if NUMVAR > 0)
Any Alphanumeric set of characters
(if NUMVAR > 1)
</ER>
- 23 -
Bytes
4
1
1
NUM-DOCUM
Meaning
Tag for beginning of destination map.
ID of the Destination
Destination of the format (Screen, Printer, Hard Disk or
Jetform
Type of document if the output is to document.
PRILIN-DOCUM
IMPRESO
IDIOMA
2
6
1
TTTTT
Possible Values
<DE>
Any value among 1,..,5
P Screen
D Printer
1 DIN A-4 Normal
print.
2 DIN A-4
Compressed print.
3 Sheet
5,6,7,8 Savings
books.
9 DIN A-4 in a laser
printer
C Check
B Band (ribbon)
I Amount
J Magnetic Diary
R Pre-printed
document.
ID of the language to
be used.
</DE>
Bytes
4
1
Meaning
Tag for beginning of Output copy map
Type of copy
FFFFFFFF
<copy>
Data
TTTTT
Possible Values
<OC>
B BMS
C COPY
0
1
2
3
4
5
Format name that will match with copy name
following Altamira Naming Standards, or the
output number for the transaction.
Copy of the specified type (BMS or standard
COPY).
</OC>
BMS copy sigue la estructura FILLER [longitud-atributo-campo], con un tamao mximo de 2000
bytes.
En caso de un copy fijo, este consistir de un nmero fijo de campos con contenido alfanumrico.
Esto permite usar diferentes copias para la misma transaccin. El copy usado ser definido por el
nmero de salida.
Si el destinatario es diferente de 0, debe de existir un mapa destino (<DE>) que informe el destino
para la salida.
En el caso de copy fijo el mapa destinatario ser siempre 0, como el front-end conocer el
destinatario.
Puede haber varios mapas <OC> con estructura de copy BMS solo en caso de copy fijo, y ambos
tipos son exclusivos (por ejemplo, el mensaje puede contener varios <OC> de tipo BMS o uno de
tipo copy)
Longitud maxima: 20 Kb.
- 24 -
4.1
Introduccin.
4.2
Programacin Multihilo.
- 25 -
El proceso sigue en ejecucin mientras, al menos uno de sus hilos de ejecucin siga activo.
Cuando el proceso finaliza, todos sus hilos de ejecucin tambin han terminado. Asimismo en el
momento en el que todos los hilos de ejecucin finalizan, el proceso no existe ms y todos sus
recursos son liberados.
Algunos lenguajes de programacin tienen las caractersticas de diseo expresamente creadas
para permitir a los programadores lidiar con hilos de ejecucin (como Java o Delphi, etc). Otros (la
mayora) desconocen la existencia de hilos de ejecucin y stos deben ser creados mediante
llamadas de biblioteca especiales que dependen del sistema operativo en el que estos lenguajes
estn siendo utilizados (como es el caso del C y de C++).
Un ejemplo de la utilizacin de hilos, es tener un hilo atento a la interfaz grafica de usuario (en los
iconos, botones, ventanas), mientras otro hilo hace una larga operacin internamente. De esta
manera el programa responde de manera ms gil a la interaccin con el usuario. Tambin pueden
ser utilizados por una aplicacin servidora para dar servicio a mltiples clientes.
4.3
- 26 -
4.4
El OpenMP C y C++ APIs permite escribir aplicaciones que efectivamente usen mltiples
procesadores. Visual C++ soporta la versin OpenMP 2.0 Standard, el cual forma parte de Visual
Studio 2008, versin que se genero el cdigo para que la aplicacin soporte paralelismo.
Directive
Description
atomic
barrier
Synchronizes all threads in a team; all threads pause at the barrier, until all threads execute
the barrier.
critical
flush (OpenMP)
Specifies that all threads have the same view of memory for all shared objects.
for (OpenMP)
Causes the work done in a for loop inside a parallel region to be divided among threads.
master
Specifies that only the master threadshould execute a section of the program.
Specifies that code under a parallelized for loop should be executed like a sequential loop.
parallel
Defines a parallel region, which is code that will be executed by multiple threads in parallel.
sections (OpenMP)
single
Lets you specify that a section of code should be executed on a single thread, not necessarily
the master thread.
threadprivate
parallel. Define una regin paralela, la cual es el cdigo que ser ejecutado por mltiples hilos en
paralelo.
#pragma omp parallel [clauses]
{
block de codigo
}
Donde,
clause (optional)
Cero o mas clausulas.
En seguida se muestran las clusulas soportadas por la directiva parallel.
copyin
default (OpenMP)
firstprivate
if (OpenMP)
num_threads
private (OpenMP)
reduction
shared (OpenMP)
- 27 -
- 28 -
5 Criptografa.
5.1
Introduccin
- 29 -
La criptografa de Triple DES se llama al algoritmo que hace triple cifrado de tipo DES. Tambin es
conocido como TDES o 3DES, fue desarrollado por IBM en 1998.
Algoritmo. No llega a ser un cifrado mltiple, porque no son independientes todas las subclases.
Este hecho se basa en que DES tiene la caracterstica matemtica de no ser un grupo, lo que
implica que si se cifra el mismo bloque dos veces con dos claves diferentes se aumenta el tamao
efectivo de la clave.
La variante ms simple del Triple DES funciona de la siguiente manera:
Donde
es el mensaje a cifrar y ,
y
las respectivas claves DES. En la variante 3TDES
las tres claves son diferentes; en la variante 2TDES, la primera y tercera clave son iguales.
Seguridad. Cuando se descubri que una clave de 56 bits no era suficiente para evitar un ataque
de fuerza bruta, TDES fue elegido como forma de agrandar el largo de la clave sin necesidad de
cambiar de algoritmo de cifrado. Este mtodo de cifrado es inmune al ataque por encuentro a
medio camino, doblando la longitud efectiva de la clave (112 bits), pero en cambio es preciso
triplicar el nmero de operaciones de cifrado, haciendo este mtodo de cifrado muchsimo ms
seguro que el DES. Por tanto, la longitud de la clave usada ser de 192 bits, aunque como se ha
dicho su eficacia solo sea de 112 bits.
Usos. El Triple DES est desapareciendo lentamente, siendo reemplazado por el algoritmo AES.
Sin embargo, la mayora de las tarjetas de crdito y otros medios de pago electrnicos tienen como
estndar el algoritmo Triple DES (anteriormente usaban el DES). Por su diseo, el DES y por lo
tanto el TDES son algoritmos lentos. AES puede llegar a ser hasta 6 veces ms rpido y a la fecha
no se ha encontrado ninguna vulnerabilidad.
Base 64, es un sistema de numeracin posicinala que usa el 64 como base. Es la mayor
potencia de dos que puede ser representada usando nicamente los caracteres imprimibles de
ASCII. Esto ha propiciado su uso para codificacin de correos electrnicos, PGP y otras
aplicaciones. Todas las variantes famosas que se conocen con el nombre de Base64 usan el rango
de caracteres A-Z, a-z y 0-9 en este orden para los primeros 62 dgitos, pero los smbolos
escogidos para los ltimos dos dgitos varan considerablemente de unas a otras. Otros mtodos
de codificacin como UUEncode y las ltimas versiones de binhex usan un conjunto diferente de
64 caracteres para representar 6 dgitos binarios, pero stos nunca son llamados Base64.
5.2
Para el proyecto se utilizo el algoritmo TDES con una llave de bits para garantizar la
seguridad de la informacin. Tambin se usa el algoritmo de base 64 para garantizar la conversin
de caracteres entres el sistema distribuido y el Host, debido a que uno usa un mapa de caracteres
ASCII y el otro EBCDIC, respectivamente.
- 30 -
Requerimientos.
- 31 -
Host ya cuenta con un servicio de encripcin bajo TDES y Base 64, para que garantice un canal
mas seguro.
Estas dos opciones se presentaron al negocio, indicando que la solucin bajo sockets se requiere
un desarrollo de un modulo para las IGs, as como la adecuacin de las mismas para que puedan
comunicarse bajo este protocolo. El rea de negocio estuvo de acuerdo con el desarrollo y
modificacin, procediendo a la creacin del requerimiento requisitazo y autorizado, ya con el
presupuesto necesario para la solucin.
Por lo anterior, se determino que la solucin ms idnea para el problema es implementarla sobre
un esquema tipo Sockets TCP-IP en distribuido y CICS Bridge Sockets TCP-IP en Host ASTA. De
esto se determina la construccin de un modulo que permita a las aplicaciones distribuidas
concertarse por TCP-IP hacia el Host. Por lo que nace la necesidad de crear la aplicacin
SICOTIP.
Presentacin General.
Se requiere mejorar los tiempos de respuesta de las diferentes aplicaciones distribuidas del
canal de Atencin Telefnica de una empresa Financiera, para comunicarse al sistema central y
disminuir el tiempo total de la llamada de los clientes que accedan a este canal. La solucin
necesita poder contar de un medio que garantice la integridad y seguridad de la informacin (canal
seguro), as como un medio para minimizar las adaptaciones de comunicacin con entidades
externas que provean el servicio de atencin telefnica (Call Center externos), cuando las
necesidades del negocio lo requieran.
Cliente.
Canal de comunicacin de acceso de clientes de un Banco, por va telefnica. A travs de
los nmeros locales o del servicio 01800 a nivel nacional.
Metas.
Mejorar el tiempo de respuesta significativamente al que se cuenta actualmente en el
servicio de atencin telefnica. Mejorar la satisfaccin de atencin y servicio de los clientes o no
clientes por el Banco a travs del medio telefnico. Disminuir el costo de las llamadas, para que en
base a esto poder ofrecer ms opciones o promociones de productos a travs de este canal, que
implica mayores ventas.
Seguridad de la informacin de los clientes en el canal de Atencin Telefnica. La solucin debe
soportar la transaccionalidad de llamadas tanto horarios pico y no pico.
- 32 -
Atributo
Detalles
Tiempo de respuesta
Seguridad
Tolerancia a fallas
Plataforma
- 33 -
6.2
Anlisis.
Casos de Uso.
Diagrama de casos de uso.
- 34 -
- 35 -
- 36 -
- 37 -
- 38 -
Diagrama de Actividades.
- 39 -
6.3
Diseo.
- 40 -
Contratos de operaciones.
Sistema SICOTIP
envioMensaje(mensajeEntrada, tamaoEntrada, mensajeSalida, tamaoSalida)
asignaParametros(IP, Puerto, usoEncripcion)
generaSiguienteTrama(mensajeRespuesta)
Se cuenta con los valores a asignar a los atributos de IP, Puerto y usoEncripcion.
Poscondiciones:
Salida:
Precondiciones:
- 41 -
Se contara con el mensaje a enviar a Host, el cual tambin contara con los datos
necesarios para la solicitud de la informacin al rea central.
Poscondiciones:
Se creara instancia de las clases MD, IH y ME. Se vinculara con la instancia de la clase
PS9.
Se enviara mensaje send(mensaje) a la instancia Socket para enviar la trama por el socket
TCP al Host o al servicio Proxy.
- 42 -
Diagrama de clases.
- 43 -
Diagrama de interaccin.
- 44 -
Diagrama de componentes
- 45 -
6.4
Construccin.
Diagrama de Bloque correspondiente a la construccin del los dos mdulos del sistema SICOTIP.
Aplicacin Conexion:
WinSock
Csockbase
TDESIVR
Ccliente::obj
cte
CServidor
CConexHost
CBase64::objB
ase64
IConexHost
- 46 -
Aplicacin ServerTCP:
WinSock
CCmdTarget
CAboutDlg
Csockbase
CDialog
CServerTCPDlgAutoProx
y
Ccliente::objcte
CServerTCPDlg
CParametros
CCServidor::servidor
CWinApp
CServerTCPApp
- 47 -
6.5
Conclusiones y resultados.
Al finalizar la construccin de los dos mdulos que componen el proyecto, el modulo cliente y el
servidor Proxy-TCP, se procedi a realizar pruebas individuales, despus pruebas nter sistemas.
Posteriormente se realizaron pruebas de volumen en un ambiente de desarrollo ya comunicando
las aplicaciones distribuidas con el Host, se fueron presentando algunas incidencias pero se fueron
resolviendo sin problema.
Para realizar la instalacin e implementacin de las aplicaciones en ambiente de produccin, se
realizo de manera controlada sin presentar algn problema. Inicialmente se realizo un piloto,
integrando sobre este esquema solo una clula, la cual consiste una agrupacin de 10 asesores
telefnicos, sin presentarse algn problema. Posteriormente de un perodo de prueba se fueron
integrando ms clulas, hasta integrar bajo este esquema dos centros de llamada (call centers)
con 300 asesores aproximadamente.
As tambin, se realizo otro piloto para integrar la aplicacin cliente de conexin sockets, para un
IVR, y se fueron integrando mas, hasta integrar los 21 IVRs que se tienen en tres sites, donde cada
IVR cuenta con 90 puertos. Donde cada puerto es equivalente, a una lnea en la cual puede recibir
una llamada, por lo tanto, cada IVR puede recibir simultneamente 90 llamadas al mismo tiempo.
Despus de un par de meses de uso de la aplicacin, en el servidor Proxy, se detecto una
incidencia. La cual ocasionaba que se cruzara la informacin, en la retransmisin de la misma en la
respuesta del Host al servidor Proxy y a su vez del servidor a las aplicaciones cliente donde se
mandaba la peticin original. Despus de un anlisis y la integracin de un log de operaciones de
esta aplicacin, se detecto el problema y en esta ultima versin del cdigo, ya se cuenta con esta
ultima correccin. Donde hasta el momento se sigue trabajando sin problema con las aplicaciones
que estn bajo este esquema.
En la parte del modulo de encripcin, solo se usa para las aplicaciones de Interfaz grafica (Call
Center) debido a que esta pendiente la integracin de este para los IVRs. Para esto, se esta
planeando realizar un piloto, con el fin de determinar el performance y poder medir el tiempo de
respuesta, y saber que no afecte al tiempo actual de respuesta.
En el caso de que se tenga algn problema, o sea, que afecte al performance actual. Entonces, se
tendr que pensar en la alternativa de solucin, como puede ser el Cripto AES. Donde la idea, es
de poder remplazar al de TDES, que en teora es mucho ms rapido y seguro. Se tendra
contemplado desarrollar este modulo, en una siguiente etapa, como un proyecto adoptativo
evolutivo, o sea integrando nueva funcionalidad al sistema actual.
- 48 -
7 Referencias.
- 49 -
// main symbols
/////////////////////////////////////////////////////////////////////////
////
// CConexHost
class ATL_NO_VTABLE CConexHost :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CConexHost, &CLSID_ConexHost>,
public IConexHost
{
public:
CConexHost()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_CONEXHOST)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CConexHost)
COM_INTERFACE_ENTRY(IConexHost)
END_COM_MAP()
// IConexHost
public:
BOOL InsertSubCadCadena(char *subcad, char *cadena, int posini, int
numcaract);
BOOL ObtenSubCadena(char *cadfuente, char *subcaddestino, int
posini, int numcarateres);
int ProcesaEncripcion(char * msgEntrada, char *MsgSalida, int
TipoSolicitud, int *TamSalida);
BOOL GeneraConsecutivoStr4(char *pcadCosecutivo, int pValorActual);
BOOL CountCadena1(char* cadfuente, int * numcarateres);
//STDMETHOD(EnviaMensajeHost)(/*[out,retval]*/ unsigned char*
nDato, unsigned char* ndirIP, int * nPuerto, int * lpnResultado);
STDMETHOD(EnviaMensajeHost)(/*[out,retval]*/ unsigned char* nDato,
unsigned char* nSalida, int * nLonSal, unsigned char* ndirIP, int *
nPuerto, int nTipo, int * lpnResultado);
STDMETHOD(EnviaMsjHostEncripto)(/*[out,retval]*/ unsigned char*
nDato, unsigned char* nSalida, int * nLonSal, unsigned char* ndirIP, int
* nPuerto, int nTipo, int * lpnResultado);
STDMETHOD(ArmaEnvioMEPseudoConversSG_SC)(/*[out,retval]*/ unsigned
char* nStrEntrada, unsigned char* nStrSalidaME, int * nLongTrama, int *
lpnResultado);
STDMETHOD(CountCadena)(/*[out,retval]*/ unsigned char* cadfuente,
int * numcarateres,
int * lpnResultado);
- 50 -
//DEFINICION DE IP Y PUERTO
LPCTSTR lpszSocketAddress =
//LPCTSTR lpszSocketAddress
//LPCTSTR lpszSocketAddress
//LPCTSTR lpszSocketAddress
UINT nSocketPort=*nPuerto;
//UINT nSocketPort=3550; //Produccion
- 51 -
//UINT nSocketPort=3555;
//Produccion
//UINT nSocketPort=3224;
//Test
//char Mensaje[50000]="";
char MensajeRecib[32000]="";
char *pmensaje, *ptrRespuesta=MensajeRecib;
char NumSesion[9]="";
char *lMensajeEntrada=(char *)nDato;
char *lMensajeSalida=(char *)nSalida;
char MensajeError[100]="",lNumError[20]="";
pmensaje=lMensajeEntrada;
//AfxMessageBox(lMensajeEntrada,MB_YESNO);
strcpy((char *)nSalida,"");
WORD wVersionRequested;
WSADATA wsaData;
int err;
BOOL respuesta=false;
wVersionRequested = MAKEWORD( 2, 2 );
//BOOL AfxSocketInit( WSADATA* lpwsaData = NULL );
//respuesta= AfxSocketInit( &wsaData);
/*
/*
/*
/*
/*
*/
*/
*/
*/
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL.
*/
WSACleanup( );
return S_OK;
}
//************************************
/* The WinSock DLL is acceptable. Proceed. */
- 52 -
//************************************
CCliente objcte(lpszSocketAddress,nSocketPort);
//************Validacion si uso de Encripcion******
char MsgSalCripto[32000]="", MsgSub1[32000]="",
MsgSub2[32000]="",strLongitud[10]="";
int ResultCripto=0, tamCripto=0,i=0, *ptrTamCripto=&tamCripto;
char *ptrSub2=MsgSub2;
char tmpcadena[10]="";
for( i=0; i<32000; i++)
{*(nSalida+i)=' ';
}
if (nTipo==0)//Procesa sin Encriptacion
{
Longitud=strlen(lMensajeEntrada);
//objcte.PedirServicio(pmensaje,lMensajeSalida,&Longitud);
objcte.PedirServicio(pmensaje,lMensajeSalida,&Longitud);
for( i=0; i<Longitud; i++)
{if(*(lMensajeSalida+i)=='\0' || *(lMensajeSalida+i)==128)
*(lMensajeSalida+i)=' ' ;
}
/*
_itoa( Longitud,tmpcadena, 10 );
AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
AfxMessageBox(_T(lMensajeSalida) ,MB_YESNO);
*/
nSalida=(unsigned char*) lMensajeSalida;
*nLonSal=Longitud;
}
else //Procesa con Cripto
{
strcpy(MsgSub1,"");
ObtenSubCadena(pmensaje, MsgSub1, 0, 225);
if(nTipo==1)
pmensaje=pmensaje+225;
tamCripto=strlen(pmensaje);
//AfxMessageBox(_T(pmensaje) ,MB_YESNO);
//Realiza la encripvion de la trama ME
//ResultCripto=ProcesaEncripcion(pmensaje,MsgSalCripto,1,&tamCripto);
//Modificacion para que maneje encripcion y desencripcion
//ResultCripto=ProcesaEncripcion(pmensaje,lMensajeSalida,1,&tamCripto);
ResultCripto=ProcesaEncripcion(pmensaje,lMensajeSalida,nTipo,&tamCripto);
//Para fines de prueba, quitar cuando este ok
//nSalida=(unsigned char*) MsgSalCripto;
//AfxMessageBox(_T(lMensajeSalida) ,MB_YESNO);
return S_OK;
//Prueba directa de cripto
- 53 -
/*
ULONG uReturnVal=0;
//char MsgEnt[10000], MsgSal[10000], MngRetornado[32000],
Servicio[2];
char Servicio[2];
char *ptrServ=Servicio;
int *ptrLMsg, LongMens, tamMsg=0, tamMsgSal=0, i=0;
char tmpcadena[10]="";
ptrLMsg=&LongMens;
strcpy(Servicio,"E");
LongMens=strlen(pmensaje);
uReturnVal= TDESCipher(pmensaje, MsgSalCripto, ptrLMsg, Servicio);
//Realiza la cuenta de caracteres diferentes de blanco y cadena
null
tamCripto=0;
for(i=0;i<32000;i++)
{if(*(MsgSalCripto+i)==' ' || *(MsgSalCripto+i)=='\0')
break;
tamCripto++;
}
*(MsgSalCripto+i)='\0';
*/
//_ultoa( tamCripto,tmpcadena, 10 );
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
pmensaje=lMensajeEntrada;
//AfxMessageBox(_T(MsgSalCripto) ,MB_YESNO);
InsertSubCadCadena(MsgSalCripto, MsgSub1, 225, tamCripto);
Longitud=225 + tamCripto;
strcpy(strLongitud,"");
//AfxMessageBox(_T(MsgSub1) ,MB_YESNO);
//Modificar la longitud de salida, anexando lo encriptado
_itoa((Longitud),strLongitud,10);
//AfxMessageBox(_T(strLongitud) ,MB_YESNO);
//char tmpcadena[10]="
";
if(strlen(strLongitud)==1)
{
strcpy(tmpcadena,"0000");
strcat(tmpcadena,strLongitud);
strcpy(strLongitud,tmpcadena );
}
else
if(strlen(strLongitud)==2)
{
strcpy(tmpcadena,"000");
strcat(tmpcadena,strLongitud);
- 54 -
strcpy(strLongitud,tmpcadena );
}
else
if(strlen(strLongitud)==3)
{
strcpy(tmpcadena,"00");
strcat(tmpcadena,strLongitud);
strcpy(strLongitud,tmpcadena );
}
else
if(strlen(strLongitud)==4)
{
strcpy(tmpcadena,"0");
strcat(tmpcadena,strLongitud);
strcpy(strLongitud,tmpcadena );
}
else
//if(strlen(strLongitud)>5)
{
strcpy(strLongitud,"00000");
//Error de longitud
}
InsertSubCadCadena(strLongitud, MsgSub1, 9, 5);
//_ultoa( tamCripto,tmpcadena, 10 );
//AfxMessageBox(_T(strLongitud) ,MB_YESNO);
//AfxMessageBox(_T(MsgSub1) ,MB_YESNO);
//Envia Mensaje Ya encriptado
objcte.PedirServicio(MsgSub1,MsgSub2,&Longitud);
/*
Respuesta mensaje desencriptado:
Para reconocer que un mensaje viene desencriptado an este
parametrizado
como mensaje de entrada y salida encriptado, se va a reconocer
porque el
septimo caracter trae un 7 un 8. Ejemplos:
"<OH>26700000000900163</OH><OC>0000 SESION ASIGNADA 00005 IDAGRD
</OC>"
"<OH>26800000000900163</OH><ER>3200 ERROR DE SESIONAMIENTO CON EL
OWNER 0000005 IDAGRD
</ER>"
*/
- 55 -
*nLonSal=Longitud;
//WSACleanup( );
return S_OK;
}
ResultCripto=ProcesaEncripcion(ptrSub2,MsgSalCripto,2,&tamCripto);
InsertSubCadCadena(MsgSalCripto,MsgSub1,26,tamCripto);
//Tamao total de la trama de respuesta desencriptada
Longitud=26 + tamCripto;
//AfxMessageBox(_T(MsgSub2) ,MB_YESNO);
//AfxMessageBox(_T(MsgSub1) ,MB_YESNO);
FILE *stream;
char strFileName[100]="logcripto.txt";
if( (stream = fopen(strFileName, "a+" )) == NULL )
AfxMessageBox(_T("The file 'logcripto.txt' was not opened")
,MB_YESNO);
/*else
AfxMessageBox(_T("The file 'logcripto.txt' was opened")
,MB_YESNO);
*/
fprintf( stream, "%s\n\t", ptrSub2);
fprintf( stream, "%s\n\t", MsgSalCripto);
- 56 -
strcpy(strLongitud,"");
//_ultoa( tamCripto,strLongitud, 10 );
//AfxMessageBox(_T(strLongitud) ,MB_YESNO);
//nSalida=(unsigned char*) MsgSub1;
*nLonSal=Longitud;
}//************Fin ValidacionProceso de Encripcion**
//WSACleanup( );
return S_OK;
}
STDMETHODIMP CConexHost::EnviaMsjHostEncripto(unsigned char* nDato,
unsigned char* nSalida, int * nLonSal, unsigned char* ndirIP, int *
nPuerto, int nTipo, int *lpnResultado )
{
// Para Llamar la Dll
//HINSTANCE hDLL;
// Handle to DLL
//LPFNDLLFUNC1 lpfnDllFunc1;
// Function pointer
//DWORD dwParam1;
//UINT uParam2, uReturnVal;
//char MsgEnt[161], MsgSal[161];
/*
hDLL = LoadLibrary("D:\\memo\\PruebasTCPIP\\Cripto\\TDESIVR");
if (hDLL != NULL)
{
lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,
"IVRCipher");
if (!lpfnDllFunc1)
{
// handle the error
FreeLibrary(hDLL);
return 0;
}
else
{
// call the function
uReturnVal = lpfnDllFunc1(MsgEnt, MsgSal,);
}
}
*/
//Implementacion de la conenexion a Host
int Error=0;
int Enviados=0;
int Recibidos=0;
int Longitud=0;
int indice =0;
//int nSocketType = SOCK_STREAM,lintBub;
- 57 -
//DEFINICION DE IP Y PUERTO
LPCTSTR lpszSocketAddress = (char *)ndirIP; //DESARROLLO Y TEST
//LPCTSTR lpszSocketAddress = "150.50.102.15"; //DESARROLLO Y TEST
//LPCTSTR lpszSocketAddress = "150.100.246.44"; //PRODUCCION
UINT nSocketPort=*nPuerto;
//UINT nSocketPort=3550; //Produccion
//UINT nSocketPort=3555; //Produccion
//UINT nSocketPort=3224; //Test
//UINT nSocketPort=3216; //puerto Desarrollo
//LPCTSTR lpszSocketAddress = "150.50.102.15"; //Desarrollo
//char Mensaje[200]="<MD>1.0.000636
00030LOGNUSERGENE****IDAGRD
GRD71026
00000000";
//char
Mensaje[2000]="<MD>1.0.000500X1X2X3X4X5X6X7X8X9X0X1X200600LOGNUSERGENE***
*UCQTLBMP
123456789012345678901234000000012006-022010:00:00******************************</MD>";
char Mensaje[50000]="";
char MensajeRecib[10000]="";
char *pmensaje, *ptrRespuesta=MensajeRecib;
char NumSesion[9]="";
char *lMensajeEntrada=(char *)nDato;
char *ptrSalida=(char *)nSalida;
char MensajeError[100]="",lNumError[20]="";
//strcat(Mensaje,"
</MD>");
//pmensaje=Mensaje;
pmensaje=lMensajeEntrada;
//*Para fines de prueba de base 64 y encripcion con triple Des
if (nTipo==1){
CBase64 objBase64;
//objBase64.encodeStr(pmensaje,MensajeRecib,2000);
objBase64.encodeStr(pmensaje,ptrSalida,2000);
AfxMessageBox(_T(pmensaje) ,MB_YESNO);
//AfxMessageBox(_T(ptrSalida) ,MB_YESNO);
FILE *stream;
char strFileName[100]="Logb64.txt";
if( (stream = fopen(strFileName, "a+" )) == NULL )
AfxMessageBox(_T("The file 'Logb64.txt' was not opened")
,MB_YESNO);
/*else
AfxMessageBox(_T("The file 'Logb64.txt' was opened") ,MB_YESNO);
*/
fprintf( stream, "%s\n\t", pmensaje);
fprintf( stream, "%s\n\t", ptrSalida);
- 58 -
else{
CBase64 objBase64;
objBase64.decode(pmensaje,ptrSalida);
//AfxMessageBox(_T(pmensaje) ,MB_YESNO);
//AfxMessageBox(_T(ptrSalida) ,MB_YESNO);
FILE *stream;
char strFileName[100]="Logb64de.txt";
if( (stream = fopen(strFileName, "a+" )) == NULL )
AfxMessageBox(_T("The file 'Logb64.txt' was not opened")
,MB_YESNO);
/*else
AfxMessageBox(_T("The file 'Logb64.txt' was opened") ,MB_YESNO);
*/
fprintf( stream, "%s\n\t", pmensaje);
fprintf( stream, "%s\n\t", ptrSalida);
CCliente objcte(lpszSocketAddress,nSocketPort);
//CCliente ObjCliente("150.50.102.15",3224);
//Longitud=strlen(Mensaje);
//objcte.PedirServicio(pmensaje, Longitud);
// TODO: Add your control notification handler code here
//CSocket sockClient;
//CCteSocket sockClient;
//CAsyncSocket sockClient;
//AfxMessageBox(lMensajeEntrada,MB_YESNO);
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
- 59 -
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL.
*/
return S_OK;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater
*/
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we
*/
/* requested.
*/
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL.
*/
WSACleanup( );
return S_OK;
}
/* The WinSock DLL is acceptable. Proceed. */
//CCliente objcte(lpszSocketAddress,nSocketPort);
//PRUEBA DE TRANSACCION SIN SESION.
//strcpy(Mensaje,"<MD>1.0.032584
00600****USERGENE****UCQTLBMP
x1x2x3x4x5x6x7x8x9x0x1x2000000012006-02-2010:00:00
</MD><IH>26VMXBL01BL00B
UCQTLBMP00000000T2J1
000063611OLBNE</IH><ME>0557C
LINEABAN1111
TC5471550172331772
1234567890123456789012345678901234
123456789012345678901234567890
</ME>");
Longitud=strlen(lMensajeEntrada);
objcte.PedirServicio(pmensaje,ptrRespuesta,&Longitud);
nDato=(unsigned char*) lMensajeEntrada;
WSACleanup( );
return S_OK;
}
int
int
int
int
int
Error=0;
Enviados=0;
Recibidos=0;
Longitud=0;
ind =0;
- 60 -
char
char
char
char
Mensaje[320000]="";
CadComparar[10000]="";
*pmensaje, *ptrmentmp=Mensaje;
*ptrRespuesta=(char *)nStrSalidaME;
char
char
char
char
char
char
*lMensajeEntrada=(char *)nStrEntrada;
MensajeError[100]="",lNumError[20]="";
*strTagIniSG="<SG>";
*strTagFinSG="</SG>";
*strTagIniSC="<SC>";
*strTagFinSC="</SC>";
char strNextTrnId[9]="";
int iNextTrnId=0;
char strAbsNumFirstLine[5]="";
int iAbsNumFirstLine=0;
char strNumLines[5]="";
int inumLines=0;
char strLinelength[5]="";
int iLinelength=0;
char
char
char
char
strIndWaySendTrn[2]="";
strTypeCopy[2]="";
strLenCopy[5]="";
strConsecutivo[5]="";
char strTmp[20]="";
//strcat(Mensaje,"
</MD>");
pmensaje=lMensajeEntrada;
strcpy(ptrRespuesta,"");
CountCadena(nStrEntrada,&Longitud, &Error);
ind=0;
while(*(pmensaje+ind)!='\0' || ind < Longitud)
{
ObtenSubCadena((pmensaje+ind),CadComparar,0,4);
// AfxMessageBox(_T(CadComparar) ,MB_YESNO);
// break;
//Valida que tipo de Trama es SC o SG
if(strcmp(CadComparar,strTagIniSC)==0)
{
pmensaje=pmensaje+ind;
//AfxMessageBox(_T(pmensaje+4) ,MB_YESNO);
//AfxMessageBox(_T(pmensaje+4+8) ,MB_YESNO);
strcpy(CadComparar,"");
ObtenSubCadena((pmensaje+4),CadComparar,ind,8);
//AfxMessageBox(_T(CadComparar) ,MB_YESNO);
ObtenSubCadena((pmensaje+4),strNextTrnId,0,8);
ObtenSubCadena((pmensaje+4+8),strAbsNumFirstLine,0,4);
ObtenSubCadena((pmensaje+4+8+4),strNumLines,0,4);
ObtenSubCadena((pmensaje+4+8+4+4),strLinelength,0,4);
//ObtenSubCadena((pmensaje+4+8+4+4+4),CadComparar,0,4);
//AfxMessageBox(_T(strNextTrnId) ,MB_YESNO);
//AfxMessageBox(_T(strAbsNumFirstLine) ,MB_YESNO);
//AfxMessageBox(_T(strNumLines) ,MB_YESNO);
- 61 -
//AfxMessageBox(_T(strLinelength) ,MB_YESNO);
pmensaje+=(4+8+4+4+4);
//Registro de log de pruebas
FILE *stream;
char strFileName[100]="LogSC.txt";
if( (stream = fopen(strFileName, "a+" )) == NULL
AfxMessageBox(_T("The file 'regMens.txt' was
opened") ,MB_YESNO);
/*else
AfxMessageBox(_T("The file 'regMens.txt' was
,MB_YESNO);
*/
fprintf( stream, "%s\n\t", strNextTrnId);
fprintf( stream, "%s\n\t", strAbsNumFirstLine);
fprintf( stream, "%s\n\t", strNumLines);
fprintf( stream, "%s\n\t", strLinelength);
if( fclose( stream ) )
AfxMessageBox(_T("The file 'regMens.txt' was
closed") ,MB_YESNO);
//Fin registro log de pruebas
strcat(ptrRespuesta,"<ME>");
strcat(ptrRespuesta,strNumLines);
strcat(ptrRespuesta,strLinelength);
inumLines=atoi(strNumLines);
iLinelength=atoi(strLinelength);
)
not
opened")
not
- 62 -
{
strcpy(CadComparar,"");
ObtenSubCadena((pmensaje+i+j),CadComparar,0,5);
if(strcmp(CadComparar,strTagFinSC)==0)
{break;
}
else
*(Mensaje+i*iLinelength+j)=*(pmensaje+ind2+i*iLinelength+j);
}
}
}
ind2++;
}
ind2++;
*/
int i=0,j=0;
for(i=0; i < inumLines; i++)
{
GeneraConsecutivoStr4(strConsecutivo, i);
strcat(Mensaje,strConsecutivo);
//AfxMessageBox(_T(Mensaje) ,MB_YESNO);
for(j=0; j < iLinelength; j++)
{
ObtenSubCadena((pmensaje+i+j),CadComparar,0,5);
if(strcmp(CadComparar,strTagFinSC)==0)
{break;
}
else
*(Mensaje+i*iLinelength+j+4*(i+1))=*(pmensaje+i*iLinelength+j);
}
}
//*(Mensaje+i*iLinelength+j+1)='\0';
*(Mensaje+i*iLinelength+j+4*(i+1)+1)='\0';
strcat(Mensaje,"</ME>");
strcat(ptrRespuesta,Mensaje);
//strcat(CadComparar,strNextTrnId);
//strcat(CadComparar,strAbsNumFirstLine);
//strcat(CadComparar,strNumLines);
//strcat(CadComparar,strLinelength);
//AfxMessageBox(_T(CadComparar) ,MB_YESNO);
if( (stream = fopen(strFileName, "a+" )) == NULL )
AfxMessageBox(_T("The file 'regMens.txt' was not
opened") ,MB_YESNO);
/*else
AfxMessageBox(_T("The file 'regMens.txt' was opened")
,MB_YESNO);
*/
fprintf( stream, "%d\n\t", i*iLinelength+j+1);
if( fclose( stream ) )
- 63 -
- 64 -
strcat(ptrRespuesta,Mensaje);
_itoa( Longitud, strTmp, 10 );
//AfxMessageBox(_T(strTmp) ,MB_YESNO);
break;
}
ind++;
}
//Validar si es correcta la validacion
//if(*(pmensaje+ind)=='\0' || ind < Longitud)
//
return S_FALSE;
//AfxMessageBox(lMensajeEntrada,MB_YESNO);
ULONG uReturnVal=0;
//char MsgEnt[10000], MsgSal[10000], MngRetornado[32000],
Servicio[2];
char Servicio[2];
char *ptrServ=Servicio;
int *ptrLMsg, LongMens, tamMsg=0, tamMsgSal=0, i=0;
char tmpcadena[10]="";
ptrLMsg=&LongMens;
if(TipoSolicitud==1)
strcpy(Servicio,"E");
else
strcpy(Servicio,"D");
LongMens=strlen(msgEntrada);
uReturnVal= TDESCipher(msgEntrada, MsgSalida, ptrLMsg, Servicio,
&tamMsgSal );
//tamMsgSal=0;
- 65 -
if(*Servicio=='E')
{for(i=0;i<32000;i++)
{if(*(MsgSalida+i)==' ' || *(MsgSalida+i)=='\0')
break;
//tamMsgSal++;
}
*(MsgSalida+i)='\0';
}
else
{
for(i=0;i<tamMsgSal;i++)
{if(*(MsgSalida+i)=='\0')
break;
//tamMsgSal++;
}
*(MsgSalida+i)='\0';
}
_itoa( tamMsgSal,tmpcadena, 10 );
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
//AfxMessageBox(_T(MsgSalida) ,MB_YESNO);
*TamSalida=tamMsgSal;
return 0;
}
STDMETHODIMP CConexHost::Cripto(unsigned char* nDato, unsigned char*
nSalida, int* TipoSolicitud, int* TamSalida, int *lpnResultado )
{
ULONG uReturnVal=0;
//char MsgEnt[10000], MsgSal[10000], MngRetornado[32000],
Servicio[2];
char Servicio[2];
char *ptrServ=Servicio;
int *ptrLMsg, LongMens, tamMsg=0, tamMsgSal=0, i=0;
char tmpcadena[10]="";
char *ptrEntrada=(char *)nDato;
char *ptrSalida=(char *)nSalida;
ptrLMsg=&LongMens;
if(*TipoSolicitud==1)
strcpy(Servicio,"E");
else
strcpy(Servicio,"D");
LongMens=strlen(ptrEntrada);
uReturnVal= TDESCipher(ptrEntrada, ptrSalida, ptrLMsg, Servicio,
&tamMsgSal );
//tamMsgSal=0;
if(*Servicio=='E')
{for(i=0;i<32000;i++)
{if(*(ptrSalida+i)==' ' || *(ptrSalida+i)=='\0')
break;
//tamMsgSal++;
}
*(ptrSalida+i)='\0';
}
else
- 66 -
{
for(i=0;i<tamMsgSal;i++)
{if(*(ptrSalida+i)=='\0')
break;
//tamMsgSal++;
}
*(ptrSalida+i)='\0';
}
_itoa( tamMsgSal,tmpcadena, 10 );
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
//AfxMessageBox(_T(MsgSalida) ,MB_YESNO);
*TamSalida=tamMsgSal;
return S_OK;
}
- 67 -
if(indice==0)
return -1;
indice++;
*numcarateres=indice;
return TRUE;
}
- 68 -
}
*/
return TRUE;
}
/***************************************************/
/*-------------------------------------------------*/
/* librera: sockstr.lib
*/
/* Fichero : sockstr.h
*/
/* Proyecto: sockstrlib.dsp
*/
/* WorkSpace: SockStream.dsw
*/
/* Objetivo:
*/
/*
*/
/***************************************************/
#ifndef __MC_SEND
#define __MC_SEND
#include <winsock.h>
#include <afxsock.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
const int DefaultTTL=1;
const int ERRBASE=65536;
const int OK=0;
const int ESEND
=
ERRBASE+1;
const int ERECV
=
ERRBASE+2;
const int ETIMEOUT = ERRBASE+3;
class Csockbase
{
public:
struct sockaddr_in addr;
// direccin
int
lenaddr;
// longitud de la direccion
int
sock;
// socket
int err;
int retval;
};
class CCliente : protected Csockbase
{
public:
CCliente(const char *AddressDest,int Port);
~CCliente();
int PedirServicio(char *bufdatos,char *bufsalida, int *numdatos);
int PedirServicioWin(char *bufdatos,char *bufsalida, int *numdatos);
};
class CServidor : protected Csockbase
{
long bytes_recibidos;
- 69 -
- 70 -
}
int CCliente::PedirServicio(char *bufdatos,char *bufsalida, int
*numdatos)
{
int nummaxrecib=32000, logresp=0, i=0;
char strrecibidos[32000]="",strtmp[2];
char tmpcadena[10]="";
char strrecibbis[32000]="";
int logrespbis=0;
char strCodError[20]="";
//Primero se construye la estructura de timeouts
//Un conjunto de sockets a comprobar si tienen peticiones
fd_set set;
FD_ZERO(&set);
FD_SET(sock,&set);
//...y el tiempo mximo a esperar si hay buffer de entrada
struct timeval tval;
//tval.tv_sec=30;
tval.tv_sec=20;
//tval.tv_sec =0;
tval.tv_usec=0;
err = setsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char *)
&optvalpropio,cbOpt);
if( err==0)
{unsigned int valortmp=optvalpropio;
//itoa( valortmp,tmpcadena, 10 );
- 71 -
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
}
if((logresp=recv(sock,strrecibidos,nummaxrecib,0))<0)
{
logresp=0;
logresp=WSAGetLastError ();
*numdatos=logresp;
_itoa(logresp,strCodError,10);
strcat(strCodError, ":Error al recibir trama...");
//AfxMessageBox(_T(strCodError) ,MB_OK);
return OK;
//throw("Error en recv. Recibiendo respuesta del servidor");
}
else
{
long logrespbis=0;
char strrecibbis[32000]="";
while((logrespbis=recv(sock,strrecibbis,nummaxrecib,0)) > 0)
{
for(long j=0; j<logrespbis; j++)
{*(strrecibidos+logresp+j)=*(strrecibbis+j);
}
*(strrecibidos+logresp+j)='\0';
logresp=logresp+logrespbis;
}
}
/*
if(logresp > 8000 && logresp < 15000)
{
int ind=0;
for(ind=0;ind<32000;ind++)
{strrecibbis[ind]=' ';
}
while(logresp < 19049)
{
if((logrespbis=recv(sock,strrecibbis,nummaxrecib,0))<0)
{
*numdatos=logresp;
AfxMessageBox(_T("Error al recibir trama...") ,MB_OK);
return OK;
}
else
if(logrespbis <=0)
{break;
}
for(long j=0; j<logrespbis; j++)
{*(strrecibidos+logresp+j)=*(strrecibbis+j);
}
*(strrecibidos+logresp+j)='\0';
logresp=logresp+logrespbis;
}
}
*/
- 72 -
FILE *stream;
char strFileName[100]="logMens.txt";
*numdatos=logresp;
if( (stream = fopen(strFileName, "a+" )) == NULL )
AfxMessageBox(_T("The file 'LOGMens.txt' was not opened")
,MB_OK);
for(i=0; i<logresp ; i++)
{if(*(strrecibidos+i)=='\0' || *(strrecibidos+i)=='\n'
|| *(strrecibidos+i)=='\r' )
*(strrecibidos+i)=' ';
//if(*(strrecibidos+i) < 35 || *(strrecibidos+i)> 125 ||
*(strrecibidos+i) ==0)
if(*(strrecibidos+i) < 20 || *(strrecibidos+i)> 125 )
{
//char *caracter;
//*caracter= *(strrecibidos+i);
//fprintf( stream, "%s", (strrecibidos+i));
strtmp[0]=*(strrecibidos+i);
strtmp[1]='\0';
fprintf( stream, "%c", strtmp);
//fprintf( stream, "%s\n\t", MensajeRecib);
*(strrecibidos+i)=' ';
}
*(bufsalida+i)=*(strrecibidos+i);
}
*(bufsalida+i)='\0';
fprintf( stream, "\n\t");
if( fclose( stream ) )
AfxMessageBox(_T("The file 'LOGMens.txt' was not closed") ,MB_OK);
//strcpy(bufsalida,strrecibidos);
return OK;
}
int CCliente::PedirServicioWin(char *bufdatos,char *bufsalida, int
*numdatos)
{
int nummaxrecib=32000, logresp=0, i=0;
char strrecibidos[32000]="";
/*
if (send(sock, bufdatos, *numdatos, 0) <0)
throw("Error en send. Envindo peticin al servidor");
//strcpy(bufdatos,"");
if((logresp=recv(sock,strrecibidos,nummaxrecib,0))<0)
{
*numdatos=logresp;
//throw("Error en recv. Recibiendo respuesta del servidor");
}
char tmpcadena[10]="";
_itoa( logresp,tmpcadena, 10 );
AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
- 73 -
*numdatos=logresp;
for(i=0; i<logresp; i++)
{if(*(strrecibidos+i)==0)
*(strrecibidos+i)=' ';
*(bufsalida+i)=*(strrecibidos+i);
}
*(bufsalida+i)='\0';
*/
//strcpy(bufsalida,strrecibidos);
int Error=0;
int Enviados=0;
int Recibidos=0;
int Longitud=0;
int indice =0;
int nSocketType = SOCK_STREAM,lintBub;
BOOL respuesta=FALSE;
//**************************************
//DEFINICION DE IP Y PUERTO por ambiente
//**************************************
LPCTSTR lpszSocketAddress = "150.50.102.15"; //DESARROLLO Y TEST
UINT nSocketPort=3224; //Test
//LPCTSTR lpszSocketAddress = "150.50.102.15"; //Desarrollo
//UINT nSocketPort=3216; //puerto Desarrollo
//LPCTSTR lpszSocketAddress = "150.100.246.44";
//UINT nSocketPort=3550; //Produccion
//UINT nSocketPort=3555; //Produccion
//PRODUCCION
- 74 -
if ((Enviados=sockClient.Send(bufdatos, *numdatos))<0)
{
Error=sockClient.GetLastError ();
}
//Error=sockClient.GetLastError ();
lintBub=32000;
if ((Recibidos=sockClient.Receive(strrecibidos,lintBub)) < 0)
{
Error=sockClient.GetLastError ();
}
Longitud=Recibidos;
char tmpcadena[10]="";
_itoa( Recibidos,tmpcadena, 10 );
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
*numdatos=Recibidos;
for(i=0; i<Recibidos; i++)
{if(*(strrecibidos+i)==0)
*(strrecibidos+i)=' ';
*(bufsalida+i)=*(strrecibidos+i);
}
*(bufsalida+i)='\0';
sockClient.Close();
*/
return OK;
}
// Implemenatacion Servidor
CServidor::CServidor(const char *SrcIPAddr,int IPPort)
{
- 75 -
}
CServidor::~CServidor()
{
//destruir la conexion si sigue activa y hacer limpieza
closesocket(sock);
}
//recibe en bufdatos como maximo maxdatos (si hay mas retorna error)
int CServidor::servicio(char *bufdatosIn, char *bufdatosOut, long
maxdatosInOut,
long &datosleidos, int timeout)
{
//Primero se construye la estructura de timeouts
//Un conjunto de sockets a comprobar si tienen peticiones
fd_set set;
FD_ZERO(&set);
FD_SET(sock,&set);
//...y el tiempo mximo a esperar si hay buffer de entrada
struct timeval tval;
tval.tv_sec=0;
tval.tv_usec=timeout;
//se suspende la ejecucin hasta que haya peticin o
//se cumpla el tiempo de espera
int result=select(0,&set,0,0,&tval);
if(result==0) return ETIMEOUT; //retornar si cumple tiempo espera
//hay peticin y se procesa.
int sockacept=accept(sock,(struct sockaddr *) &addr, (int *) &lenaddr
);
if(sockacept==-1)
throw("Error en accept");
//obtenemos datos del socket creado por el sitema para atender
//el servicio
int lenaddrservicio= sizeof addr;
if( getsockname( sockacept, (struct sockaddr *) &addrservicio,
&lenaddrservicio ) ==-1)
throw("Error averiguando sockaddr_in del socket asignado para el
servicio");
//obtenemos los datos del cliente conectado al socket
int lenaddrcliente= sizeof addrcliente;
if( getpeername( sockacept, (struct sockaddr *) &addrcliente,
&lenaddrcliente ) ==-1)
throw("Error averiguando sockaddr_in del socket cliente conectado
a este");
//printf("Socket port #%d\n", ntohs( server.sin_port));
//Con los datos del cliente se podra decidor si se acepta o no
//la peticin...
//Se reciben los datos.
retval=recv(sockacept,bufdatosIn,maxdatosInOut,0);
if (retval==-1)
throw("Error en recv");
datosleidos=retval;
//se hace el procesamiento de los datos. (convertimos a mayusculas!)
for(int i=0;i<datosleidos;i++)
bufdatosOut[i]=toupper(bufdatosIn[i]);
- 76 -
- 77 -
/*++
Module Name:
basetsd.h
Abstract:
Type definitions for the basic sized types.
Author:
Revision History:
- 78 -
--*/
#ifndef _BASETSD_H_
#define _BASETSD_H_
#ifdef __cplusplus
extern "C" {
#endif
//
// The following types are guaranteed to be signed and 32 bits wide.
//
typedef int LONG32, *PLONG32;
typedef int INT32, *PINT32;
//
// The following types are guaranteed to be unsigned and 32 bits wide.
//
typedef unsigned int ULONG32, *PULONG32;
typedef unsigned int DWORD32, *PDWORD32;
typedef unsigned int UINT32, *PUINT32;
//
//
//
//
//
//
//
//
//
//
#ifdef _WIN64
typedef __int64 INT_PTR, *PINT_PTR;
typedef unsigned __int64 UINT_PTR, *PUINT_PTR;
#define MAXINT_PTR (0x7fffffffffffffffI64)
#define MININT_PTR (0x8000000000000000I64)
#define MAXUINT_PTR (0xffffffffffffffffUI64)
typedef unsigned int UHALF_PTR, *PUHALF_PTR;
typedef int HALF_PTR, *PHALF_PTR;
#define MAXUHALF_PTR (0xffffffffUL)
#define MAXHALF_PTR (0x7fffffffL)
#define MINHALF_PTR (0x80000000L)
#pragma warning(disable:4311)
#if !defined(__midl)
__inline
unsigned long
- 79 -
HandleToUlong(
void *h
)
{
return((unsigned long) h );
}
__inline
unsigned long
PtrToUlong(
void *p
)
{
return((unsigned long) p );
}
__inline
unsigned short
PtrToUshort(
void *p
)
{
return((unsigned short) p );
}
__inline
long
PtrToLong(
void *p
)
{
return((long) p );
}
__inline
short
PtrToShort(
void *p
)
{
return((short) p );
}
#endif
#pragma warning(3:4311)
#else
- 80 -
#endif
//
// SIZE_T used for counts or ranges which need to span the range of
// of a pointer. SSIZE_T is the signed variation.
//
typedef UINT_PTR SIZE_T, *PSIZE_T;
typedef INT_PTR SSIZE_T, *PSSIZE_T;
//
// The following types are guaranteed to be signed and 64 bits wide.
//
typedef __int64 LONG64, *PLONG64;
typedef __int64 INT64, *PINT64;
//
// The following types are guaranteed to be unsigned and 64 bits wide.
//
typedef unsigned __int64 ULONG64, *PULONG64;
typedef unsigned __int64 DWORD64, *PDWORD64;
typedef unsigned __int64 UINT64, *PUINT64;
#ifdef __cplusplus
}
#endif
#endif // _BASETSD_H_
- 81 -
Aplicacion ServerTCP:
// Cliente.h: interface for the CCliente class.
//
//////////////////////////////////////////////////////////////////////
#if
!defined(AFX_CLIENTE_H__6E3BAC5A_7C8E_4CC0_AB94_188E0F49659D__INCLUDED_)
#define AFX_CLIENTE_H__6E3BAC5A_7C8E_4CC0_AB94_188E0F49659D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "sockbase.h"
class CCliente : public Csockbase
{
public:
CCliente(const char *AddressDest,int Port);
virtual ~CCliente();
int PedirServicio(char *bufdatos, long numdatos,char *bufsalida, long
*ndatosreciv);
};
#endif //
!defined(AFX_CLIENTE_H__6E3BAC5A_7C8E_4CC0_AB94_188E0F49659D__INCLUDED_)
"stdafx.h"
"ServerTCP.h"
"Cliente.h"
<time.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CCliente::CCliente(const char *AddressDest,int Port)
{
if((sock = socket( AF_INET, SOCK_STREAM, 0 ))==-1)
AfxMessageBox(_T("Error de socket...") ,MB_OK);
//throw ("Error en socket");
memset (&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(AddressDest);
- 82 -
addr.sin_port = htons(Port);
lenaddr=sizeof(addr);
retval=connect(sock,(struct sockaddr *)&addr,lenaddr);
if (retval)
{
char strTmp[10]="";
char strMensaje[50]="";
strcpy(strMensaje,"Error de connect...Codigo: ");
_itoa((retval),strTmp,10);
strcat(strMensaje,strTmp);
//AfxMessageBox(_T(strMensaje) ,MB_OK);
time_t ltime;
time( <ime );
char *strtime=ctime(<ime );
//AfxMessageBox(_T(strtime) ,MB_OK);
strcpy(strTmp,"");
FILE *stream;
char strNameFile[50]="log";
//strncpy( string, "Dogs", 4 );
strncpy(strTmp, strtime,3);
strcat(strNameFile, strTmp);
strncpy(strTmp, strtime+4,3);
strcat(strNameFile, strTmp);
strncpy(strTmp, strtime+8,2);
strcat(strNameFile, strTmp);
strcat(strNameFile, ".txt");
if( (stream = fopen(strNameFile , "a+" )) == NULL )
AfxMessageBox(_T("Error al abrir archivo ") ,MB_OK);
fprintf(stream,"%s ","Error de connect...");
fprintf(stream,"%i\n",retval);
//fscanf(stream,"%s",puerto);
//fscanf(stream,"%s",ip_Host);
//fscanf(stream,"%s",puerto_Host);
fclose(stream);
} //fin if
//throw("Error en connect.");
}
CCliente::~CCliente()
{ //destruir la conexion si sigue activa y hacer limpieza
closesocket(sock);
}
int CCliente::PedirServicio(char *bufdatos, long numdatos, char
*bufsalida, long* ndatosreciv)
{
long dat_maxrecib=32000;
long dat_recib=0;
char buffer[10]="";
int iCodError=0;
fd_set set;
FD_ZERO(&set);
FD_SET(sock,&set);
- 83 -
FILE *stream;
char strNameFile[50]="log";
strncpy(strTmp, strtime,3);
strcat(strNameFile, strTmp);
strncpy(strTmp, strtime+4,3);
strcat(strNameFile, strTmp);
strncpy(strTmp, strtime+8,2);
strcat(strNameFile, strTmp);
strcat(strNameFile, ".txt");
int result=select(0,&set,0,0,&tval);
//for(int i=0;i<10000;i++) ;
- 84 -
//optvalpropio=20000;
err = setsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char *)
&optvalpropio,cbOpt);
if( err < 0)
{unsigned int valortmp=optvalpropio;
//itoa( valortmp,tmpcadena, 10 );
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
fprintf(stream,"Codigo de error de setsockopt: %i\n",numdatos);
}
err = getsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char *)
&optvalpropio,&cbOpt);
if( err < 0)
{char tmpcadena[20]="";
unsigned int valortmp=optvalpropio;
itoa( valortmp,tmpcadena, 10 );
//AfxMessageBox(_T(tmpcadena) ,MB_YESNO);
fprintf(stream,"Codigo de error de getsockopt: %i\n",numdatos);
}
if((dat_recib=recv(sock,bufsalida,dat_maxrecib,0))<0)
{
//AfxMessageBox(_T("Error de recv de Host a Servidor...") ,MB_OK);
fprintf(stream,"Error de recv de Host a Servidor...:
%i\n",numdatos);
fclose(stream);
return -1;
}
else
{
long logrespbis=0;
char strrecibbis[32000]="";
long j=0;
while((logrespbis=recv(sock,strrecibbis,dat_maxrecib,0)) > 0)
{
for(j=0; j<logrespbis; j++)
{*(bufsalida+dat_recib+j)=*(strrecibbis+j);
}
*(bufsalida+dat_recib+j)='\0';
dat_recib=dat_recib+logrespbis;
}
*(bufsalida+dat_recib)='\0';
}
//Cerramos archivo log
fclose(stream);
- 85 -
/*for(int j=0;j++;j<dat_recib)
{
if(*(bufsalida+j)=='\0' || *(bufsalida+j)=='\n'
|| *(bufsalida+j)=='\r')
{*(bufsalida+j)=' ';
}
}*/
FILE *stream;
char strNameFile[50]="log";
strncpy(strTmp, strtime,3);
strcat(strNameFile, strTmp);
strncpy(strTmp, strtime+4,3);
strcat(strNameFile, strTmp);
strncpy(strTmp, strtime+8,2);
strcat(strNameFile, strTmp);
strcat(strNameFile, ".txt");
fclose(stream);
*/
//int AfxMessageBox( LPCTSTR lpszText, UINT nType = MB_OK, UINT
nIDHelp = 0 );
*ndatosreciv=dat_recib;
/*ltoa( dat_recib, buffer, 10 );
AfxMessageBox(buffer,MB_OK,0);
AfxMessageBox(bufdatos,MB_OK,0);*/
return OK;
}
- 86 -
//
#if
!defined(AFX_DLGPROXY_H__93616031_64C9_4AA8_9038_C09957C4D19E__INCLUDED_)
#define AFX_DLGPROXY_H__93616031_64C9_4AA8_9038_C09957C4D19E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CServerTCPDlg;
/////////////////////////////////////////////////////////////////////////
////
// CServerTCPDlgAutoProxy command target
class CServerTCPDlgAutoProxy : public CCmdTarget
{
DECLARE_DYNCREATE(CServerTCPDlgAutoProxy)
CServerTCPDlgAutoProxy();
by dynamic creation
// Attributes
public:
CServerTCPDlg* m_pDialog;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CServerTCPDlgAutoProxy)
public:
virtual void OnFinalRelease();
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CServerTCPDlgAutoProxy();
// Generated message map functions
//{{AFX_MSG(CServerTCPDlgAutoProxy)
// NOTE - the ClassWizard will add and remove member
functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
DECLARE_OLECREATE(CServerTCPDlgAutoProxy)
// Generated OLE dispatch map functions
//{{AFX_DISPATCH(CServerTCPDlgAutoProxy)
// NOTE - the ClassWizard will add and remove member
functions here.
//}}AFX_DISPATCH
DECLARE_DISPATCH_MAP()
DECLARE_INTERFACE_MAP()
- 87 -
};
/////////////////////////////////////////////////////////////////////////
////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately
before the previous line.
#endif //
!defined(AFX_DLGPROXY_H__93616031_64C9_4AA8_9038_C09957C4D19E__INCLUDED_)
"stdafx.h"
"ServerTCP.h"
"DlgProxy.h"
"ServerTCPDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////
////
// CServerTCPDlgAutoProxy
IMPLEMENT_DYNCREATE(CServerTCPDlgAutoProxy, CCmdTarget)
CServerTCPDlgAutoProxy::CServerTCPDlgAutoProxy()
{
EnableAutomation();
// To keep the application running as long as an automation
//
object is active, the constructor calls AfxOleLockApp.
AfxOleLockApp();
// Get access to the dialog through the application's
// main window pointer. Set the proxy's internal pointer
// to point to the dialog, and set the dialog's back pointer to
// this proxy.
ASSERT (AfxGetApp()->m_pMainWnd != NULL);
ASSERT_VALID (AfxGetApp()->m_pMainWnd);
ASSERT_KINDOF(CServerTCPDlg, AfxGetApp()->m_pMainWnd);
m_pDialog = (CServerTCPDlg*) AfxGetApp()->m_pMainWnd;
m_pDialog->m_pAutoProxy = this;
}
CServerTCPDlgAutoProxy::~CServerTCPDlgAutoProxy()
{
// To terminate the application when all objects created with
//
with automation, the destructor calls AfxOleUnlockApp.
// Among other things, this will destroy the main dialog
- 88 -
if (m_pDialog != NULL)
m_pDialog->m_pAutoProxy = NULL;
AfxOleUnlockApp();
}
void CServerTCPDlgAutoProxy::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. The base class will automatically
// deletes the object. Add additional cleanup required for your
// object before calling the base class.
CCmdTarget::OnFinalRelease();
}
BEGIN_MESSAGE_MAP(CServerTCPDlgAutoProxy, CCmdTarget)
//{{AFX_MSG_MAP(CServerTCPDlgAutoProxy)
// NOTE - the ClassWizard will add and remove mapping macros
here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CServerTCPDlgAutoProxy, CCmdTarget)
//{{AFX_DISPATCH_MAP(CServerTCPDlgAutoProxy)
// NOTE - the ClassWizard will add and remove mapping macros
here.
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
// Note: we add support for IID_IServerTCP to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
// {4F07CD07-8179-4624-8EA6-080D1563F8EE}
static const IID IID_IServerTCP =
{ 0x4f07cd07, 0x8179, 0x4624, { 0x8e, 0xa6, 0x8, 0xd, 0x15, 0x63, 0xf8,
0xee } };
BEGIN_INTERFACE_MAP(CServerTCPDlgAutoProxy, CCmdTarget)
INTERFACE_PART(CServerTCPDlgAutoProxy, IID_IServerTCP, Dispatch)
END_INTERFACE_MAP()
// The IMPLEMENT_OLECREATE2 macro is defined in StdAfx.h of this project
// {DA04FF49-EB17-4D98-9CBB-7889A7291471}
IMPLEMENT_OLECREATE2(CServerTCPDlgAutoProxy, "ServerTCP.Application",
0xda04ff49, 0xeb17, 0x4d98, 0x9c, 0xbb, 0x78, 0x89, 0xa7, 0x29, 0x14,
0x71)
/////////////////////////////////////////////////////////////////////////
////
// CServerTCPDlgAutoProxy message handlers
// Parametros.h: interface for the CParametros class.
//
//////////////////////////////////////////////////////////////////////
- 89 -
#if
!defined(AFX_PARAMETROS_H__1B530A4A_C351_47B9_B47D_63ACF2601F44__INCLUDED
_)
#define AFX_PARAMETROS_H__1B530A4A_C351_47B9_B47D_63ACF2601F44__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CParametros
{
public:
int m_puertoHost;
CString m_ipHost;
long maxDatosEntSal;
long tamSalida;
long tamEntrada;
char * pstrDatosSalida;
char * pstrDatosEntrada;
int SockProc;
CParametros();
virtual ~CParametros();
};
#endif //
!defined(AFX_PARAMETROS_H__1B530A4A_C351_47B9_B47D_63ACF2601F44__INCLUDED
_)
- 90 -
// main symbols
/////////////////////////////////////////////////////////////////////////
////
// CServerTCPApp:
// See ServerTCP.cpp for the implementation of this class
//
class CServerTCPApp : public CWinApp
{
public:
CServerTCPApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CServerTCPApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CServerTCPApp)
// NOTE - the ClassWizard will add and remove member
functions here.
//
DO NOT EDIT what you see in these blocks of generated
code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////
////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately
before the previous line.
- 91 -
#endif //
!defined(AFX_SERVERTCP_H__1A43E420_B41F_4C7D_BDD4_8A2EC9E53734__INCLUDED_
)
- 92 -
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls();
shared DLL
#else
Enable3dControlsStatic();
statically
#endif
- 93 -
// Since the dialog has been closed, return FALSE so that we exit
the
// application, rather than start the application's message pump.
return FALSE;
}
// standard constructor
// Dialog Data
//{{AFX_DATA(CServerTCPDlg)
enum { IDD = IDD_SERVERTCP_DIALOG };
CString
m_ipServer;
CString
m_ipHost;
int
m_puertoHost;
int
m_PuertoServer;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CServerTCPDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX);
support
//}}AFX_VIRTUAL
// Implementation
protected:
CServerTCPDlgAutoProxy* m_pAutoProxy;
HICON m_hIcon;
- 94 -
// DDX/DDV
BOOL CanExit();
// Generated message map functions
//{{AFX_MSG(CServerTCPDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClose();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnEjecuta();
afx_msg void OnFin();
afx_msg void OnSetfocusIpServer();
afx_msg void OnModifconfig();
afx_msg void OnCheckConfig();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately
before the previous line.
#endif //
!defined(AFX_SERVERTCPDLG_H__5D44512B_F398_4187_9C0B_E2592151AC9C__INCLUD
ED_)
"stdafx.h"
"ServerTCP.h"
"ServerTCPDlg.h"
"DlgProxy.h"
#include <afxmt.h>
#include "servidor.h"
#include "Parametros.h"
#include <omp.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////
////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
- 95 -
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX);
// DDX/DDV
support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////
////
// CServerTCPDlg dialog
IMPLEMENT_DYNAMIC(CServerTCPDlg, CDialog);
CServerTCPDlg::CServerTCPDlg(CWnd* pParent /*=NULL*/)
: CDialog(CServerTCPDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CServerTCPDlg)
m_ipServer = _T("");
m_ipHost = _T("");
m_puertoHost = 0;
m_PuertoServer = 0;
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in
Win32
- 96 -
}
CServerTCPDlg::~CServerTCPDlg()
{
// If there is an automation proxy for this dialog, set
// its back pointer to this dialog to NULL, so it knows
// the dialog has been deleted.
if (m_pAutoProxy != NULL)
m_pAutoProxy->m_pDialog = NULL;
}
void CServerTCPDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CServerTCPDlg)
DDX_Text(pDX, IDC_IP_SERVER, m_ipServer);
DDV_MaxChars(pDX, m_ipServer, 15);
DDX_Text(pDX, IDC_IP_HOST, m_ipHost);
DDV_MaxChars(pDX, m_ipHost, 15);
DDX_Text(pDX, IDC_PUERTO_HOST, m_puertoHost);
DDV_MinMaxInt(pDX, m_puertoHost, 0, 999999);
DDX_Text(pDX, IDC_PUERTO_SERVER, m_PuertoServer);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CServerTCPDlg, CDialog)
//{{AFX_MSG_MAP(CServerTCPDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CLOSE()
ON_BN_CLICKED(IDEJECUTA, OnEjecuta)
ON_BN_CLICKED(IDC_FIN, OnFin)
ON_EN_SETFOCUS(IDC_IP_SERVER, OnSetfocusIpServer)
ON_BN_CLICKED(IDC_MODIFCONFIG, OnModifconfig)
ON_BN_CLICKED(IDC_CHECK1, OnCheckConfig)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////
////
// CServerTCPDlg message handlers
const int MaxLineas=100;
CEvent EvTerminar(FALSE, TRUE);
BOOL banderaProceso = TRUE;
UINT ThreadProc( LPVOID pdialog)
{
EvTerminar.ResetEvent();
CSingleLock slTerminar(&EvTerminar);
CServerTCPDlg *pSDlg=(CServerTCPDlg *)pdialog;
//CParametros *pParam=(CParametros *)pSDlg->GetDlgItem(IDC_EDIT1);
CString ip_server=pSDlg->m_ipServer;
CString ip_host=pSDlg->m_ipHost;
int puerto_server=pSDlg->m_PuertoServer ;
- 97 -
int puerto_host=pSDlg->m_puertoHost;
char DatosEntrada[32000]="";
char DatosSalida[32000]="";
long cuantosLeidos=0;
long datosenviados=0;
CParametros param;
param.m_ipHost =ip_host;
param.m_puertoHost =puerto_host;
banderaProceso=TRUE;
/*
for(int i=0; i<32000; i++)
{*(DatosEntrada+i)=' ';
*(DatosSalida+i)=' ';
}
*/
//CServidor servidor((LPCSTR)pSDlg->m_IPDir,pSDlg->m_IPPuerto);
//CServidor servidor("150.100.102.142",3220);
CServidor servidor(ip_server,puerto_server);
while(1)
{
for(int i=0; i<32000; i++)
{*(DatosEntrada+i)=' ';
*(DatosSalida+i)=' ';
}
cuantosLeidos=0;
datosenviados=0;
*DatosEntrada='\0';
*DatosSalida='\0';
if(servidor.servicio(DatosEntrada,DatosSalida,32000,cuantosLeidos,datosen
viados,100,param)==OK)
{
//DatosEntrada[cuantosLeidos]=0;
//DatosSalida[cuantosLeidos]=0;
}
else
if(banderaProceso==FALSE)
break;
}//fin while
//falta indicar la direccin de loopback si hay problemas.
return 0;
}
BOOL CServerTCPDlg::OnInitDialog()
{
FILE *stream;
char ip[30]="";
char puerto[30]="";
- 98 -
char ip_Host[30]="";
char puerto_Host[30]="";
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX,
strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this
automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE);
// Set big icon
SetIcon(m_hIcon, FALSE);
// Set small icon
// TODO: Add extra initialization here
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_pAutoProxy = NULL;
CEdit *p_EditIpServer = (CEdit *)GetDlgItem(IDC_IP_SERVER);
p_EditIpServer->EnableWindow(FALSE);
CEdit *p_EditPuertoServer = (CEdit *)GetDlgItem(IDC_PUERTO_SERVER);
p_EditPuertoServer->EnableWindow(FALSE);
CEdit *p_EditIpHost = (CEdit *)GetDlgItem(IDC_IP_HOST);
p_EditIpHost->EnableWindow(FALSE);
CEdit *p_EditPuertoHost = (CEdit *)GetDlgItem(IDC_PUERTO_HOST);
p_EditPuertoHost->EnableWindow(FALSE);
CButton *p_BotonModifica=(CButton *)GetDlgItem(IDC_MODIFCONFIG);
p_BotonModifica->EnableWindow(FALSE);
//Anexar datos de Archivo
//Abre el archivo en la ruta actual del ejecutable, en este caso
del proyecto.
if( (stream = fopen( "ippuerto.txt", "r+" )) == NULL )
return TRUE;
fscanf(stream,"%s",ip);
fscanf(stream,"%s",puerto);
fscanf(stream,"%s",ip_Host);
fscanf(stream,"%s",puerto_Host);
fclose(stream);
//AfxMessageBox(_T(ip) ,MB_OK);
//AfxMessageBox(_T(puerto) ,MB_OK);
//AfxMessageBox(_T(ip_Host) ,MB_OK);
- 99 -
//AfxMessageBox(_T(puerto_Host) ,MB_OK);
m_ipServer = _T(ip);
m_PuertoServer = atoi( puerto );
m_ipHost = _T(ip_Host);
m_puertoHost = atoi(puerto_Host);
UpdateData(FALSE);
return TRUE; // return TRUE
}
void CServerTCPDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code
below
// to draw the icon. For MFC applications using the document/view
model,
// this is automatically done for you by the framework.
void CServerTCPDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user
drags
// the minimized window.
- 100 -
HCURSOR CServerTCPDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
// Automation servers should not exit when a user closes the UI
// if a controller still holds on to one of its objects. These
// message handlers make sure that if the proxy is still in use,
// then the UI is hidden but the dialog remains around if it
// is dismissed.
void CServerTCPDlg::OnClose()
{
if (CanExit())
CDialog::OnClose();
}
void CServerTCPDlg::OnOK()
{
if (CanExit())
CDialog::OnOK();
}
void CServerTCPDlg::OnCancel()
{
if (CanExit())
CDialog::OnCancel();
}
BOOL CServerTCPDlg::CanExit()
{
// If the proxy object is still around, then the automation
// controller is still holding on to this application. Leave
// the dialog around, but hide its UI.
if (m_pAutoProxy != NULL)
{
ShowWindow(SW_HIDE);
return FALSE;
}
return TRUE;
}
void CServerTCPDlg::OnEjecuta()
{
// TODO: Add your control notification handler code here
EvTerminar.SetEvent();
AfxBeginThread(ThreadProc,this);
/*
char DatosEntrada[32000];
char DatosSalida[32000];
long cuantosLeidos;
long datosenviados;
banderaProceso=TRUE;
//CServidor servidor((LPCSTR)pSDlg->m_IPDir,pSDlg->m_IPPuerto);
- 101 -
CServidor servidor("150.100.102.142",3220);
while(1)
{
if(servidor.servicio(DatosEntrada,DatosSalida,32000,cuantosLeidos,datosen
viados,100)==OK)
{
}
else
if(banderaProceso==FALSE)
break;
}//fin while
*/
- 102 -
{
CEdit *p_EditIpServer = (CEdit *)GetDlgItem(IDC_IP_SERVER);
p_EditIpServer->EnableWindow(TRUE);
CEdit *p_EditPuertoServer = (CEdit
*)GetDlgItem(IDC_PUERTO_SERVER);
p_EditPuertoServer->EnableWindow(TRUE);
CEdit *p_EditIpHost = (CEdit *)GetDlgItem(IDC_IP_HOST);
p_EditIpHost->EnableWindow(TRUE);
CEdit *p_EditPuertoHost = (CEdit
*)GetDlgItem(IDC_PUERTO_HOST);
p_EditPuertoHost->EnableWindow(TRUE);
CButton *p_BotonModifica=(CButton
*)GetDlgItem(IDC_MODIFCONFIG);
p_BotonModifica->EnableWindow(TRUE);
}
else
{
CEdit *p_EditIpServer = (CEdit *)GetDlgItem(IDC_IP_SERVER);
p_EditIpServer->EnableWindow(FALSE);
CEdit *p_EditPuertoServer = (CEdit
*)GetDlgItem(IDC_PUERTO_SERVER);
p_EditPuertoServer->EnableWindow(FALSE);
CEdit *p_EditIpHost = (CEdit *)GetDlgItem(IDC_IP_HOST);
p_EditIpHost->EnableWindow(FALSE);
CEdit *p_EditPuertoHost = (CEdit
*)GetDlgItem(IDC_PUERTO_HOST);
p_EditPuertoHost->EnableWindow(FALSE);
CButton *p_BotonModifica=(CButton
*)GetDlgItem(IDC_MODIFCONFIG);
p_BotonModifica->EnableWindow(FALSE);
}
}
- 103 -
int GetPort();
char *GetAddr();
int GetPortUltimoServicio();
char *GetAddrUltimoServicio();
int GetPortUltimoCliente();
char *GetAddrUltimoCliente();
};
#endif //
!defined(AFX_SERVIDOR_H__5B8F2810_EE0F_43E0_B391_8ACCCA49E3E5__INCLUDED_)
"stdafx.h"
"ServerTCP.h"
"Servidor.h"
"Cliente.h"
"Parametros.h"
<time.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CServidor::CServidor(const char *SrcIPAddr,int IPPort)
{
if (( sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
AfxMessageBox(_T("Error de socket...") ,MB_OK);
//throw("Error creando socket SOCK_STREAM");
memset(&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
if(!SrcIPAddr)
addr.sin_addr.s_addr = INADDR_ANY;
else
addr.sin_addr.s_addr= inet_addr(SrcIPAddr);
addr.sin_port = htons(IPPort);
lenaddr=sizeof(addr);
//Se asocia el socket TCP a la direccion de recepcion,
//Es la direccion de escucha del Servidor
if (bind (sock, (struct sockaddr *) &addr, lenaddr) == -1 )
AfxMessageBox(_T("Error de bind...") ,MB_OK);
//throw ("Error en bind");
if(getsockname(sock,(struct sockaddr *)&addr,&lenaddr)==-1)
AfxMessageBox(_T("Error de getsockname...") ,MB_OK);
//throw ("error en getsockname");
listen(sock,5);
}
- 104 -
- 105 -
int j=0;
for( j=0; j < 5;j++)
*(cadTamTrama+j)=*(ptrMsg1+9+j);
*(cadTamTrama+j)='\0';
j=0;
j = atoi(cadTamTrama);
//Modificacion y se comenta para usar la long que viene en el MD
*(ptrMsg1+j)='\0';
//*(ptrMsg1+iErrorLong)='\0';
//fclose(stream);
//Fin manejo de archivo log
// throw("Error en recv");
//***************************
//Retrasmite la informacion a la IP de Host
CCliente objCte(ptrobjParametros->m_ipHost,ptrobjParametros>m_puertoHost);
//CCliente objCte("150.50.102.15",3224);
//comentado para pruebas
//objCte.PedirServicio(ptrobjParametros>pstrDatosEntrada,ptrobjParametros->tamEntrada,ptrobjParametros>pstrDatosSalida,(long *)&ptrobjParametros->tamSalida );
if( (stream = fopen(strNameFile , "a+" )) == NULL )
AfxMessageBox(_T("Error al abrir archivo log*.txt...") ,MB_OK);
if(*ptrMsg1==' ' || *ptrMsg1=='\0')
{
//AfxMessageBox(_T("Error al recibir trama entrada en servidor")
,MB_OK);
fprintf(stream,"Trama erronea: %s\n",ptrobjParametros>pstrDatosEntrada);
fclose(stream);
return -1;
}
fclose(stream);
//Se comenta oara correccion de problema
//objCte.PedirServicio(ptrMsg1,ptrobjParametros>tamEntrada,ptrobjParametros->pstrDatosSalida,(long *)&ptrobjParametros>tamSalida );
objCte.PedirServicio(ptrMsg1,iErrorLong,ptrobjParametros>pstrDatosSalida,(long *)&ptrobjParametros->tamSalida );
//fprintf(stream,"Trama respuesta: %s\n",ptrobjParametros>pstrDatosSalida);
- 106 -
//recibe en bufdatos como maximo maxdatos (si hay mas retorna error)
int CServidor::servicio(char *bufdatosIn, char *bufdatosOut, long
maxdatosInOut,
long &datosleidos,long &datosenviados, int
timeout, CParametros parametros)
{
//Primero se construye la estructura de timeouts
//Un conjunto de sockets a comprobar si tienen peticiones
fd_set set;
FD_ZERO(&set);
FD_SET(sock,&set);
//...y el tiempo mximo a esperar si hay buffer de entrada
struct timeval tval;
tval.tv_sec=10;
tval.tv_usec=timeout;
//se suspende la ejecucin hasta que haya peticin o
//se cumpla el tiempo de espera
//se modifico para validar el tiempo de espera a indefinido.
int result=select(0,&set,0,0,NULL);
//int result=select(0,&set,0,0,&tval);
if(result==0) return ETIMEOUT; //retornar si cumple tiempo espera
//hay peticin y se procesa.
int sockacept=accept(sock,(struct sockaddr *) &addr, (int *) &lenaddr
);
- 107 -
if(sockacept==-1)
{
AfxMessageBox(_T("Error de accept...") ,MB_OK);
return EACCEPT;
}
//throw("Error en accept");
//obtenemos datos del socket creado por el sitema para atender
//el servicio
/*
int lenaddrservicio= sizeof addr;
if( getsockname( sockacept, (struct sockaddr *) &addrservicio,
&lenaddrservicio ) ==-1)
throw("Error averiguando sockaddr_in del socket asignado para el
servicio");
int lenaddrcliente= sizeof addrcliente;
if( getpeername( sockacept, (struct sockaddr *) &addrcliente,
&lenaddrcliente ) ==-1)
throw("Error averiguando sockaddr_in del socket cliente conectado
a este");
*/
//printf("Socket port #%d\n", ntohs( server.sin_port));
//Con los datos del cliente se podra decidor si se acepta o no
//la peticin...
//Se reciben los datos.
//retval=recv(sockacept,bufdatosIn,maxdatosInOut,0);
//if (retval==-1)
// throw("Error en recv");
//xxdatosleidos=retval;
//char cadena[32000]="";
- 108 -
//***************************
//Retrasmite la informacion a la IP de Host
//CCliente objCte("150.50.102.15",3224);
//objCte.PedirServicio(bufdatosIn,retval,bufdatosOut,&datosleidos);
//***************************
//Fin de Retrasmite la informacion a la IP de Host
//devolvemos los resultados
//if (send(sockacept,bufdatosOut,datosleidos,0) <0)
// throw("Error en send contestando al cliente");
//damos por terminada la comunicacin.
//closesocket(sockacept);
return OK;
}
int CServidor::GetPort()
{
return ntohs(addr.sin_port);
}
char *CServidor::GetAddr()
{
return inet_ntoa(addr.sin_addr);
}
int CServidor::GetPortUltimoServicio()
{
return ntohs(addrservicio.sin_port);
}
char *CServidor::GetAddrUltimoServicio()
{
return inet_ntoa(addrservicio.sin_addr);
}
int CServidor::GetPortUltimoCliente()
{
return ntohs(addrcliente.sin_port);
}
char *CServidor::GetAddrUltimoCliente()
{
return inet_ntoa(addrcliente.sin_addr);
}
- 109 -
<Afxsock.h>
<winsock.h>
<sys/types.h>
<stdio.h>
int
int
int
int
int
int
ERRBASE=65536;
OK=0;
ESEND
=
ERRBASE+1;
ERECV
=
ERRBASE+2;
ETIMEOUT = ERRBASE+3;
EACCEPT = ERRBASE+4;
class Csockbase
{
public:
struct sockaddr_in addr;
int
lenaddr;
int
sock;
int err;
int retval;
Csockbase();
virtual ~Csockbase();
// direccin
// longitud de la direccion
// socket
};
#endif //
!defined(AFX_SOCKBASE_H__9C4836F8_DA0A_4A10_B931_1724EAF90048__INCLUDED_)
- 110 -
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Csockbase::Csockbase()
{
}
Csockbase::~Csockbase()
{
}
#include <afxwin.h>
// MFC core and standard components
#include <afxext.h>
// MFC extensions
#include <afxdisp.h>
// MFC Automation classes
#include <afxdtctl.h>
// MFC support for Internet Explorer 4
Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>
// MFC support for Windows Common
Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxsock.h>
- 111 -
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately
before the previous line.
#endif //
!defined(AFX_STDAFX_H__21013768_D8C6_4A23_9000_9DF0CC1E49B2__INCLUDED_)
- 112 -
The following ifdef block is the standard way of creating macros which make exporting
from a DLL simpler. All files within this DLL are compiled with the TDESIVR_EXPORTS
symbol defined on the command line. this symbol should not be defined on any project
that uses this DLL. This way any other project whose source files include this file see
TDESIVR_API functions as being imported from a DLL, wheras this DLL sees symbols
defined with this macro as being exported.
#ifdef TDESIVR_EXPORTS
#define TDESIVR_API __declspec(dllexport)
#else
#define TDESIVR_API __declspec(dllimport)
#endif
- 113 -
TDESIVR.cpp
// TDESIVR.cpp : Defines the entry point for the DLL application.
//
#include
#define
#include
#include
"StdAfx.h"
TDESIVR_EXPORTS
"TDESIVR.h"
"CnvBase64.h"
s_RowBit_Type
struct
{
int
int
int
int
s_ColBit_Type
s_RowByte_H;
s_RowBit_H;
s_RowByte_L;
s_RowBit_L;
s_ColByte_1;
s_ColBit_1;
s_ColByte_2;
s_ColBit_2;
- 114 -
int
int
int
int
s_ColByte_3;
s_ColBit_3;
s_ColByte_4;
s_ColBit_4;
};
/** Area de definicin de constantes
*********************************************************/
static struct find_a_bit IP_L0 [32] =
{{07,01},{06,01},{05,01},{04,01},{03,01},{02,01},{01,01},{00,01},
{07,03},{06,03},{05,03},{04,03},{03,03},{02,03},{01,03},{00,03},
{07,05},{06,05},{05,05},{04,05},{03,05},{02,05},{01,05},{00,05},
{07,07},{06,07},{05,07},{04,07},{03,07},{02,07},{01,07},{00,07}};
static struct find_a_bit IP_R0 [32] =
{{07,00},{06,00},{05,00},{04,00},{03,00},{02,00},{01,00},{00,00},
{07,02},{06,02},{05,02},{04,02},{03,02},{02,02},{01,02},{00,02},
{07,04},{06,04},{05,04},{04,04},{03,04},{02,04},{01,04},{00,04},
{07,06},{06,06},{05,06},{04,06},{03,06},{02,06},{01,06},{00,06}};
static struct find_a_bit E [48] =
{{03,07},{00,00},{00,01},{00,02},{00,03},{00,04},{00,03},{00,04},
{00,05},{00,06},{00,07},{01,00},{00,07},{01,00},{01,01},{01,02},
{01,03},{01,04},{01,03},{01,04},{01,05},{01,06},{01,07},{02,00},
{01,07},{02,00},{02,01},{02,02},{02,03},{02,04},{02,03},{02,04},
{02,05},{02,06},{02,07},{03,00},{02,07},{03,00},{03,01},{03,02},
{03,03},{03,04},{03,03},{03,04},{03,05},{03,06},{03,07},{00,00}};
static struct find_a_bit P [32] =
{{01,07},{00,06},{02,03},{02,04},{03,04},{01,03},{03,03},{02,00},
{00,00},{01,06},{02,06},{03,01},{00,04},{02,01},{03,06},{01,01},
{00,01},{00,07},{02,07},{01,05},{03,07},{03,02},{00,02},{01,00},
{02,02},{01,04},{03,05},{00,05},{02,05},{01,02},{00,03},{03,00}};
static struct find_a_bit PC_Inv [64] =
{{04,07},{00,07},{05,07},{01,07},{06,07},{02,07},{07,07},{03,07},
{04,06},{00,06},{05,06},{01,06},{06,06},{02,06},{07,06},{03,06},
{04,05},{00,05},{05,05},{01,05},{06,05},{02,05},{07,05},{03,05},
{04,04},{00,04},{05,04},{01,04},{06,04},{02,04},{07,04},{03,04},
{04,03},{00,03},{05,03},{01,03},{06,03},{02,03},{07,03},{03,03},
{04,02},{00,02},{05,02},{01,02},{06,02},{02,02},{07,02},{03,02},
{04,01},{00,01},{05,01},{01,01},{06,01},{02,01},{07,01},{03,01},
{04,00},{00,00},{05,00},{01,00},{06,00},{02,00},{07,00},{03,00}};
static struct s_type s_function [8] =
{0xE0,0x40,0xD0,0x10,0x20,0xF0,0xB0,0x80,0x30,0xA0,0x60,0xC0,0x50,0x90,0x00,0x70,
0x00,0xF0,0x70,0x40,0xE0,0x20,0xD0,0x10,0xA0,0x60,0xC0,0xB0,0x90,0x50,0x30,0x80,
- 115 -
0x40,0x10,0xE0,0x80,0xD0,0x60,0x20,0xB0,0xF0,0xC0,0x90,0x70,0x30,0xA0,0x50,0x00,
0xF0,0xC0,0x80,0x20,0x40,0x90,0x10,0x70,0x50,0xB0,0x30,0xE0,0xA0,0x00,0x60,0xD0,
0x0F,0x01,0x08,0x0E,0x06,0x0B,0x03,0x04,0x09,0x07,0x02,0x0D,0x0C,0x00,0x05,0x0A,
0x03,0x0D,0x04,0x07,0x0F,0x02,0x08,0x0E,0x0C,0x00,0x01,0x0A,0x06,0x09,0x0B,0x05,
0x00,0x0E,0x07,0x0B,0x0A,0x04,0x0D,0x01,0x05,0x08,0x0C,0x06,0x09,0x03,0x02,0x0F,
0x0D,0x08,0x0A,0x01,0x03,0x0F,0x04,0x02,0x0B,0x06,0x07,0x0C,0x00,0x05,0x0E,0x09,
0xA0,0x00,0x90,0xE0,0x60,0x30,0xF0,0x50,0x10,0xD0,0xC0,0x70,0xB0,0x40,0x20,0x80,
0xD0,0x70,0x00,0x90,0x30,0x40,0x60,0xA0,0x20,0x80,0x50,0xE0,0xC0,0xB0,0xF0,0x10,
0xD0,0x60,0x40,0x90,0x80,0xF0,0x30,0x00,0xB0,0x10,0x20,0xC0,0x50,0xA0,0xE0,0x70,
0x10,0xA0,0xD0,0x00,0x60,0x90,0x80,0x70,0x40,0xF0,0xE0,0x30,0xB0,0x50,0x20,0xC0,
0x07,0x0D,0x0E,0x03,0x00,0x06,0x09,0x0A,0x01,0x02,0x08,0x05,0x0B,0x0C,0x04,0x0F,
0x0D,0x08,0x0B,0x05,0x06,0x0F,0x00,0x03,0x04,0x07,0x02,0x0C,0x01,0x0A,0x0E,0x09,
0x0A,0x06,0x09,0x00,0x0C,0x0B,0x07,0x0D,0x0F,0x01,0x03,0x0E,0x05,0x02,0x08,0x04,
0x03,0x0F,0x00,0x06,0x0A,0x01,0x0D,0x08,0x09,0x04,0x05,0x0B,0x0C,0x07,0x02,0x0E,
0x20,0xC0,0x40,0x10,0x70,0xA0,0xB0,0x60,0x80,0x50,0x30,0xF0,0xD0,0x00,0xE0,0x90,
0xE0,0xB0,0x20,0xC0,0x40,0x70,0xD0,0x10,0x50,0x00,0xF0,0xA0,0x30,0x90,0x80,0x60,
0x40,0x20,0x10,0xB0,0xA0,0xD0,0x70,0x80,0xF0,0x90,0xC0,0x50,0x60,0x30,0x00,0xE0,
0xB0,0x80,0xC0,0x70,0x10,0xE0,0x20,0xD0,0x60,0xF0,0x00,0x90,0xA0,0x40,0x50,0x30,
0x0C,0x01,0x0A,0x0F,0x09,0x02,0x06,0x08,0x00,0x0D,0x03,0x04,0x0E,0x07,0x05,0x0B,
0x0A,0x0F,0x04,0x02,0x07,0x0C,0x09,0x05,0x06,0x01,0x0D,0x0E,0x00,0x0B,0x03,0x08,
0x09,0x0E,0x0F,0x05,0x02,0x08,0x0C,0x03,0x07,0x00,0x04,0x0A,0x01,0x0D,0x0B,0x06,
0x04,0x03,0x02,0x0C,0x09,0x05,0x0F,0x0A,0x0B,0x0E,0x01,0x07,0x06,0x00,0x08,0x0D,
0x40,0xB0,0x20,0xE0,0xF0,0x00,0x80,0xD0,0x30,0xC0,0x90,0x70,0x50,0xA0,0x60,0x10,
0xD0,0x00,0xB0,0x70,0x40,0x90,0x10,0xA0,0xE0,0x30,0x50,0xC0,0x20,0xF0,0x80,0x60,
0x10,0x40,0xB0,0xD0,0xC0,0x30,0x70,0xE0,0xA0,0xF0,0x60,0x80,0x00,0x50,0x90,0x20,
0x60,0xB0,0xD0,0x80,0x10,0x40,0xA0,0x70,0x90,0x50,0x00,0xF0,0xE0,0x20,0x30,0xC0,
0x0D,0x02,0x08,0x04,0x06,0x0F,0x0B,0x01,0x0A,0x09,0x03,0x0E,0x05,0x00,0x0C,0x07,
0x01,0x0F,0x0D,0x08,0x0A,0x03,0x07,0x04,0x0C,0x05,0x06,0x0B,0x00,0x0E,0x09,0x02,
0x07,0x0B,0x04,0x01,0x09,0x0C,0x0E,0x02,0x00,0x06,0x0A,0x0D,0x0F,0x03,0x05,0x08,
0x02,0x01,0x0E,0x07,0x04,0x0A,0x08,0x0D,0x0F,0x0C,0x09,0x00,0x03,0x05,0x06,0x0B};
static unsigned char SKE[3] = {'S','K','E'};
static struct key_type TDES_Key[48] = {0x27,0xE4,0x8A,0xDB,0xFF,0xC6,
- 116 -
0xD4,0x33,0xCD,0x5D,0xBB,0x2F,
0x13,0xDE,0x61,0xB6,0x7C,0xFC,
0xC9,0x79,0xE6,0x69,0xBB,0xF7,
0xB0,0xE7,0xCD,0xB7,0xEC,0xBB,
0x51,0x57,0x23,0x6F,0x1F,0x57,
0xE1,0x99,0xF5,0x9F,0xE1,0xFE,
0x95,0xE2,0xC7,0x65,0xDF,0xC5,
0xEC,0x0F,0x5E,0x7E,0xBA,0xD8,
0x66,0xFA,0x09,0xF1,0xF5,0x7F,
0x0B,0xBD,0x72,0x2F,0xBE,0xAA,
0xEC,0x6C,0xDB,0xFC,0x7D,0x77,
0x77,0xE7,0x08,0x2F,0xCA,0xFE,
0x4A,0x9D,0x93,0xD5,0xFD,0xD3,
0x7D,0xA8,0x5F,0xAF,0x86,0x7D,
0x89,0x5F,0xBC,0xF3,0x56,0xFA,
0xB7,0x0D,0x92,0x46,0x4A,0xFB,
0x9C,0xD7,0x4C,0x2F,0xE9,0x64,
0xCA,0x72,0xF8,0x1E,0x75,0x73,
0x9F,0x1E,0x60,0x3F,0x9E,0x8B,
0xA6,0x32,0xB5,0xF0,0xA6,0xFF,
0x85,0x0B,0x3E,0xE4,0xBA,0xC4,
0xB8,0xC0,0x35,0x95,0x61,0x6E,
0x72,0x01,0xEE,0x7F,0x53,0x12,
0xC5,0x3F,0x08,0xA3,0x1F,0x67,
0xA8,0x6E,0x3D,0xA7,0xF0,0xB9,
0x8A,0x29,0x6A,0x49,0x78,0xDF,
0x3E,0xD8,0x2C,0x7C,0x4C,0xBC,
0x4E,0x02,0xDE,0x59,0xBF,0x26,
0x9F,0x94,0x1C,0xA3,0x97,0x78,
0x7E,0x22,0xB1,0xD7,0xB9,0x59,
0x42,0x5B,0x4B,0xE0,0xED,0xD2,
0x6F,0x10,0xA7,0x6A,0x58,0x3E,
0x09,0xB7,0x29,0x8A,0xCD,0xB2,
0xC1,0x1C,0xDB,0x8D,0x6F,0x11,
0x75,0xEA,0xC0,0xFB,0x42,0x50,
0x12,0xFD,0x82,0xD1,0xC3,0x0E,
0x78,0x25,0x57,0x94,0x36,0x8C,
0x65,0xC4,0x0D,0xF8,0x32,0xE5,
0x43,0x81,0xB6,0x32,0xEA,0xAB,
0xD2,0xC6,0x69,0x22,0x6D,0x8F,
0xC9,0xDB,0x02,0xAE,0x11,0x97,
0x20,0xBB,0xCF,0xC7,0x43,0xE3,
0x31,0x74,0x43,0x56,0x8B,0x49,
0x61,0x4D,0xF0,0xD2,0x95,0x5C,
0xD4,0xE1,0x95,0x49,0xB7,0xA8,
0x17,0x87,0x13,0x78,0x7C,0x29,
0xEA,0x6B,0x09,0x3A,0xDC,0x65};
static unsigned char SKD[3] = {'S','K','D'};
static struct key_type unTDES_Key[48] = {0xEA,0x6B,0x09,0x3A,0xDC,0x65,
0x17,0x87,0x13,0x78,0x7C,0x29,
0xD4,0xE1,0x95,0x49,0xB7,0xA8,
0x61,0x4D,0xF0,0xD2,0x95,0x5C,
0x31,0x74,0x43,0x56,0x8B,0x49,
0x20,0xBB,0xCF,0xC7,0x43,0xE3,
0xC9,0xDB,0x02,0xAE,0x11,0x97,
0xD2,0xC6,0x69,0x22,0x6D,0x8F,
0x43,0x81,0xB6,0x32,0xEA,0xAB,
0x65,0xC4,0x0D,0xF8,0x32,0xE5,
0x78,0x25,0x57,0x94,0x36,0x8C,
0x12,0xFD,0x82,0xD1,0xC3,0x0E,
0x75,0xEA,0xC0,0xFB,0x42,0x50,
0xC1,0x1C,0xDB,0x8D,0x6F,0x11,
0x09,0xB7,0x29,0x8A,0xCD,0xB2,
0x6F,0x10,0xA7,0x6A,0x58,0x3E,
0x42,0x5B,0x4B,0xE0,0xED,0xD2,
0x7E,0x22,0xB1,0xD7,0xB9,0x59,
0x9F,0x94,0x1C,0xA3,0x97,0x78,
0x4E,0x02,0xDE,0x59,0xBF,0x26,
0x3E,0xD8,0x2C,0x7C,0x4C,0xBC,
- 117 -
0x8A,0x29,0x6A,0x49,0x78,0xDF,
0xA8,0x6E,0x3D,0xA7,0xF0,0xB9,
0xC5,0x3F,0x08,0xA3,0x1F,0x67,
0x72,0x01,0xEE,0x7F,0x53,0x12,
0xB8,0xC0,0x35,0x95,0x61,0x6E,
0x85,0x0B,0x3E,0xE4,0xBA,0xC4,
0xA6,0x32,0xB5,0xF0,0xA6,0xFF,
0x9F,0x1E,0x60,0x3F,0x9E,0x8B,
0xCA,0x72,0xF8,0x1E,0x75,0x73,
0x9C,0xD7,0x4C,0x2F,0xE9,0x64,
0xB7,0x0D,0x92,0x46,0x4A,0xFB,
0x89,0x5F,0xBC,0xF3,0x56,0xFA,
0x7D,0xA8,0x5F,0xAF,0x86,0x7D,
0x4A,0x9D,0x93,0xD5,0xFD,0xD3,
0x77,0xE7,0x08,0x2F,0xCA,0xFE,
0xEC,0x6C,0xDB,0xFC,0x7D,0x77,
0x0B,0xBD,0x72,0x2F,0xBE,0xAA,
0x66,0xFA,0x09,0xF1,0xF5,0x7F,
0xEC,0x0F,0x5E,0x7E,0xBA,0xD8,
0x95,0xE2,0xC7,0x65,0xDF,0xC5,
0xE1,0x99,0xF5,0x9F,0xE1,0xFE,
0x51,0x57,0x23,0x6F,0x1F,0x57,
0xB0,0xE7,0xCD,0xB7,0xEC,0xBB,
0xC9,0x79,0xE6,0x69,0xBB,0xF7,
0x13,0xDE,0x61,0xB6,0x7C,0xFC,
0xD4,0x33,0xCD,0x5D,0xBB,0x2F,
0x27,0xE4,0x8A,0xDB,0xFF,0xC6};
static struct s_RowBit_Type Row2Use[8] = {0,0,0,5,
0,6,1,3,
1,4,2,1,
2,2,2,7,
3,0,3,5,
3,6,4,3,
4,4,5,1,
5,2,5,7};
static struct s_ColBit_Type Col2Use[8] = {0,1,0,2,0,3,0,4,
0,7,1,0,1,1,1,2,
1,5,1,6,1,7,2,0,
2,3,2,4,2,5,2,6,
3,1,3,2,3,3,3,4,
3,7,4,0,4,1,4,2,
4,5,4,6,4,7,5,0,
5,3,5,4,5,5,5,6};
static unsigned int Ask4Bit[8] = {128,64,32,16,8,4,2,1};
static unsigned int Set_Bit[8] = {128,64,32,16,8,4,2,1};
static unsigned int Clear_Bit[8] = {127,191,223,239,247,251,253,254};
static unsigned int Shifts[16] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};
static char Low_Values[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
/** Area de definicin de funciones
**********************************************************/
void Permuta(char *Ini_Vector,
struct find_a_bit *Perm_Arr,
char *Vector_Fin,
int PosIni,
int PosFin,
int SizeOut);
void ExOr(char *Vector_A,
char *Vector_B,
char *Vector_C,
int BlqSize);
- 118 -
- 119 -
- 120 -
for (S_In_Prc=0;S_In_Prc<8;S_In_Prc++)
{
Row2Proc = GetRow(Vector_Xor,S_In_Prc);
Col2Proc = GetCol(Vector_Xor,S_In_Prc);
Vector_S[(S_In_Prc >> 1)] = Vector_S[(S_In_Prc >> 1)] |
s_function[S_In_Prc].s_val[Row2Proc][Col2Proc];
};
return;
};
/** Ejecuta el cifrado / descifrado de informacin independiente al medio de entrada
*********/
void ExecTDES (char *pInputMsg, char *pOutputMsg, int MsgSize, char Servicio, char *IniCBC)
{
struct key_type *KeyGen;
char Wrk_Key[6];
char *info2TDES;
int infolength;
char *cbc_vec;
char accion;
char
char
char
char
blk2Proc[8];
Vector_S[6];
Vector_Xor[8];
*blkTDES;
char
char
char
char
char
Vector_L[4];
Vector_R[4];
Vector_E[6];
Vector_P[4];
full_vector[8];
int
int
int
int
int
numblks;
blk_num;
TDES_In_Proc;
sub_key;
i;
cbc_vec = IniCBC;
infolength = MsgSize;
info2TDES = pInputMsg;
blkTDES = pOutputMsg;
accion = Servicio;
numblks = infolength / 8;
for (blk_num=0;blk_num<numblks;blk_num++)
{
if ( accion == 'E' )
{
KeyGen = TDES_Key;
ExOr(cbc_vec, info2TDES, blk2Proc, 8);
}
else
{
KeyGen = unTDES_Key;
for ( i=0; i<8; i++ )
{
blk2Proc[i] = info2TDES[i];
};
};
for (TDES_In_Proc = 0;TDES_In_Proc < 3;TDES_In_Proc++)
{
Permuta(blk2Proc, IP_L0, Vector_L, 0, 32, 4);
Permuta(blk2Proc, IP_R0, Vector_R, 0, 32, 4);
- 121 -
- 122 -
for (i=0;i<ciclos3;i++)
{
CnvBase64(MsgIn, MsgOut, 3);
MsgIn += 3;
MsgOut += 4;
};
if (ciclofin > 0)
{
for (i=0;i<ciclofin;i++)
{
FinalBlq[i] = MsgIn[i];
}
CnvBase64(FinalBlq, FinalB64, 3);
for (i=0;i<=ciclofin;i++)
{
MsgOut[i] = FinalB64[i];
}
if (ciclofin == 1)
{
MsgOut += 2;
*MsgOut = '=';
MsgOut += 1;
*MsgOut = '=';
}
else if (ciclofin == 2)
{
MsgOut += 3;
*MsgOut = '=';
}
*finalsize += 4;
}
return;
};
void Base64a256(char *InputMsg, char *OutTDES, int *finalsize)
{
int i;
int ciclos4;
int ciclofin;
char *MsgIn;
char *MsgOut;
int msgSize;
char FinalB256[3];
char FinalBlk[4];
MsgIn = InputMsg;
MsgOut = OutTDES;
msgSize = *finalsize;
MsgIn += msgSize - 1;
while (*MsgIn == '=')
{
msgSize -= 1;
MsgIn -= 1;
}
ciclos4 = msgSize / 4;
ciclofin = msgSize % 4;
MsgIn = InputMsg;
*finalsize = ciclos4 * 3;
*finalsize = *finalsize + (ciclofin * 6/8);
- 123 -
for (i=0;i<ciclos4;i++)
{
CnvBase256(MsgIn, MsgOut, 4);
MsgIn += 4;
MsgOut += 3;
};
if (ciclofin > 0)
{
for (i=0;i<4;i++)
{
FinalBlk[i] = (char) "A";
}
for (i=0;i<ciclofin;i++)
{
FinalBlk[i] = MsgIn[i];
}
CnvBase256(FinalBlk, FinalB256, 4);
ciclofin = (ciclofin * 6) / 8;
for (i=0;i<ciclofin;i++)
{
MsgOut[i] = FinalB256[i];
}
}
return;
};
int ProcTDES(char *InputMsg, char *OutPutMsg, int MsgSize,char Servicio)
{
int lastblksize;
int i;
char *OutTDES;
char lastblock[8];
int B64Size;
int finalsize;
if (Servicio == 'E')
{
finalsize = (MsgSize / 8) * 8;
OutTDES = (char *) malloc(finalsize + 8);
ExecTDES(InputMsg, OutTDES, finalsize, Servicio, Low_Values);
lastblksize = MsgSize & 0x07;
if (lastblksize > 0)
{
for (i=0;i<lastblksize;i++)
{
lastblock[i]= InputMsg[MsgSize-lastblksize+i];
}
for (i=lastblksize;i<8;i++)
{
lastblock[i]= ' ';
}
ExecTDES(lastblock,OutTDES+finalsize,8,Servicio,OutTDES+finalsize-8);
finalsize += 8;
};
Base256a64(OutTDES, OutPutMsg, &finalsize);
}
- 124 -
else
{
B64Size = MsgSize;
finalsize = (B64Size * 6) / 8;
OutTDES = (char *) malloc(finalsize);
Base64a256(InputMsg, OutTDES, &B64Size);
finalsize = B64Size;
ExecTDES(OutTDES,OutPutMsg, finalsize,Servicio,Low_Values);
};
free(OutTDES);
return finalsize;
};
TDESIVR_API long IVRCipher(IQVAL line,
PUSERDLLPARAM32 InputMsg,
PUSERDLLPARAM32 OutputMsg,
PUSERDLLPARAM32 Servicio)
{
int finalsize;
finalsize = ProcTDES(InputMsg->u.ptr,OutputMsg->u.ptr, InputMsg->length,*Servicio>u.ptr);
OutputMsg->length = finalsize;
return 0;
};
TDESIVR_API long TDESCipher(char *InputMsg,
char *OutputMsg,
int *MsgLen,
char *Servicio,
int *OutMsgLen)
{
*OutMsgLen = ProcTDES(InputMsg,OutputMsg, *MsgLen,*Servicio);
return 0;
};
long __stdcall VBCipher(char *InputMsg,
{
int finalsize;
- 125 -