mini_serv
Código comentado línea a línea y paso a paso:
Entregas: mini_serv.c. Flags: gcc -Wall -Wextra -Werror. Sin #define.
Qué pide (en palabras normales)
- Un chat: un servidor TCP en
127.0.0.1y el puerto del argumento. Todo lo que escribe un cliente lo reciben los demás. - Cada cliente tiene un id: 0 el primero, 1 el segundo… nunca se reutilizan.
- Al entrar uno:
server: client N just arriveda los demás. Al irse:server: client N just left. - Cada línea que manda un cliente llega a los demás como
client N: la línea. Un mensaje puede traer varias líneas: cada una con su prefijo. - Sin argumento →
Wrong number of argumentsen stderr, salir con 1. Error de sistema antes de empezar a aceptar (o sin memoria) →Fatal error, salir con 1. - No bloquearse nunca:
selectantes de cadarecv/send. Un cliente que no lee no se desconecta, se salta.
Subject (enunciado original)
Assignment name : mini_serv
Expected files : mini_serv.c
Allowed functions: write, close, select, socket, accept, listen, send, recv, bind, strstr, malloc, realloc, free, calloc, bzero, atoi, sprintf, strlen, exit, strcpy, strcat, memset
--------------------------------------------------------------------------------
Write a program that will listen for client to connect on a certain port on 127.0.0.1 and will let clients to speak with each other
This program will take as first argument the port to bind to
If no argument is given, it should write in stderr "Wrong number of arguments" followed by a \n and exit with status 1
If a System Calls returns an error before the program start accepting connection, it should write in stderr "Fatal error" followed by a \n and exit with status 1
If you cant allocate memory it should write in stderr "Fatal error" followed by a \n and exit with status 1
Your program must be non-blocking but client can be lazy and if they don't read your message you must NOT disconnect them...
Your program must not contains #define preproc
Your program must only listen to 127.0.0.1
The fd that you will receive will already be set to make 'recv' or 'send' to block if select hasn't be called before calling them, but will not block otherwise.
When a client connect to the server:
- the client will be given an id. the first client will receive the id 0 and each new client will received the last client id + 1
- %d will be replace by this number
- a message is sent to all the client that was connected to the server: "server: client %d just arrived\n"
clients must be able to send messages to your program.
- message will only be printable characters, no need to check
- a single message can contains multiple \n
- when the server receive a message, it must resend it to all the other client with "client %d: " before every line!
When a client disconnect from the server:
- a message is sent to all the client that was connected to the server: "server: client %d just left\n"
Memory or fd leaks are forbidden
To help you, you will find the file main.c with the beginning of a server and maybe some useful functions. (Beware this file use forbidden functions or write things that must not be there in your final program)
Warning our tester is expecting that you send the messages as fast as you can. Don't do un-necessary buffer.
Evaluation can be a bit longer than usual...
Hint: you can use nc to test your program
Hint: you should use nc to test your program
Hint: To test you can use fcntl(fd, F_SETFL, O_NONBLOCK) but use select and NEVER check EAGAIN (man 2 send)
[MAIN]
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
int extract_message(char **buf, char **msg)
{
char *newbuf;
int i;
*msg = 0;
if (*buf == 0)
return (0);
i = 0;
while ((*buf)[i])
{
if ((*buf)[i] == '\n')
{
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
if (newbuf == 0)
return (-1);
strcpy(newbuf, *buf + i + 1);
*msg = *buf;
(*msg)[i + 1] = 0;
*buf = newbuf;
return (1);
}
i++;
}
return (0);
}
char *str_join(char *buf, char *add)
{
char *newbuf;
int len;
if (buf == 0)
len = 0;
else
len = strlen(buf);
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
if (newbuf == 0)
return (0);
newbuf[0] = 0;
if (buf != 0)
strcat(newbuf, buf);
free(buf);
strcat(newbuf, add);
return (newbuf);
}
int main() {
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1
servaddr.sin_port = htons(8081);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
if (listen(sockfd, 10) != 0) {
printf("cannot listen\n");
exit(0);
}
len = sizeof(cli);
connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
}
4 piezas
1. Montar el servidor (copiado del main.c del subject)
sock = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(2130706433); // 127.0.0.1
addr.sin_port = htons(atoi(argv[1]));
bind(sock, (struct sockaddr *)&addr, sizeof(addr));
listen(sock, 128);
Cualquiera de estas falla → Fatal error. Después de listen ya estamos aceptando: los errores dejan de ser fatales (menos quedarse sin memoria).
2. El bucle select
rd = wr = all;
select(maxfd + 1, &rd, &wr, NULL, NULL);
for (int fd = 0; fd <= maxfd; fd++)
if (FD_ISSET(fd, &rd))
fd == sock ? add_client() : read_client(fd);
all son los fds abiertos. select modifica lo que le pasas: por eso trabajo con copias. Lectura en el socket de escucha = alguien quiere entrar. Lectura en un cliente = datos, o 0 bytes si se ha ido.
3. Acumular hasta el \n
buf = realloc(bufs[fd], len + n + 1); // lo viejo + lo nuevo
strcpy(buf + len, chunk);
while ((nl = strstr(line, "\n"))) // cada línea completa
{
*nl = '\0';
relay(fd, line);
line = nl + 1;
}
recv devuelve lo que ha llegado: media línea, o tres. Guardo por cliente lo que aún no acaba en \n y reparto solo líneas enteras. strchr y memmove no están permitidos: strstr y una copia nueva.
4. Repartir sin bloquearse
if (fd != from && fd != sock && FD_ISSET(fd, &wr))
send(fd, msg, strlen(msg), 0);
Solo a los que select marcó como listos para escribir. Un cliente vago (no lee) no está en wr: me lo salto y no lo echo. Es la línea que pide "non-blocking".
mini_serv función por función
| Función | Qué hace |
|---|---|
fatal() | Fatal error por stderr y exit(1) |
broadcast(from, msg) | send a todos los listos para escribir menos from y el de escucha |
notify(fd, what) | server: client N just arrived/left a los demás |
add_client() | accept, id nuevo, buffer vacío, al conjunto, aviso |
rm_client(fd) | aviso, free del buffer, fuera del conjunto, close |
relay(fd, line) | client N: línea a los demás |
read_client(fd) | recv, acumular, repartir líneas completas, guardar el resto |
main | argumentos, socket, bind, listen, bucle select |
Trampas
selectmachaca los conjuntos:rd = wr = allen cada vuelta.- El aviso de
leftva antes de cerrar: luego ya no sabes su id. %dcon el id del cliente, no con el fd.write(2, "Fatal error\n", 12): cuenta el\n. Son 12 y 26.- Leaks: cada
malloc/realloccon sufree, cadaacceptcon suclose.
Otras soluciones
| Versión | Buffer por cliente | Reparto | Ojo |
|---|---|---|---|
| Optim | realloc justo + strstr | solo a los de wr | una copia por recv para el resto sin \n |
| Compañero | array fijo de 400000 por cliente, carácter a carácter, con tope | solo a los de wr | sin malloc: nada que liberar · solo fds por debajo de 1024 · una línea de más de 400 KB se corta |
| stc71 ↗ | array fijo de 370000 por cliente, carácter a carácter | solo a los de wr | usa vsprintf y stdarg: no están en la lista de permitidas · sin malloc, 2048 clientes × 370 KB estáticos |
mohaben-1 no tiene repo de rank 06 (solo hasta el 05). stc71 no se copia aquí (sin licencia): el enlace ↗ lleva a su código en GitHub, y tiene también un mini_serv_comentado.c línea a línea.