void http_init(void) { http.tcp_session = tcp_open(sys_setup.http_port); http.state = HTTP_IDLE; //http.timeout = 0; sse_sock = tcp_open(sys_setup.http_port); if(sse_sock != 0xff) tcp_socket[sse_sock].tcp_state = TCP_RESERVED; }
//open a port (serial or tcp) GOOD_OR_BAD COM_open(struct connection_in *connection) { struct port_in * pin ; struct connection_in * head_in ; if (connection == NO_CONNECTION) { LEVEL_DEBUG("Attempt to open a NULL serial device"); return gbBAD; } pin = connection->pown ; head_in = pin->first ; // head of multigroup bus switch ( pin->state ) { case cs_deflowered: // Attempt to reopen a good connection? COM_close(head_in) ; break ; case cs_virgin: break ; } switch ( pin->type ) { case ct_telnet: if ( pin->dev.telnet.telnet_negotiated == completed_negotiation ) { pin->dev.telnet.telnet_negotiated = needs_negotiation ; } pin->dev.telnet.telnet_supported = 0 ; return tcp_open( head_in ) ; case ct_tcp: return tcp_open( head_in ) ; case ct_netlink: #if OW_W1 return w1_bind( connection ) ; #endif /* OW_W1 */ case ct_i2c: case ct_usb: LEVEL_DEBUG("Unimplemented"); return gbBAD ; case ct_serial: return serial_open( head_in ) ; case ct_unknown: case ct_none: default: LEVEL_DEBUG("Unknown type."); return gbBAD ; } }
int http_open(char * arg) { char * host; int port; char * request; int tcp_sock; char http_request[1024]; char c; /* Check for URL syntax */ if(strncmp(arg, "http://", strlen("http://"))) return(0); /* Parse URL */ port = 80; host = arg + strlen("http://"); if((request = strchr(host, '/')) == NULL) return(0); *request++ = 0; if(strchr(host, ':') != NULL) /* port is specified */ { port = atoi(strchr(host, ':') + 1); *strchr(host, ':') = 0; } /* Open a TCP socket */ if(!(tcp_sock = tcp_open(host, port))) { perror("http_open"); return(0); } /* Send HTTP GET request */ sprintf(http_request, "GET /%s HTTP/1.0\r\n" "User-Agent: Mozilla/2.0 (Win95; I)\r\n" "Pragma: no-cache\r\n" "Host: %s\r\n" "Accept: */*\r\n" "\r\n", request, host); send(tcp_sock, http_request, strlen(http_request), 0); /* Parse server reply */ do read(tcp_sock, &c, sizeof(char)); while(c != ' '); read(tcp_sock, http_request, 4*sizeof(char)); http_request[4] = 0; if(strcmp(http_request, "200 ")) { fprintf(stderr, "http_open: "); do { read(tcp_sock, &c, sizeof(char)); fprintf(stderr, "%c", c); } while(c != '\r'); fprintf(stderr, "\n"); return(0); } return(tcp_sock); }
// ------------------------------------------------ // Function: smtp_new() // ------------------------------------------------ // Input: Server address // Network interface ID // Output: TRUE if succesful // ------------------------------------------------ // Description: Connects to a SMTP server and // starts a new mail session // ------------------------------------------------ BOOL smtp_new(IPV4 server, BYTE interface) { if(smtp_state != SMTP_IDLE) return FALSE; // ----------------- // connect to server // ----------------- if(!tcp_open(SOCKET_SMTP, tcp_get_port(), server, 25, interface)) return FALSE; if(!smtp_ok()) { smtp_quit(); return FALSE; } // ----------------- // send HELO command // ----------------- if(!tcp_send_text(SOCKET_SMTP, "HELO hermes\r\n")) { smtp_quit(); return FALSE; } if(!smtp_ok()) return FALSE; smtp_state = SMTP_FROM; return TRUE; }
tcp_handle *open_device_tcp(void) { static tcp_handle *tcp = 0; if(tcp) return tcp; tcp = tcp_open(host); return tcp; }
/* Send push. */ as_bool as_push_send (ASPush *push) { if (push->state != PUSH_NEW) { assert (0); return FALSE; } if (AS->netinfo->port == 0) return FALSE; assert (push->sconn == NULL); /* TODO: Check if this is one of our supernodes and send push directly * instead of opening new connection. */ if (!(push->sconn = tcp_open (push->source->shost, push->source->sport, FALSE))) { AS_ERR_3 ("Unable to open tcp connection for push %d to %s:%d", push->id, net_ip_str (push->source->shost), push->source->sport); return FALSE; } push->state = PUSH_CONNECTING; AS_HEAVY_DBG_3 ("Push %d connecting to %s:%d", push->id, net_ip_str (push->sconn->host), push->sconn->port); input_add (push->sconn->fd, (void *)push, INPUT_WRITE, (InputCallback)push_connected, AS_PUSH_CONNECT_TIMEOUT); return TRUE; }
QBBSd() { int udp_sock, tcp_sock; fd_set fdmask; if((udp_sock = udp_open(1)) < 0) logsyserr("<getconnect> could not get UDP socket"); if((tcp_sock = tcp_open(1)) < 0) logsyserr("<getconnect> could not get TCP socket"); loginfo("<quakebbs> QuakeBBS v%s Now Running!", QBBS_VERSION); for(;;) { loginfo("<quakebbs> Waiting for TCP connect on %d or UDP connect on %d", config.serv[0].port[0], config.serv[0].port[1]); FD_ZERO(&fdmask); FD_SET(udp_sock, &fdmask); FD_SET(tcp_sock, &fdmask); if(select(1+((tcp_sock > udp_sock) ? tcp_sock : udp_sock), &fdmask, (fd_set *)0, (fd_set *)0, (struct timeval *)0) < 0) logerr("<getconnect> select failed"); if(FD_ISSET(udp_sock, &fdmask)) udpconnect(udp_sock); if(FD_ISSET(tcp_sock, &fdmask)) tcpconnect(tcp_sock); } }
/* Open a device with standard options. * Use value (-1) for "with_hw_handshake" if its specification is required from the user */ int tcp_opendevice(const char *file, int with_async, struct gn_statemachine *state) { int fd; int retcode; /* Open device */ fd = tcp_open(file); if (fd < 0) return fd; /* handle config file connect_script: */ if (device_script(fd, "connect_script", state) == -1) { fprintf(stderr, _("Gnokii tcp_opendevice: connect_script\n")); tcp_close(fd, state); return -1; } /* Allow process/thread to receive SIGIO */ #if !(__unices__) retcode = fcntl(fd, F_SETOWN, getpid()); if (retcode == -1){ perror(_("Gnokii tcp_opendevice: fcntl(F_SETOWN)")); tcp_close(fd, state); return -1; } #endif /* Make filedescriptor asynchronous. */ /* We need to supply FNONBLOCK (or O_NONBLOCK) again as it would get reset * by F_SETFL as a side-effect! */ #ifdef FNONBLOCK retcode = fcntl(fd, F_SETFL, (with_async ? FASYNC : 0) | FNONBLOCK); #else # ifdef FASYNC retcode = fcntl(fd, F_SETFL, (with_async ? FASYNC : 0) | O_NONBLOCK); # else retcode = fcntl(fd, F_SETFL, O_NONBLOCK); if (retcode != -1) retcode = ioctl(fd, FIOASYNC, &with_async); # endif #endif if (retcode == -1) { perror(_("Gnokii tcp_opendevice: fcntl(F_SETFL)")); tcp_close(fd, state); return -1; } return fd; }
void opn_download_start(OpnDownload *download) { assert(download); if (!(download->con = tcp_open(download->url->client.ip, download->url->client.port, FALSE))) return; input_add(download->con->fd, download, INPUT_READ, (InputCallback) on_download_connect, 30 * SECONDS); }
// Create a file struct for given path static uufile_t * httpfs_namei(uufs_t *fs, const char *filename) { int ip0, ip1, ip2, ip3, port; (void) fs; if( 5 != sscanf( filename, "%d.%d.%d.%d:%d", &ip0, &ip1, &ip2, &ip3, &port ) ) { return 0; } sockaddr addr; addr.port = port; addr.addr.len = 4; addr.addr.type = ADDR_TYPE_IP; NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(ip0, ip2, ip2, ip3); struct uusocket *us = calloc(1, sizeof(struct uusocket)); if(us == 0) return 0; us->addr = addr; if( tcp_open(&(us->prot_data)) ) { SHOW_ERROR0(0, "can't prepare endpoint"); fail: free(us); return 0; } if( tcp_connect( us->prot_data, &us->addr) ) { SHOW_ERROR(0, "can't connect to %s", filename); goto fail; } uufile_t *ret = create_uufile(); ret->ops = &httpfs_fops; ret->pos = 0; ret->fs = &http_fs; ret->impl = us; ret->flags = UU_FILE_FLAG_NET|UU_FILE_FLAG_TCP|UU_FILE_FLAG_OPEN; // TODO wrong! open in open! return ret; }
int bot_connect(EV_P_ irc_bot *b) { if (strlen(b->irc_host) == 0 || strlen(b->irc_port) == 0) return -1; // connect if ((b->sockfd = tcp_open(b->irc_host, b->irc_port)) == -1) return -1; // make socket non-blocking fcntl(b->sockfd, F_SETFD, (fcntl(b->sockfd, F_GETFD) | O_NONBLOCK)); ev_io_init(b->irc_io, ev_irc_cb, b->sockfd, EV_READ); ev_io_start(loop, b->irc_io); return 0; }
FModTCP * FModTCP:: Create(uint32_t portnum, const char * server, unsigned int usec_cycle, unsigned int max_errcount) { int fd(tcp_open(8010, server)); if(fd < 0) return 0; struct fmod_s * fs(fmod_new(fd)); int result(fmod_tcp_wiodir(fs, 0, 0, 0)); if(FMOD_OK != result){ fmod_delete(fs); tcp_close(fd); return 0; } return new FModTCP(fs, usec_cycle, max_errcount); }
void set_nist_time(){ int dst, health; struct tm t; unsigned long longsec; char response[100]; int bytes_read,total_bytes; tcp_Socket sock; longword nist_server; printf("Trying to set time from NIST server...\n"); //get the time if (!(nist_server = resolve(NIST_SERVER))) { printf(" ! Could not resolve time host\n"); exit( 3 ); } if( !tcp_open(&sock,0,nist_server,NIST_PORT,NULL)){ printf(" ! Unable to connect to time server\n"); exit( 3 ); } while (!sock_established(&sock) && sock_bytesready(&sock)==-1){ tcp_tick(NULL); } sock_mode(&sock, TCP_MODE_ASCII); total_bytes=0; do{ bytes_read=sock_fastread(&sock,response+total_bytes,sizeof(response)-1-total_bytes); total_bytes+=bytes_read; } while(tcp_tick(&sock) && (total_bytes < sizeof(response)-2)); //parse it t.tm_year = 100 + 10*(response[7]-'0') + (response[8]-'0'); t.tm_mon = 10*(response[10]-'0') + (response[11]-'0'); t.tm_mday = 10*(response[13]-'0') + (response[14]-'0'); t.tm_hour = 10*(response[16]-'0') + (response[17]-'0'); t.tm_min = 10*(response[19]-'0') + (response[20]-'0'); t.tm_sec = 10*(response[22]-'0') + (response[23]-'0'); dst = 10*(response[25]-'0') + (response[26]-'0'); health = response[28]-'0'; longsec = mktime(&t); longsec += 3600ul * NIST_TIMEZONE; // adjust for timezone if (dst != 0) longsec += 3600ul; // DST is in effect if (health < 2) write_rtc(longsec); printf(" Time set to : "); print_time(read_rtc()); }
static int windows_open(const char *name, char *suffix, struct stream **streamp, uint8_t dscp) { int error, port; FILE *file; char *suffix_new, *path; /* If the path does not contain a ':', assume it is relative to * OVS_RUNDIR. */ if (!strchr(suffix, ':')) { path = xasprintf("%s/%s", ovs_rundir(), suffix); } else { path = xstrdup(suffix); } file = fopen(path, "r"); if (!file) { error = errno; VLOG_DBG("%s: could not open %s (%s)", name, suffix, ovs_strerror(error)); return error; } error = fscanf(file, "%d", &port); if (error != 1) { VLOG_ERR("failed to read port from %s", suffix); fclose(file); return EINVAL; } fclose(file); suffix_new = xasprintf("127.0.0.1:%d", port); error = tcp_open(name, suffix_new, streamp, dscp); free(suffix_new); free(path); return error; }
static as_bool timer_cb (int test_id) { static int count = 1; TCPC *c; printf ("[%d] Timer callback %d\n", test_id, count); if (count < 5) { count++; return TRUE; /* call us again */ } /* reset count for next test */ count = 1; printf ("[%d] Timer test completed successfully.\n", test_id); /* do a socket event test */ printf ("[%d] Step 2: Trying TCP connection to 127.0.0.1:1111 with 10 " "second timeout...\n", test_id); if (!(c = tcp_open (net_ip ("127.0.0.1"), 1111, FALSE))) { printf ("[%d] tcp_open() failed.\n", test_id); return FALSE; } c->udata = (void *)test_id; if (input_add (c->fd, (void *)c, INPUT_WRITE, (InputCallback)input_cb, 10 * SECONDS) == 0) { printf ("[%d] input_add() failed.\n", test_id); tcp_close (c); return FALSE; } return FALSE; /* discard this timer */ }
int main(int argc, char *argv[] ) { int n, i, c, err, max_port = 0; char *portname, *s; struct servent *servent; struct info *in; prog = argv[0]; Opterr = 1; while( (n = Getopt(argc, argv, "dut")) != EOF ){ switch(n){ default: usage(); break; case 'u': use_udp = !use_udp; break; case 't': use_tcp = !use_tcp; break; case 'd': debug = 1; break; } } i = argc - Optind; if( i > 1 ) usage(); if( i == 1 ){ portname = argv[Optind]; n = atoi( portname ); if( n <= 0 ){ servent = getservbyname( portname, "udp" ); if( servent ){ n = ntohs( servent->s_port ); } } if( n <= 0 ){ FPRINTF( STDERR, "udp_open: bad port number '%s'\n",portname ); usage(); } port_num = n; } if( !use_tcp && !use_udp ) use_udp = 1; if( debug ){ FPRINTF(STDERR,"monitor: udp %d, tcp %d, port %d\n", use_udp, use_tcp, port_num ); } max_port = 0; FD_ZERO( &readfds ); if( use_udp && (udp_fd = udp_open( port_num )) >= 0){ if( debug ) FPRINTF(STDERR,"monitor: udp port %d\n", udp_fd ); FD_SET(udp_fd, &readfds); if( udp_fd >= max_port ) max_port = udp_fd+1; } if( use_tcp && (tcp_fd = tcp_open( port_num )) >= 0){ if( debug ) FPRINTF(STDERR,"monitor: tcp port %d\n", tcp_fd ); FD_SET(tcp_fd, &readfds); if( tcp_fd >= max_port ) max_port = tcp_fd+1; } if( debug ){ FPRINTF(STDERR,"monitor: max_port %d\n", max_port ); for( i = 0; i < max_port; ++i ){ if( FD_ISSET(i, &readfds) ){ FPRINTF(STDERR,"monitor: initial on %d\n", i ); } } } while(1){ FD_ZERO( &testfds ); for( i = 0; i < max_port; ++i ){ if( FD_ISSET(i, &readfds) ){ if( debug ) FPRINTF(STDERR,"monitor: waiting on %d\n", i ); FD_SET(i, &testfds); } } if( debug ) FPRINTF(STDERR,"monitor: starting wait, max %d\n", i ); n = select( i, FD_SET_FIX((fd_set *))&testfds, FD_SET_FIX((fd_set *))0, FD_SET_FIX((fd_set *))0, (struct timeval *)0 ); err = errno; if( debug ) FPRINTF(STDERR,"monitor: select returned %d\n", n ); if( n < 0 ){ FPRINTF( STDERR, "select error - %s\n", Errormsg(errno) ); if( err != EINTR ) break; } if( n > 0 ) for( i = 0; i < max_port; ++i ){ if( FD_ISSET(i, &testfds) ){ if( debug ) FPRINTF(STDERR,"monitor: input on %d\n", i ); if( i == tcp_fd ){ #if defined(HAVE_SOCKLEN_T) socklen_t len; #else int len; #endif struct sockaddr_in sinaddr; len = sizeof( sinaddr ); i = accept( tcp_fd, (struct sockaddr *)&sinaddr, &len ); if( i < 0 ){ FPRINTF( STDERR, "accept error - %s\n", Errormsg(errno) ); continue; } FPRINTF( STDOUT, "connection from %s\n", inet_ntoa( sinaddr.sin_addr ) ); if( i >= max_port ) max_port = i+1; FD_SET(i, &readfds); } else { c = read( i, buffer, sizeof(buffer)-1 ); if( c == 0 ){ /* closed connection */ FPRINTF(STDOUT, "closed connection %d\n", i ); close( i ); FD_CLR(i, &readfds ); Clear_buffer(i); } else if( c > 0 ){ buffer[c] = 0; if(debug)FPRINTF( STDOUT, "recv port %d: %s\n", i, buffer ); Add_buffer(i); in = Save_outbuf_len( i, buffer, c ); while( (s = safestrchr(in->buffer,'\n')) ){ *s++ = 0; Decode(in->buffer); memmove(in->buffer,s, safestrlen(s)+1 ); in->len = safestrlen(in->buffer); } } else { FPRINTF( STDERR, "read error - %s\n", Errormsg(errno) ); close( i ); FD_CLR(i, &readfds ); } } } } } return(0); }
void mupip_restore(void) { static readonly char label[] = GDS_LABEL; char db_name[MAX_FN_LEN + 1], *inbuf, *p; inc_list_struct *ptr; inc_header *inhead; sgmnt_data *old_data; short iosb[4]; unsigned short n_len; int4 status, vbn, rsize, temp, save_errno; uint4 rest_blks, totblks; trans_num curr_tn; uint4 ii; block_id blk_num; bool extend; uint4 cli_status; BFILE *in; int i, db_fd; uint4 old_blk_size, old_tot_blks, bplmap; short old_start_vbn; off_t new_eof; char buff[DISK_BLOCK_SIZE]; char msg_buffer[1024], *newmap, *newmap_bptr; mstr msg_string; char addr[SA_MAXLEN+1]; unsigned char tcp[5]; backup_type type; unsigned short port; int4 timeout, cut, match; char debug_info[256]; void (*common_read)(); char *errptr; pid_t waitpid_res; error_def(ERR_MUPRESTERR); error_def(ERR_MUPCLIERR); error_def(ERR_IOEOF); extend = TRUE; if (CLI_NEGATED == (cli_status = cli_present("EXTEND"))) extend = FALSE; mu_outofband_setup(); mu_gv_cur_reg_init(); n_len = sizeof(db_name); if (cli_get_str("DATABASE", db_name, &n_len) == FALSE) mupip_exit(ERR_MUPCLIERR); strcpy((char *)gv_cur_region->dyn.addr->fname, db_name); gv_cur_region->dyn.addr->fname_len = n_len; if (!mu_rndwn_file(gv_cur_region, TRUE)) { util_out_print("Error securing stand alone access to output file !AD. Aborting restore.", TRUE, n_len, db_name); mupip_exit(ERR_MUPRESTERR); } OPENFILE(db_name, O_RDWR, db_fd); if (-1 == db_fd) { save_errno = errno; util_out_print("Error accessing output file !AD. Aborting restore.", TRUE, n_len, db_name); errptr = (char *)STRERROR(save_errno); util_out_print("open : !AZ", TRUE, errptr); mupip_exit(save_errno); } murgetlst(); inbuf = (char*)malloc(INC_BACKUP_CHUNK_SIZE); old_data = (sgmnt_data*)malloc(sizeof(sgmnt_data)); LSEEKREAD(db_fd, 0, old_data, sizeof(sgmnt_data), save_errno); if (0 != save_errno) { util_out_print("Error accessing output file !AD. Aborting restore.", TRUE, n_len, db_name); if (-1 != save_errno) { errptr = (char *)STRERROR(save_errno); util_out_print("read : !AZ", TRUE, errptr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(save_errno); } else { db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_IOEOF); } } if (memcmp(&old_data->label[0], &label[0], GDS_LABEL_SZ)) { util_out_print("Output file !AD has an unrecognizable format", TRUE, n_len, db_name); free(old_data); free(inbuf); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } curr_tn = old_data->trans_hist.curr_tn; old_blk_size = old_data->blk_size; old_tot_blks = old_data->trans_hist.total_blks; old_start_vbn = old_data->start_vbn; bplmap = old_data->bplmap; free(old_data); msg_string.addr = msg_buffer; msg_string.len = sizeof(msg_buffer); inhead = (inc_header *)malloc(sizeof(inc_header) + 8); inhead = (inc_header *)((((int4)inhead) + 7) & -8); rest_blks = 0; for (ptr = in_files.next; ptr; ptr = ptr->next) { /* --- determine source type --- */ type = backup_to_file; if (0 == ptr->input_file.len) continue; else if ('|' == *(ptr->input_file.addr + ptr->input_file.len - 1)) { type = backup_to_exec; ptr->input_file.len--; *(ptr->input_file.addr + ptr->input_file.len) = '\0'; } else if (ptr->input_file.len > 5) { lower_to_upper(tcp, (uchar_ptr_t)ptr->input_file.addr, 5); if (0 == memcmp(tcp, "TCP:/", 5)) { type = backup_to_tcp; cut = 5; while ('/' == *(ptr->input_file.addr + cut)) cut++; ptr->input_file.len -= cut; p = ptr->input_file.addr; while (p < ptr->input_file.addr + ptr->input_file.len) { *p = *(p + cut); p++; } *p = '\0'; } } /* --- open the input stream --- */ restore_read_errno = 0; switch(type) { case backup_to_file: common_read = iob_read; if ((in = iob_open_rd(ptr->input_file.addr, DISK_BLOCK_SIZE, BLOCKING_FACTOR)) == NULL) { save_errno = errno; util_out_print("Error accessing input file !AD. Aborting restore.", TRUE, ptr->input_file.len, ptr->input_file.addr); errptr = (char *)STRERROR(save_errno); util_out_print("open : !AZ", TRUE, errptr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(save_errno); } ESTABLISH(iob_io_error); break; case backup_to_exec: pipe_child = 0; common_read = exec_read; in = (BFILE *)malloc(sizeof(BFILE)); if (0 > (in->fd = gtm_pipe(ptr->input_file.addr, input_from_comm))) { util_out_print("Error creating input pipe from !AD.", TRUE, ptr->input_file.len, ptr->input_file.addr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } #ifdef DEBUG_ONLINE PRINTF("file descriptor for the openned pipe is %d.\n", in->fd); PRINTF("the command passed to gtm_pipe is %s.\n", ptr->input_file.addr); #endif break; case backup_to_tcp: common_read = tcp_read; /* parse the input */ switch (match = SSCANF(ptr->input_file.addr, "%[^:]:%hu", addr, &port)) { case 1 : port = DEFAULT_BKRS_PORT; case 2 : break; default : util_out_print("Error : A hostname has to be specified.", TRUE); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } if ((0 == cli_get_int("NETTIMEOUT", &timeout)) || (0 > timeout)) timeout = DEFAULT_BKRS_TIMEOUT; in = (BFILE *)malloc(sizeof(BFILE)); iotcp_fillroutine(); if (0 > (in->fd = tcp_open(addr, port, timeout, TRUE))) { util_out_print("Error establishing TCP connection to !AD.", TRUE, ptr->input_file.len, ptr->input_file.addr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } break; default: util_out_print("Aborting restore!/", TRUE); util_out_print("Unrecognized input format !AD", TRUE, ptr->input_file.len, ptr->input_file.addr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } COMMON_READ(in, inhead, sizeof(inc_header)); if (memcmp(&inhead->label[0], INC_HEADER_LABEL, INC_HDR_LABEL_SZ)) { util_out_print("Input file !AD has an unrecognizable format", TRUE, ptr->input_file.len, ptr->input_file.addr); free(inbuf); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } if (curr_tn != inhead->start_tn) { util_out_print("Transaction in input file !AD does not align with database TN.!/DB: !XL!_Input file: !XL", TRUE, ptr->input_file.len, ptr->input_file.addr, curr_tn, inhead->start_tn); free(inbuf); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } if (old_blk_size != inhead->blk_size) { util_out_print("Incompatable block size. Output file !AD has block size !XL,", TRUE, n_len, db_name); util_out_print("while input file !AD is from a database with block size !XL,", TRUE, ptr->input_file.len, ptr->input_file.addr, inhead->blk_size); free(inbuf); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } if (old_tot_blks != inhead->db_total_blks) { if (old_tot_blks > inhead->db_total_blks || !extend) { totblks = old_tot_blks - DIVIDE_ROUND_UP(old_tot_blks, DISK_BLOCK_SIZE); util_out_print("Incompatable database sizes. Output file !AD has!/ !UL (!XL hex) total blocks,", TRUE, n_len, db_name, totblks, totblks); totblks = inhead->db_total_blks - DIVIDE_ROUND_UP(inhead->db_total_blks, DISK_BLOCK_SIZE); util_out_print("while input file !AD is from a database with!/ !UL (!XL hex) total blocks", TRUE, ptr->input_file.len, ptr->input_file.addr, totblks, totblks); free(inbuf); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } else { /* this part of the code is similar to gdsfilext except that you don't need to do * most of the work that gdsfilext does. However, for situations where the database * extended since the last backup (the beginning of this incremental backup), and * there are new bitmaps that are never touched later on by GT.M, these bitmaps * will have tn == 0, which prevents the backup process to pick up these blocks, * so, we need to initialize these bitmaps here */ new_eof = ((off_t)(old_start_vbn - 1) * DISK_BLOCK_SIZE) + ((off_t)inhead->db_total_blks * old_blk_size); memset(buff, 0, DISK_BLOCK_SIZE); LSEEKWRITE(db_fd, new_eof, buff, DISK_BLOCK_SIZE, status); if (0 != status) { util_out_print("Aborting restore!/", TRUE); util_out_print("lseek or write error : Unable to extend output file !AD!/", TRUE, n_len, db_name); util_out_print(" from !UL (!XL hex) total blocks to !UL (!XL hex) total blocks.!/", TRUE, old_tot_blks, old_tot_blks, inhead->db_total_blks, inhead->db_total_blks); util_out_print(" Current input file is !AD with !UL (!XL hex) total blocks!/", TRUE, ptr->input_file.len, ptr->input_file.addr, inhead->db_total_blks, inhead->db_total_blks); gtm_putmsg(VARLSTCNT(1) status); free(inbuf); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } /* --- initialize all new bitmaps, just in case they are not touched later --- */ if (DIVIDE_ROUND_DOWN(inhead->db_total_blks, bplmap) > DIVIDE_ROUND_DOWN(old_tot_blks, bplmap)) { /* -- similar logic exist in bml_newmap.c, which need to pick up any new updates here -- */ newmap = (char *)malloc(old_blk_size); ((blk_hdr *)newmap)->bsiz = BM_SIZE(bplmap); ((blk_hdr *)newmap)->levl = LCL_MAP_LEVL; ((blk_hdr *)newmap)->tn = curr_tn; newmap_bptr = newmap + sizeof(blk_hdr); *newmap_bptr++ = THREE_BLKS_FREE; memset(newmap_bptr, FOUR_BLKS_FREE, BM_SIZE(bplmap) - sizeof(blk_hdr) - 1); for (ii = ROUND_UP(old_tot_blks, bplmap); ii <= inhead->db_total_blks; ii += bplmap) { new_eof = (off_t)(old_start_vbn - 1) * DISK_BLOCK_SIZE + (off_t)ii * old_blk_size; LSEEKWRITE(db_fd, new_eof, newmap, old_blk_size, status); if (0 != status) { util_out_print("Aborting restore!/", TRUE); util_out_print("Bitmap 0x!XL initialization error!", TRUE, ii); gtm_putmsg(VARLSTCNT(1) status); free(inbuf); free(newmap); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } } free(newmap); } old_tot_blks = inhead->db_total_blks; } } COMMON_READ(in, &rsize, sizeof(int4)); for ( ; ;) { /* rsize is the size of the record, including the size, but, since the size has already been read in, this will read in the current record and the size for the next record */ /* ensure we have a reasonable record size, at least */ if (rsize - sizeof(int4) - sizeof(block_id) > old_blk_size) { util_out_print("Invalid information in restore file !AD. Aborting restore.", TRUE, ptr->input_file.len, ptr->input_file.addr); iob_close(in); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(ERR_MUPRESTERR); } COMMON_READ(in, inbuf, rsize); if (!memcmp(inbuf, &end_msg[0], sizeof end_msg - 1)) break; rest_blks++; blk_num = *(block_id*)inbuf; vbn = old_start_vbn - 1 + (old_blk_size / DISK_BLOCK_SIZE * blk_num); LSEEKWRITE(db_fd, (off_t)vbn * DISK_BLOCK_SIZE, inbuf + sizeof(block_id), rsize - sizeof(block_id) - sizeof(int4), save_errno); if (0 != save_errno) { util_out_print("Error accessing output file !AD. Aborting restore.", TRUE, n_len, db_name); errptr = (char *)STRERROR(save_errno); util_out_print("write : !AZ", TRUE, errptr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(save_errno); } GET_LONG(temp, (inbuf + rsize - sizeof(int4))); rsize = temp; } GET_LONG(temp, (inbuf + rsize - sizeof(int4))); rsize = temp; vbn = 0; for (i = 0; ; i++) /* Restore file header */ { COMMON_READ(in, inbuf, rsize); if (!memcmp(inbuf, &hdr_msg[0], sizeof hdr_msg - 1)) break; LSEEKWRITE(db_fd, vbn, inbuf, rsize - sizeof(int4), save_errno); if (0 != save_errno) { util_out_print("Error accessing output file !AD. Aborting restore.", TRUE, n_len, db_name); errptr = (char *)STRERROR(save_errno); util_out_print("write : !AZ", TRUE, errptr); db_ipcs_reset(gv_cur_region, TRUE); mu_gv_cur_reg_free(); mupip_exit(save_errno); } vbn += rsize - sizeof(int4); GET_LONG(temp, (inbuf + rsize - sizeof(int4))); rsize = temp; } curr_tn = inhead->end_tn; switch (type) { case backup_to_file: REVERT; iob_close(in); break; case backup_to_exec: close(in->fd); if ((pipe_child > 0) && (FALSE != is_proc_alive(pipe_child, 0))) WAITPID(pipe_child, (int *)&status, 0, waitpid_res); break; case backup_to_tcp: break; } } util_out_print("!/RESTORE COMPLETED", TRUE); util_out_print("!UL blocks restored", TRUE, rest_blks); free(inbuf); db_ipcs_reset(gv_cur_region, FALSE); mu_gv_cur_reg_free(); mupip_exit(SS_NORMAL); }
int xsendmail(struct Url *url, char helo, char logfile) { longword host; long length; //!!glennmcc: Feb 05, 2008 -- increased from 128 to 512 char str[512/*128*/],pom[512/*128*/]; //!!glennmcc Apr 30, 2004 -- for AuthSMTP char AuthSMTPusername[128]="",AuthSMTPpassword[128]=""; //!!glennmcc: end char buffer[BUFLEN]; struct ffblk ff; char filename[80]; int rv=0; //default return value == error int f,nomoremail; int done,lenread,i,j,lastcarka,carka,field,success,u,z; int status,err=0; char *ptr; int log; //!!glennmcc & Ray: Dec 14, 2006 int bcc=0; //!!glennmcc & Ray: end if(!tcpip) return 0; nomoremail=findfirst(&url->file[1],&ff,0); if(nomoremail) return 1; if(logfile) log= a_open( "SMTP.LOG" , O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE ); else log=-1; free_socket(); //reset requests on IDENT port: reset_detected=0; tcp_listen(sock[1-socknum], 113, 0, 0, (dataHandler_t) resetport , 0); sprintf(str,msg_askdns,url->host); outs(str); GlobalLogoStyle=0; //SDL set resolve animation host = resolve_fn(url->host, (sockfunct_t) TcpIdleFunc); //SDL // host = resolve(url->host); if(!host) { DNSerr(url->host); return 0; } sprintf(str,msg_con,url->host,url->port); outs(str); GlobalLogoStyle=2; //SDL set connect animation if (!tcp_open( socket, locport(), host, url->port, NULL )) { sprintf(str,msg_errcon,url->host); outs(str); return 0; } sock_wait_established( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status); //SDL GlobalLogoStyle=1; //SDL set data animation sock_mode( socket, TCP_MODE_ASCII ); outs(MSG_SMTP); //wait for daemon to appear: do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) goto quit; } while(buffer[3]=='-'); //continued message! if(log!=-1 && reset_detected) { strcpy(str,MSG_IDENT); write(log,str,strlen(str)); write(log,"\r\n",2); } if(helo) // if(helo!=0) { //HELO protocol char *mydomain=strchr(url->user,'@'); if(mydomain) mydomain++; // xx@->yyy else //!!glennmcc: Feb 22, 2006 -- use host domain instead of user { mydomain=strchr(url->host,'.'); mydomain++; // xx@->yyy } // mydomain=url->user; //!!glennmcc: end //!!glennmcc: begin Nov 09, 2003 --- EHLO == Authenticated SMTP //finally finished it on Apr 30, 2004 ;-) if(helo==2) { //!!glennmcc: Feb 14, 2006 -- use 'authuser' for AuthSMTP mydomain=strrchr(url->authuser,'@'); if(mydomain) mydomain++; // xx@->yyy else //!!glennmcc: Feb 22, 2006 -- use host domain instead of authuser { mydomain=strchr(url->host,'.'); mydomain++; // xx@->yyy } // mydomain=url->authuser; //!!glennmcc: end sprintf( str, "EHLO %s", mydomain); outs(str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) goto quit; } while(buffer[3]=='-'); //continued message! sprintf( str, "AUTH LOGIN"); outs(str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '3' ) goto quit; } while(buffer[3]=='-'); //continued message! //!!glennmcc: Sept 17, 2004 // changed so that "email" will always get used for "mail from" // base64code((unsigned char *)url->user,AuthSMTPusername); base64code((unsigned char *)url->authuser,AuthSMTPusername); //!!glennmcc: end sprintf( str, AuthSMTPusername); outs(str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '3' ) goto quit; } while(buffer[3]=='-'); //continued message! //!!glennmcc: Feb 17, 2006 -- switch to new variable 'authpassword' base64code((unsigned char *)url->authpassword,AuthSMTPpassword); // base64code((unsigned char *)url->password,AuthSMTPpassword); sprintf( str, AuthSMTPpassword); outs(str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) goto quit; } while(buffer[3]=='-'); //continued message! } else //begin else HELO { //!!glennmcc: end sprintf( str, "HELO %s", mydomain); outs(str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) goto quit; } while(buffer[3]=='-'); //continued message! }//!!glennmcc: end of else HELO } //do for all messages while (!nomoremail) { //process msg body if(err) { outs("RSET"); if(log!=-1) { write(log,"RSET\r\n",6); } sock_puts(socket,(unsigned char *)"RSET"); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) goto quit; //cannot reset ?? } while(buffer[3]=='-'); //continued message! err=0; } strcpy(filename,&url->file[1]); ptr=strrchr(filename,'\\'); if(ptr) ptr++; //point after "\" else ptr=filename; //current dir ? (not likelky case) strcpy(ptr,ff.ff_name); //open file f=a_fast_open(filename, O_TEXT|O_RDONLY,0); if(f<0) goto cont; //go to next message! //start SMTP sprintf( str, "MAIL FROM: <%s>", url->user); outs(str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) goto quit; //I am not accepted ?! } while(buffer[3]=='-'); //continued message! //process msg header done=lenread=j=lastcarka=carka=field=success=u=z=0; i=1; //force reading! do { if(i>=lenread) { lenread=a_read(f,buffer,BUFLEN); if(lenread<=0) done=1; i=0; } str[j]=buffer[i++]; if(str[j]=='\"')u=1-u; else if(str[j]=='(')z=1; else if(str[j]==')')z=0; else if(str[j]==',' && !u && !z)carka=1; if(j>=127 || str[j]=='\n' || carka || done) { str[j]='\0'; if(!str[0] && !lastcarka) //empty line -> end of message header { done=1; field=0; } else if(!strncmpi("TO:",str,3) || !strncmpi("CC:",str,3)) { ptr=&str[3]; field=1; } else if(!strncmpi("BCC:",str,4)) { //!!glennmcc & Ray: Dec 14, 2006 bcc=1; //!!glennmcc & Ray: end ptr=&str[4]; field=1; } else if(field && (lastcarka || str[0]==' ')) ptr=str; else field=0; if(field) { struct ib_editor expandlist; int rcpt; if(ptr[0]==' ' && ptr[1]=='@') //expand mailing list { makestr(expandlist.filename,&ptr[2],79); if(ie_openf(&expandlist,CONTEXT_TMP)==1) field=-1; else { field=0; expandlist.filename[0]='\0'; } } else expandlist.filename[0]='\0'; if(field!=0) rcpt=1; else rcpt=0; while(rcpt) { if(field==1) //address in ptr rcpt=0; else { ptr=ie_getline(&expandlist,expandlist.y++); if(expandlist.y>=expandlist.lines) { rcpt=0; field=0; } } cutaddress(ptr); if(*ptr) { //add SMTP recipient sprintf( pom, "RCPT TO: <%s>", ptr); outs(pom); if(log!=-1) { write(log,pom,strlen(pom)); write(log,"\r\n",2); } sock_puts(socket,(unsigned char *)pom); sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)pom, sizeof( pom )); outs(pom); if(log!=-1) { write(log,pom,strlen(pom)); write(log,"\r\n",2); } if(*pom == '2') success++; } }//loop if(expandlist.filename[0]) { ie_killcontext(CONTEXT_TMP); //clear temporary file // ie_closef(&expandlist); } }//end temp variables lastcarka=carka; carka=0; j=0; } else j++; } while(!done); if(!success) //cannot send to any recipient ? { err=1; goto cont; } //process msg body outs("DATA"); if(log!=-1) { write(log,"DATA\r\n",6); } sock_puts(socket,(unsigned char *)"DATA"); sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '3') { err=1; goto cont; //failed ? try next message! } a_lseek(f,0L,SEEK_SET); //reset file j=lenread=done=0; i=1; length=0; { long fll=a_filelength(f); do { if(i>=lenread) { sprintf(pom,MSG_SEND,length,fll); outs(pom); /* //!!glennmcc:Oct 23, 2008 -- 'reversed the logic' // to keep from overflowing at 21megs if(fll>100) percentbar((int)(length/(fll/100))); */ percentbar((int)(100*length/fll)); lenread=a_read(f,buffer,BUFLEN); length+=lenread; if(lenread<=0) done=1; i=0; // printf("\nlenread=%d \n",lenread); //!!glennmcc & Ray: Dec 14, 2006 -- bypass Bcc: if(bcc) { char *ptr = strstr(buffer, "Bcc:");//Ray if(ptr) { //Ray's method replaces the address(s) with spaces //it also looks for '\r' (carrage return) as the end of the Bcc line // ptr += 4; // PASS 'Bcc:' // while(*ptr && *ptr != '\r') // *ptr++ = ' '; //printf("After: \n\n%40s", ptr); getch(); // SEE THE RESULT //!!glennmcc: this method works better by 'nulling-out' the Bcc line and //looking for '\n' (new line) as the end of the Bcc line /* method #1 */ /**/ if(*ptr--=='\n')*ptr='\0';//remove previous '\r\n' if it exists do {*ptr='\0'; ptr++;} while( *ptr && *ptr!='\n'); /**/ /* end method #1 */ /* method *2 */ /* if(*ptr--=='\n')*ptr='\0';//remove previous '\r\n' if it exists while(*ptr && *ptr!='\n') *ptr++ ='\0'; *ptr='\0';//also remove this '\n' */ /* end method #2 */ bcc=0; } } //!!glennmcc & Ray: end } str[j]=buffer[i++]; //!!glennmcc: Feb 05, 2008 -- prevent character from being lost at line break //by breaking at a space instead of 127 explicitly //also increased line length limit to the next space past 200 //instead of just 127 explicitly if((j>=200 && str[j]==' ') || str[j]=='\n' || done) // if(j>=127 || str[j]=='\n' || done) //original line //!!glennmcc: end { str[j]='\0'; length++; //ASCI mode !!! //wait until we can write to socket: while(sock_tbleft(socket)<j+1) //SDL // while( socket->datalen > 1024) { sock_tick(socket,&status); xChLogoTICK(1); // animace loga if(GUITICK()) goto quit; } if (str[0]=='.') //SDL always double up sock_putc(socket,'.'); //SDL leading periods sock_puts(socket,(unsigned char *)str); if(log!=-1) { write(log,str,strlen(str)); write(log,"\r\n",2); } sock_tick(socket,&status); j=0; } else j++; } while(!done); } a_close(f); sock_puts(socket,(unsigned char *)"."); if(log!=-1) { write(log,".\r\n",3); } sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); if(log!=-1) { write(log,buffer,strlen(buffer)); write(log,"\r\n",2); } if ( *buffer != '2' ) { err=1; } else { //delete or rename ptr=strrchr(filename,'\\'); if(!ptr) ptr=filename; else ptr++; if(*ptr=='!') unlink(filename); else { strcpy(str,filename); ptr=strrchr(str,'.'); if(ptr) strcpy(&ptr[1],"SNT"); rename(filename,str); } }//endif cont: nomoremail=findnext(&ff); }//loop - next message rv=1; quit: outs("QUIT"); if(log!=-1) { write(log,"QUIT\r\n",6); close(log); } sock_puts(socket,(unsigned char *)"QUIT"); sock_close( socket ); closing[socknum]=1; sock_keepalive[socknum][0]='\0'; sock_err: switch (status) { case 1 : /* foreign host closed */ break; case -1: /* timeout */ sprintf(str,MSG_TCPERR, sockerr(socket)); outs(str); break; } return rv; }
int main(int argc, char* argv[]){ int fd, pasv_fd; char buf[MAX_LENGTH] = {0}; char file[MAX_FILE_SIZE] = {0}; char pasv_ip[MAX_LENGTH]; int pasv_port; parse_args(argc, argv); getip(sv.ip, sv.host); //Ask for account data if it wasnt used in link. if(strcmp(sv.user, "_undefined")==0 || strcmp(sv.pass, "_undefined")==0){ printf("[App] Username: "******"%s", sv.user); printf("[App] Password: "******"%s", sv.pass); printf("\n"); } printf("RCOM FTP Application Initialized\n"); printf("-----------------------------\n"); printf("Hostname : %s\n", sv.host); printf("IP Addr : %s\n", sv.ip); printf("Port : %d\n", sv.port); printf("Username : %s\n", sv.user); printf("Password : %s\n", sv.pass); printf("Path : %s\n", sv.path); printf("File : %s\n", sv.file); printf("-----------------------------\n"); // FTP Application fd = tcp_open(sv.ip, sv.port); // Open Connection tcp_read(fd, buf); // Read 220, Server Welcome Message sprintf(buf, "user %s\n", sv.user); // Write Username Data and get Reply tcp_write(fd, buf); tcp_read(fd, buf); sprintf(buf, "pass %s\n", sv.pass); // Write Password Data and get Reply tcp_write(fd, buf); tcp_read(fd, buf); sprintf(buf, "cwd .%s\n", sv.path); // Change Directory and get Reply tcp_write(fd, buf); tcp_read(fd, buf); sprintf(buf, "pasv\n"); // Enter Passive Mode and get Reply tcp_write(fd, buf); tcp_read(fd, buf); pasv_port = calculate_pasv_data(buf, pasv_ip); printf("[App] Passive Mode Data - Address: %s, Port: %d\n", pasv_ip, pasv_port); pasv_fd = tcp_open(pasv_ip, pasv_port); // Open Secondary Stream and Download File (void) signal(SIGALRM, retr_alarm); retr_fd = fd; sprintf(buf, "retr %s\n", sv.file); strcpy(retr_buf, buf); alarm(RETR_DELAY); tcp_getfile(pasv_fd, file); tcp_close(pasv_fd); // Close Connections tcp_close(fd); return 0; }
static int get_headlines(char *rss_site,char *rss_page){ longword rss_server; //holds resolve(RSS_SERVER) int bytes_read,total_bytes; //for sock_fastread int count; tcp_Socket socket; //for comm char rssCode[6500]; //7kb max downloaded file limit unsigned int pos; char temp[500]; char* newStr; char otherStr[500]; printf("Fetching headlines...\n"); if (!tcp_tick(NULL)) { printf(" ! No network"); return 0; } //connect to the server if (!(rss_server = resolve(rss_site))) { printf(" ! Could not resolve host"); return 0; } if( !tcp_open(&socket,0,rss_server,HTTP_PORT,NULL)){ printf(" ! Unable to connect to remote server"); return 0; } //wait for the connection to be established while (!sock_established(&socket) && sock_bytesready(&socket)==-1){ tcp_tick(NULL); } printf(" connected! sending request\n"); //get the RSS code memset(rssCode,0,sizeof(rssCode)); //empty it first! sock_puts(&socket,"GET "); sock_puts(&socket,rss_page); sock_puts(&socket," HTTP/1.0\n"); sock_puts(&socket,"Accept: text/xml\nAccept: text/plain\nAccept: application/rss+xml\n\n"); sock_puts(&socket,"User-Agent: Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0 \r\n\r\n"); total_bytes=0; do{ //this should be changed to parse as we receive each set of //bytes, so we don't need to waste 10k of memory with the big //rssCode array... bytes_read=sock_fastread(&socket,rssCode+total_bytes,sizeof(rssCode)-1-total_bytes); total_bytes+=bytes_read; } while(tcp_tick(&socket) && (total_bytes < sizeof(rssCode)-2)); printf(" Connection closed (received %d bytes)...\n",total_bytes); if(total_bytes<600) printf(rssCode); //parse out the headlines memset(headlines,0,sizeof(headlines)); strcat(headlines,"** "); newStr = strstr(rssCode,"<title>"); newStr = strstr(newStr,">"); count=0; while((newStr!= NULL)){ pos = strcspn(newStr,"<"); temp[0] = 0; strncat(temp,newStr,pos); substr(otherStr,temp,1,strlen(temp)); printf(" - \"%s\"\n",otherStr); //debug - print out the headline strcat(headlines,otherStr); strcat(headlines,"... "); newStr = strstr(newStr,"</title>"); newStr = strstr(newStr,"<title>"); newStr = strstr(newStr,">"); count++; } printf("Parsed out %d headlines.\n\n",count); return 1; }
SSLSTREAM *ssl_open (char *host,char *service,unsigned long port) { TCPSTREAM *stream = tcp_open (host,service,port); return stream ? ssl_start (stream,host,port) : NIL; }
bool mubinccpy(backup_reg_list *list) { static readonly mval null_str = {MV_STR, 0, 0 , 0 , 0, 0}; int backup_socket; int4 size, size1, bsize, bm_num, hint, lmsize, save_blks, rsize, match, timeout, outsize; uint4 status, total_blks, bplmap, gds_ratio, blks_per_buff, counter, i, lcnt, read_size; uchar_ptr_t bm_blk_buff, ptr1, ptr1_top, ptr, ptr_top; char_ptr_t outptr, data_ptr; unsigned short rd_iosb[4], port; enum db_acc_method access; blk_hdr *bp, *bptr; struct FAB *fcb, temp_fab, mubincfab; struct RAB temp_rab, mubincrab; inc_header *outbuf; mval val; mstr *file; sgmnt_data_ptr_t header; char *common, addr[SA_MAXLEN + 1]; void (*common_write)(); void (*common_close)(); muinc_blk_hdr_ptr_t sblkh_p; trans_num blk_tn; block_id blk_num_base, blk_num; boolean_t is_bitmap_blk, backup_this_blk; enum db_ver dummy_odbv; int4 blk_bsiz; error_def(ERR_BCKUPBUFLUSH); error_def(ERR_COMMITWAITSTUCK); error_def(ERR_DBCCERR); error_def(ERR_ERRCALL); assert(list->reg == gv_cur_region); assert(incremental); /* Make sure inc_header can be same size on all platforms. Some platforms pad 8 byte aligned structures that end on a 4 byte boundary and some do not. It is critical that this structure is the same size on all platforms as it is sent across TCP connections when doing TCP backup. */ assert(0 == (SIZEOF(inc_header) % 8)); /* ================= Initialization and some checks ======================== */ header = list->backup_hdr; file = &(list->backup_file); if (!mubtomag) mubmaxblk = BACKUP_TEMPFILE_BUFF_SIZE; fcb = ((vms_gds_info *)(gv_cur_region->dyn.addr->file_cntl->file_info))->fab; if (list->tn >= header->trans_hist.curr_tn) { util_out_print("!/TRANSACTION number is greater than or equal to current transaction,", TRUE); util_out_print("No blocks backed up from database !AD", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); return TRUE; } /* =========== open backup destination and define common_write ================= */ backup_write_errno = 0; backup_close_errno = 0; switch(list->backup_to) { case backup_to_file: /* open the file and define the common_write function */ mubincfab = cc$rms_fab; mubincfab.fab$b_fac = FAB$M_PUT; mubincfab.fab$l_fop = FAB$M_CBT | FAB$M_MXV | FAB$M_TEF | FAB$M_POS & (~FAB$M_RWC) & (~FAB$M_RWO); mubincfab.fab$l_fna = file->addr; mubincfab.fab$b_fns = file->len; mubincfab.fab$l_alq = cs_addrs->hdr->start_vbn + STARTING_BLOCKS * cs_addrs->hdr->blk_size / DISK_BLOCK_SIZE; mubincfab.fab$w_mrs = mubmaxblk; mubincfab.fab$w_deq = EXTEND_SIZE; switch (status = sys$create(&mubincfab)) { case RMS$_NORMAL: case RMS$_CREATED: case RMS$_SUPERSEDE: case RMS$_FILEPURGED: break; default: gtm_putmsg(status, 0, mubincfab.fab$l_stv); util_out_print("Error: Cannot create backup file !AD.", TRUE, mubincfab.fab$b_fns, mubincfab.fab$l_fna); return FALSE; } mubincrab = cc$rms_rab; mubincrab.rab$l_fab = &mubincfab; mubincrab.rab$l_rop = RAB$M_WBH; if (RMS$_NORMAL != (status = sys$connect(&mubincrab))) { gtm_putmsg(status, 0, mubincrab.rab$l_stv); util_out_print("Error: Cannot connect to backup file !AD.", TRUE, mubincfab.fab$b_fns, mubincfab.fab$l_fna); mubincfab.fab$l_fop |= FAB$M_DLT; sys$close(&mubincfab); return FALSE; } common = (char *)(&mubincrab); common_write = file_write; common_close = file_close; break; case backup_to_exec: util_out_print("Error: Backup to pipe is yet to be implemented.", TRUE); util_out_print("Error: Your request to backup database !AD to !AD is currently not valid.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna, file->len, file->addr); return FALSE; case backup_to_tcp: iotcp_fillroutine(); /* parse it first */ switch (match = SSCANF(file->addr, "%[^:]:%hu", addr, &port)) { case 1 : port = DEFAULT_BKRS_PORT; case 2 : break; default : util_out_print("ERROR: A hostname has to be specified to backup through a TCP connection.", TRUE); return FALSE; } if ((0 == cli_get_int("NETTIMEOUT", &timeout)) || (0 > timeout)) timeout = DEFAULT_BKRS_TIMEOUT; if (0 > (backup_socket = tcp_open(addr, port, timeout, FALSE))) { util_out_print("ERROR: Cannot open tcp connection due to the above error.", TRUE); return FALSE; } common_write = tcp_write; common_close = tcp_close; common = (char *)(&backup_socket); break; default : util_out_print("ERROR: Backup format !UL not supported.", TRUE, list->backup_to); util_out_print("Error: Your request to backup database !AD to !AD is not valid.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna, file->len, file->addr); return FALSE; } /* ============================= write inc_header =========================================== */ outptr = malloc(SIZEOF(inc_header)); outbuf = (inc_header *)outptr; MEMCPY_LIT(&outbuf->label[0], INC_HEADER_LABEL); stringpool.free = stringpool.base; op_horolog(&val); stringpool.free = stringpool.base; op_fnzdate(&val, &mu_bin_datefmt, &null_str, &null_str, &val); memcpy(&outbuf->date[0], val.str.addr, val.str.len); memcpy(&outbuf->reg[0], gv_cur_region->rname, MAX_RN_LEN); outbuf->start_tn = list->tn; outbuf->end_tn = header->trans_hist.curr_tn; outbuf->db_total_blks = header->trans_hist.total_blks; outbuf->blk_size = header->blk_size; outbuf->blks_to_upgrd = header->blks_to_upgrd; COMMON_WRITE(common, outptr, SIZEOF(inc_header)); free(outptr); if (mu_ctrly_occurred || mu_ctrlc_occurred) { error_mupip = TRUE; COMMON_CLOSE(common); util_out_print("WARNING: DB file !AD backup aborted.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); return FALSE; } /* ============================ read/write appropriate blocks =============================== */ bsize = header->blk_size; gds_ratio = bsize / DISK_BLOCK_SIZE; blks_per_buff = BACKUP_READ_SIZE / bsize; read_size = blks_per_buff * bsize; outsize = SIZEOF(muinc_blk_hdr) + bsize; outptr = (char_ptr_t)malloc(MAX(outsize, mubmaxblk)); sblkh_p = (muinc_blk_hdr_ptr_t)outptr; data_ptr = (char_ptr_t)(sblkh_p + 1); bp = (blk_hdr_ptr_t)mubbuf; bm_blk_buff = (uchar_ptr_t)malloc(SIZEOF(blk_hdr) + (BLKS_PER_LMAP * BML_BITS_PER_BLK / BITS_PER_UCHAR)); mubincrab.rab$l_rbf = outptr; save_blks = 0; access = header->acc_meth; memset(sblkh_p, 0, SIZEOF(*sblkh_p)); if (access == dba_bg) bp = mubbuf; else { ptr = cs_addrs->db_addrs[0] + (cs_addrs->hdr->start_vbn - 1) * DISK_BLOCK_SIZE; ptr_top = cs_addrs->db_addrs[1] + 1; } sblkh_p->use.bkup.ondsk_blkver = GDSNOVER; for (blk_num_base = 0; blk_num_base < header->trans_hist.total_blks; blk_num_base += blks_per_buff) { if (online && (0 != cs_addrs->shmpool_buffer->failed)) break; if (header->trans_hist.total_blks - blk_num_base < blks_per_buff) { blks_per_buff = header->trans_hist.total_blks - blk_num_base; read_size = blks_per_buff * bsize; } if (access == dba_bg) { if ((SS$_NORMAL != (status = sys$qiow(EFN$C_ENF, fcb->fab$l_stv, IO$_READVBLK, &rd_iosb, 0, 0, bp, read_size, cs_addrs->hdr->start_vbn + (gds_ratio * blk_num_base), 0, 0, 0))) || (SS$_NORMAL != (status = rd_iosb[0]))) { gtm_putmsg(VARLSTCNT(1) status); util_out_print("Error reading data from database !AD.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } } else { assert(dba_mm == access); bp = ptr + blk_num_base * bsize; } bptr = (blk_hdr *)bp; /* The blocks we back up will be whatever version they are. There is no implicit conversion in this part of the backup/restore. Since we aren't even looking at the blocks (and indeed some of these blocks could potentially contain unintialized garbage data), we set the block version to GDSNOVER to signal that the block version is unknown. The above applies to "regular" blocks but not to bitmap blocks which we know are initialized. Because we have to read the bitmap blocks, they will be converted as necessary. */ for (i = 0; i < blks_per_buff && ((blk_num_base + i) < header->trans_hist.total_blks); i++, bptr = (blk_hdr *)((char *)bptr + bsize)) { blk_num = blk_num_base + i; if (mu_ctrly_occurred || mu_ctrlc_occurred) { free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); util_out_print("WARNING: DB file !AD backup aborted.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); return FALSE; } /* Before we check if this block needs backing up, check if this is a new bitmap block or not. If it is, we can fall through and back it up as normal. But if this is NOT a bitmap block, use the existing bitmap to determine if this block has ever been allocated or not. If not, we don't want to even look at this block. It could be uninitialized which will just make things run slower if we go to read it and back it up. */ if (0 != ((BLKS_PER_LMAP - 1) & blk_num)) { /* Not a local bitmap block */ if (!gvcst_blk_ever_allocated(bm_blk_buff + SIZEOF(blk_hdr), ((blk_num * BML_BITS_PER_BLK) % (BLKS_PER_LMAP * BML_BITS_PER_BLK)))) continue; /* Bypass never-set blocks to avoid conversion problems */ is_bitmap_blk = FALSE; if (SIZEOF(v15_blk_hdr) <= (blk_bsiz = ((v15_blk_hdr_ptr_t)bptr)->bsiz)) { /* We have either a V4 block or uninitialized garbage */ if (blk_bsiz > bsize) /* This is not a valid V4 block so ignore it */ continue; blk_tn = ((v15_blk_hdr_ptr_t)bptr)->tn; } else { /* Assume V5 block */ if ((blk_bsiz = bptr->bsiz) > bsize) /* Not a valid V5 block either */ continue; blk_tn = bptr->tn; } } else { /* This is a bitmap block so save it into our bitmap block buffer. It is used as the basis of whether or not we have to process a given block or not. We process allocated and recycled blocks leaving free (never used) blocks alone as they have no data worth saving. But after saving it, upgrade it to the current format if necessary. */ is_bitmap_blk = TRUE; memcpy(bm_blk_buff, bptr, BM_SIZE(header->bplmap)); if (SIZEOF(v15_blk_hdr) <= ((v15_blk_hdr_ptr_t)bm_blk_buff)->bsiz) { /* This is a V4 format block -- needs upgrading */ status = gds_blk_upgrade(bm_blk_buff, bm_blk_buff, bsize, &dummy_odbv); if (SS_NORMAL != status) { free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); util_out_print("Error: Block 0x!XL is too large for automatic upgrade", TRUE, sblkh_p->blkid); return FALSE; } } assert(BM_SIZE(header->bplmap) == ((blk_hdr_ptr_t)bm_blk_buff)->bsiz); assert(LCL_MAP_LEVL == ((blk_hdr_ptr_t)bm_blk_buff)->levl); assert(gvcst_blk_is_allocated(bm_blk_buff + SIZEOF(blk_hdr), ((blk_num * BML_BITS_PER_BLK) % (BLKS_PER_LMAP * BML_BITS_PER_BLK)))); blk_bsiz = BM_SIZE(header->bplmap); blk_tn = ((blk_hdr_ptr_t)bm_blk_buff)->tn; } /* The conditions for backing up a block or ignoring it (in order of evaluation): 1) If blk is larger than size of db at time backup was initiated, we ignore the block. 2) Always backup blocks 0, 1, and 2 as these are the only blocks that can contain data and still have a transaction number of 0. 3) For bitmap blocks, if blks_to_upgrd != 0 and the TN is 0 and the block number >= last_blk_at_last_bkup, then backup the block. This way we get the correct version of the bitmap block in the restore (otherwise have no clue what version to create them in as bitmaps are created with a TN of 0 when before image journaling is enabled). 4) If the block TN is below our TN threshold, ignore the block. 5) Else if none of the above conditions, backup the block. */ if (online && (header->trans_hist.curr_tn <= blk_tn)) backup_this_blk = FALSE; else if (3 > blk_num || (is_bitmap_blk && 0 != header->blks_to_upgrd && (trans_num)0 == blk_tn && blk_num >= list->last_blk_at_last_bkup)) backup_this_blk = TRUE; else if ((blk_tn < list->tn)) backup_this_blk = FALSE; else backup_this_blk = TRUE; if (!backup_this_blk) { if (online) cs_addrs->nl->nbb = blk_num; continue; /* not applicable */ } sblkh_p->blkid = blk_num; memcpy(data_ptr, bptr, blk_bsiz); sblkh_p->valid_data = TRUE; /* Validation marker */ COMMON_WRITE(common, outptr, outsize); if (online) { if (0 != cs_addrs->shmpool_buffer->failed) break; cs_addrs->nl->nbb = blk_num; } save_blks++; } } /* ============================= write saved information for online backup ========================== */ if (online && (0 == cs_addrs->shmpool_buffer->failed)) { /* -------- make sure everyone involved finishes -------- */ cs_addrs->nl->nbb = BACKUP_NOT_IN_PROGRESS; /* By getting crit here, we ensure that there is no process still in transaction logic that sees (nbb != BACKUP_NOT_IN_PRORESS). After rel_crit(), any process that enters transaction logic will see (nbb == BACKUP_NOT_IN_PRORESS) because we just set it to that value. At this point, backup buffer is complete and there will not be any more new entries in the backup buffer until the next backup. */ grab_crit(gv_cur_region); assert(cs_data == cs_addrs->hdr); if (dba_bg == cs_data->acc_meth) { /* Now that we have crit, wait for any pending phase2 updates to finish. Since phase2 updates happen * outside of crit, we dont want them to keep writing to the backup temporary file even after the * backup is complete and the temporary file has been deleted. */ if (cs_addrs->nl->wcs_phase2_commit_pidcnt && !wcs_phase2_commit_wait(cs_addrs, NULL)) { gtm_putmsg(VARLSTCNT(7) ERR_COMMITWAITSTUCK, 5, process_id, 1, cs_addrs->nl->wcs_phase2_commit_pidcnt, DB_LEN_STR(gv_cur_region)); rel_crit(gv_cur_region); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } } if (debug_mupip) { util_out_print("MUPIP INFO: Current Transaction # at end of backup is 0x!16@XQ", TRUE, &cs_data->trans_hist.curr_tn); } rel_crit(gv_cur_region); counter = 0; while (0 != cs_addrs->shmpool_buffer->backup_cnt) { if (0 != cs_addrs->shmpool_buffer->failed) { util_out_print("Process !UL encountered the following error.", TRUE, cs_addrs->shmpool_buffer->failed); if (0 != cs_addrs->shmpool_buffer->backup_errno) gtm_putmsg(VARLSTCNT(1) cs_addrs->shmpool_buffer->backup_errno); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } backup_buffer_flush(gv_cur_region); if (++counter > MAX_BACKUP_FLUSH_TRY) { gtm_putmsg(VARLSTCNT(1) ERR_BCKUPBUFLUSH); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } if (counter & 0xF) wcs_sleep(counter); else { /* Force shmpool recovery to see if it can find the lost blocks */ if (!shmpool_lock_hdr(gv_cur_region)) { gtm_putmsg(VARLSTCNT(9) ERR_DBCCERR, 2, REG_LEN_STR(gv_cur_region), ERR_ERRCALL, 3, CALLFROM); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); assert(FALSE); return FALSE;; } shmpool_abandoned_blk_chk(gv_cur_region, TRUE); shmpool_unlock_hdr(gv_cur_region); } } /* -------- Open the temporary file -------- */ temp_fab = cc$rms_fab; temp_fab.fab$b_fac = FAB$M_GET; temp_fab.fab$l_fna = list->backup_tempfile; temp_fab.fab$b_fns = strlen(list->backup_tempfile); temp_rab = cc$rms_rab; temp_rab.rab$l_fab = &temp_fab; for (lcnt = 1; MAX_OPEN_RETRY >= lcnt; lcnt++) { if (RMS$_FLK != (status = sys$open(&temp_fab, NULL, NULL))) break; wcs_sleep(lcnt); } if (RMS$_NORMAL != status) { gtm_putmsg(status, 0, temp_fab.fab$l_stv); util_out_print("WARNING: DB file !AD backup aborted.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } if (RMS$_NORMAL != (status = sys$connect(&temp_rab))) { gtm_putmsg(status, 0, temp_rab.rab$l_stv); util_out_print("WARNING: DB file !AD backup aborted.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } /* -------- read and write every record in the temporary file -------- */ while (1) { temp_rab.rab$w_usz = outsize; temp_rab.rab$l_ubf = outptr; status = sys$get(&temp_rab); if (RMS$_NORMAL != status) { if (RMS$_EOF == status) status = RMS$_NORMAL; break; } assert(outsize == temp_rab.rab$w_rsz); /* Still validly sized blk? */ assert((outsize - SIZEOF(shmpool_blk_hdr)) >= ((blk_hdr_ptr_t)(outptr + SIZEOF(shmpool_blk_hdr)))->bsiz); COMMON_WRITE(common, outptr, temp_rab.rab$w_rsz); } if (RMS$_NORMAL != status) { gtm_putmsg(status, 0, temp_rab.rab$l_stv); util_out_print("WARNING: DB file !AD backup aborted.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } /* ---------------- Close the temporary file ----------------------- */ if (RMS$_NORMAL != (status = sys$close(&temp_fab))) { gtm_putmsg(status, 0, temp_fab.fab$l_stv); util_out_print("WARNING: DB file !AD backup aborted.", TRUE, fcb->fab$b_fns, fcb->fab$l_fna); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } } /* ============================= write end_msg and fileheader ======================================= */ if ((!online) || (0 == cs_addrs->shmpool_buffer->failed)) { MEMCPY_LIT(outptr, END_MSG); /* Although the write only need be of length SIZEOF(END_MSG) - 1 for file IO, if the write is going to TCP we have to write all these records with common length so just write the "regular" sized buffer. The extra garbage left over from the last write will be ignored as we key only on the this end text. */ COMMON_WRITE(common, outptr, outsize); ptr1 = header; size1 = ROUND_UP(SIZEOF(sgmnt_data), DISK_BLOCK_SIZE); ptr1_top = ptr1 + size1; for (;ptr1 < ptr1_top ; ptr1 += size1) { if ((size1 = ptr1_top - ptr1) > mubmaxblk) size1 = (mubmaxblk / DISK_BLOCK_SIZE) * DISK_BLOCK_SIZE; COMMON_WRITE(common, ptr1, size1); } MEMCPY_LIT(outptr, HDR_MSG); COMMON_WRITE(common, outptr, SIZEOF(HDR_MSG)); ptr1 = MM_ADDR(header); size1 = ROUND_UP(MASTER_MAP_SIZE(header), DISK_BLOCK_SIZE); ptr1_top = ptr1 + size1; for (;ptr1 < ptr1_top ; ptr1 += size1) { if ((size1 = ptr1_top - ptr1) > mubmaxblk) size1 = (mubmaxblk / DISK_BLOCK_SIZE) * DISK_BLOCK_SIZE; COMMON_WRITE(common, ptr1, size1); } MEMCPY_LIT(outptr, MAP_MSG); COMMON_WRITE(common, outptr, SIZEOF(MAP_MSG)); } /* ================== close backup destination, output and return ================================== */ if (online && (0 != cs_addrs->shmpool_buffer->failed)) { util_out_print("Process !UL encountered the following error.", TRUE, cs_addrs->shmpool_buffer->failed); if (0 != cs_addrs->shmpool_buffer->backup_errno) gtm_putmsg(VARLSTCNT(1) cs_addrs->shmpool_buffer->backup_errno); free(outptr); free(bm_blk_buff); error_mupip = TRUE; COMMON_CLOSE(common); return FALSE; } COMMON_CLOSE(common); free(outptr); free(bm_blk_buff); util_out_print("DB file !AD incrementally backed up in !AD", TRUE, fcb->fab$b_fns, fcb->fab$l_fna, file->len, file->addr); util_out_print("!UL blocks saved.", TRUE, save_blks); util_out_print("Transactions from 0x!16@XQ to 0x!16@XQ are backed up.", TRUE, &cs_addrs->shmpool_buffer->inc_backup_tn, &header->trans_hist.curr_tn); cs_addrs->hdr->last_inc_backup = header->trans_hist.curr_tn; if (record) cs_addrs->hdr->last_rec_backup = header->trans_hist.curr_tn; file_backed_up = TRUE; return TRUE; }
int main(int argc, char **argv) { if(argc<3) { printf("Mail utility are needed a message file and\n" "and mail address of recipient\n" "call: <function> <message file> <RCPT addr>\n"); return 0; } size_t SIZE=100; char response[SIZE],query[SIZE]; char *sender =(char *) "*****@*****.**"; // char *str= new char[len]; // sprintf(str,"nc %s %s",argv[1],argv[2]); // FILE *chanel = popen(str,"w"); FILE *message = fopen(argv[1],"r"); assert(message!=NULL); char *Domain = (char *) memchr(argv[2],'@',strlen(argv[2])); *Domain='\0'; Domain++; char *recipient = argv[2]; char yandexServ[]="mx.yandex.ru"; char gmailServ[]="gmail-smtp-in.l.google.com"; char yandex[]="yandex"; char gmail[]="gmail"; char *domainName; if(!strncmp(yandex,Domain,strlen(yandex))) { domainName = yandexServ; } else if(!strncmp(gmail,Domain,strlen(gmail))) { domainName=gmailServ; } else { domainName = Domain; } printf("%s\n%s\n",recipient,domainName); hostent *host = gethostbyname2(domainName,AF_INET); #ifndef Release for(int i=0;host->h_addr_list[i];i++) printf("%d:%s\n",i, inet_ntoa(*( in_addr *)host->h_addr_list[i])); #endif // //Create socket and bind it MySocket *sock=tcp_open(host->h_addr_list[1],25); getMessage(sock->sd,response,SIZE); int n; //Greeting n=sprintf(query,"HELO zhucci\n"); printf("%s",query); write(sock->sd,query,n); getMessage(sock->sd,response,SIZE); //MAIL FROM n = sprintf(query,"MAIL FROM:<%s>\n",sender); printf("%s",query); write(sock->sd,query,n); getMessage(sock->sd,response,SIZE); //RCPT TO n=sprintf(query,"RCPT TO:<%s@%s>\n",recipient,Domain); printf("%s",query); n= write(sock->sd,query,n); getMessage(sock->sd,response,SIZE); //DATA n=sprintf(query,"DATA\n"); n=write(sock->sd,query,n); printf("%s",query); getMessage(sock->sd,response,SIZE); // n=sprintf(query,"Date: 8 Aug 1998 04:10:45 -0000\n"); // n= write(sock->sd,query,n); // printf("%s",query); //Header n=sprintf(query,"From:%s\n",sender); n= write(sock->sd,query,n); printf("%s",query); // getMessage(sock->sd,response,SIZE); n=sprintf(query,"To:%s@%s\n",recipient,Domain); n= write(sock->sd,query,n); printf("%s",query); // getMessage(sock->sd,response,SIZE); n=sprintf(query,"Subject: Socket test\n"); n= write(sock->sd,query,n); printf("%s",query); // getMessage(sock->sd,response,SIZE); //New line n=sprintf(query,"\n"); write(sock->sd,query,n); printf("%s",query); char *buf= (char *)malloc(SIZE+1); //MSG TEXT for(; ( n=getline(&buf,&SIZE,message) ) > 0;) { n=sprintf(query,"%s",buf); write(sock->sd,query,n); printf("%s",query); } //END MSG \n'.'\n n=sprintf(query,"\n"); write(sock->sd,query,n); printf("%s",query); n=sprintf(query,".\n"); write(sock->sd,query,n); printf("%s",query); getMessage(sock->sd,response,SIZE); //QUIT n=sprintf(query,"QUIT\n"); write(sock->sd,buf,n); printf("%s",query); //END // fromServer.close(); shutdown(sock->sd,SHUT_WR); close(sock->sd); return 0; }
int usys_socket(int *err, uuprocess_t *u, int domain, int type, int protocol) { if( domain != PF_INET ) { *err = EAFNOSUPPORT; return -1; } if( type != SOCK_STREAM && type != SOCK_DGRAM ) { *err = EINVAL; return -1; } if( protocol != 0 ) SHOW_INFO( 0, "Warning: proto %d", protocol ); int isTCP = (type == SOCK_STREAM); struct uusocket *us = calloc(1, sizeof(struct uusocket)); if(us == 0) { *err = ENOMEM; return -1; } if( isTCP ) { if( tcp_open(&(us->prot_data)) ) { SHOW_ERROR0(0, "can't prepare TCP endpoint"); fail: free(us); return 0; } } else { if( udp_open(&(us->prot_data)) ) { SHOW_ERROR0(0, "can't prepare UDP endpoint"); goto fail; } } uufile_t *f = create_uufile(); f->ops = isTCP ? &tcpfs_fops : &udpfs_fops; f->pos = 0; f->fs = isTCP ? &tcp_fs : &udp_fs; f->impl = us; f->flags = UU_FILE_FLAG_NET| (isTCP ? UU_FILE_FLAG_TCP : UU_FILE_FLAG_UDP); int fd = uu_find_fd( u, f ); if( fd < 0 ) { f->fs->close( f ); *err = EMFILE; return -1; } return fd; }
/* ping host , char *cmdstr*/ int run_ping6(int argc, char **argv) { pcs *pc = &vpc[pcid]; struct in6_addr ipaddr; struct packet *m = NULL; int i; char *p; char proto_seq[16]; int count = 5; printf("\n"); i = 2; for (i = 2; i < argc; i++) { if (!strcmp(argv[i], "-c")) { if ((i + 1) < argc && digitstring(argv[i + 1])) count = atoi(argv[i + 1]); break; } } if (vinet_pton6(AF_INET6, argv[1], &ipaddr) != 1) { printf("Invalid address: %s\n", argv[1]); return 0; } memcpy(pc->mscb.dip6.addr8, ipaddr.s6_addr, 16); if (pc->mscb.dip6.addr16[0] != IPV6_ADDR_INT16_ULL) memcpy(pc->mscb.sip6.addr8, pc->ip6.ip.addr8, 16); else memcpy(pc->mscb.sip6.addr8, pc->link6.ip.addr8, 16); /* ping self, discard options */ if (IP6EQ(&pc->mscb.sip6, &pc->mscb.dip6)) { i = 1; while (i < 6) { printf("%s icmp_seq=%d ttl=%d time=0.001 ms\n", argv[1], i++, pc->mscb.ttl); delay_ms(1); } return 1; } /* find destination */ p = (char*)nbDiscovery(pc, &pc->mscb.dip6); if (p == NULL) { printf("host (%s) not reachable\n", argv[1]); return 0; } memcpy(pc->mscb.dmac, p, 6); if (pc->mscb.proto == IPPROTO_ICMP) { pc->mscb.proto = IPPROTO_ICMPV6; strcpy(proto_seq, "icmp6_seq"); } else if (pc->mscb.proto == IPPROTO_TCP) { strcpy(proto_seq, "tcp6_seq"); } else if (pc->mscb.proto == IPPROTO_UDP) { strcpy(proto_seq, "udp6_seq"); } if (pc->mscb.proto == IPPROTO_TCP && pc->mscb.flags == 0) { i = 0; while ((i++ < count || count == -1) && !ctrl_c) { struct timeval ts0, ts; u_int usec; int k; int dsize = pc->mscb.dsize; int traveltime = 1; if (i > 1) delay_ms(pc->mscb.waittime); /* clear the input queue */ while ((m = deq(&pc->iq)) != NULL); /* connect the remote */ gettimeofday(&(ts), (void*)0); k = tcp_open(IPV6_VERSION); /* restore data size */ pc->mscb.dsize = dsize; gettimeofday(&(ts0), (void*)0); usec = (ts0.tv_sec - ts.tv_sec) * 1000000 + ts0.tv_usec - ts.tv_usec; if (k == 0) { printf("Connect %d@%s timeout\n", pc->mscb.dport, argv[1]); continue; } else if (k == 2) { char buf[INET6_ADDRSTRLEN + 1]; memset(buf, 0, sizeof(buf)); vinet_ntop6(AF_INET6, &pc->mscb.rdip6, buf, INET6_ADDRSTRLEN + 1); printf("*%s %s=%d ttl=%d time=%.3f ms", buf, proto_seq, i++, pc->mscb.rttl, usec / 1000.0); printf(" (ICMP type:%d, code:%d, %s)\n", pc->mscb.icmptype, pc->mscb.icmpcode, icmpTypeCode2String(6, pc->mscb.icmptype, pc->mscb.icmpcode)); continue; } else if (k == 3) { printf("Connect %d@%s RST returned\n", pc->mscb.dport, argv[1]); continue; } printf("Connect %d@%s seq=%d ttl=%d time=%.3f ms\n", pc->mscb.dport, argv[1], i, pc->mscb.rttl, usec / 1000.0); traveltime = 0.6 * usec / 1000; /* send data */ delay_ms(traveltime); gettimeofday(&(ts), (void*)0); k = tcp_send(IPV6_VERSION); if (k == 0) { printf("SendData %d@%s timeout\n", pc->mscb.dport, argv[1]); continue; } gettimeofday(&(ts0), (void*)0); usec = (ts0.tv_sec - ts.tv_sec) * 1000000 + ts0.tv_usec - ts.tv_usec; printf("SendData %d@%s seq=%d ttl=%d time=%.3f ms\n", pc->mscb.dport, argv[1], i, pc->mscb.rttl, usec / 1000.0); /* close */ if (k != 2) delay_ms(traveltime); gettimeofday(&(ts), (void*)0); k = tcp_close(IPV6_VERSION); if (k == 0) { printf("Close %d@%s timeout\n", pc->mscb.dport, argv[1]); continue; } gettimeofday(&(ts0), (void*)0); usec = (ts0.tv_sec - ts.tv_sec) * 1000000 + ts0.tv_usec - ts.tv_usec; printf("Close %d@%s seq=%d ttl=%d time=%.3f ms\n", pc->mscb.dport, argv[1], i, pc->mscb.rttl, usec / 1000.0); } } else { i = 1; while ((i <= count || count == -1) && !ctrl_c) { struct packet *p; struct timeval tv; u_int usec; int respok = 0; pc->mscb.sn = i; pc->mscb.timeout = time_tick; m = packet6(&pc->mscb); if (m == NULL) { printf("out of memory\n"); return false; } gettimeofday(&(tv), (void*)0); enq(&pc->oq, m); while (!timeout(tv, pc->mscb.waittime) && !ctrl_c) { delay_ms(1); respok = 0; while ((p = deq(&pc->iq)) != NULL && !respok && !timeout(tv, pc->mscb.waittime) && !ctrl_c) { pc->mscb.icmptype = pc->mscb.icmpcode = 0; respok = response6(p, &pc->mscb); usec = (p->ts.tv_sec - tv.tv_sec) * 1000000 + p->ts.tv_usec - tv.tv_usec; del_pkt(p); if (respok == 0) continue; tv.tv_sec = 0; if ((pc->mscb.proto == IPPROTO_ICMPV6 && pc->mscb.icmptype == ICMP6_ECHO_REPLY) || (pc->mscb.proto == IPPROTO_UDP && respok == IPPROTO_UDP)|| (pc->mscb.proto == IPPROTO_TCP && respok == IPPROTO_TCP)) { printf("%s %s=%d ttl=%d time=%.3f ms\n", argv[1], proto_seq, i++, pc->mscb.rttl, usec / 1000.0); break; } if (respok == IPPROTO_ICMPV6) { char buf[INET6_ADDRSTRLEN + 1]; memset(buf, 0, sizeof(buf)); vinet_ntop6(AF_INET6, &pc->mscb.rdip6, buf, INET6_ADDRSTRLEN + 1); printf("*%s %s=%d ttl=%d time=%.3f ms", buf, proto_seq, i++, pc->mscb.rttl, usec / 1000.0); printf(" (ICMP type:%d, code:%d, %s)\n", pc->mscb.icmptype, pc->mscb.icmpcode, icmpTypeCode2String(6, pc->mscb.icmptype, pc->mscb.icmpcode)); break; } } } if (!respok && !ctrl_c) printf("%s %s=%d timeout\n", argv[1], proto_seq, i++); } } return 1; }
int ftp_open(char * arg) { char * host; int port; char * dir; char * file; int tcp_sock; int data_sock; char ftp_request[1024]; struct sockaddr_in stLclAddr; socklen_t namelen; int i; /* Check for URL syntax */ if(strncmp(arg, "ftp://", strlen("ftp://"))) return(0); /* Parse URL */ port = 21; host = arg + strlen("ftp://"); if((dir = strchr(host, '/')) == NULL) return(0); *dir++ = 0; if((file = strrchr(dir, '/')) == NULL) { file = dir; dir = NULL; } else *file++ = 0; if(strchr(host, ':') != NULL) /* port is specified */ { port = atoi(strchr(host, ':') + 1); *strchr(host, ':') = 0; } /* Open a TCP socket */ if(!(tcp_sock = tcp_open(host, port))) { perror("ftp_open"); return(0); } /* Send FTP USER and PASS request */ ftp_get_reply(tcp_sock); sprintf(ftp_request, "USER anonymous\r\n"); send(tcp_sock, ftp_request, strlen(ftp_request), 0); if(ftp_get_reply(tcp_sock) != 331) return(0); sprintf(ftp_request, "PASS smpeguser@\r\n"); send(tcp_sock, ftp_request, strlen(ftp_request), 0); if(ftp_get_reply(tcp_sock) != 230) return(0); sprintf(ftp_request, "TYPE I\r\n"); send(tcp_sock, ftp_request, strlen(ftp_request), 0); if(ftp_get_reply(tcp_sock) != 200) return(0); if(dir != NULL) { sprintf(ftp_request, "CWD %s\r\n", dir); send(tcp_sock, ftp_request, strlen(ftp_request), 0); if(ftp_get_reply(tcp_sock) != 250) return(0); } /* Get interface address */ namelen = sizeof(stLclAddr); if(getsockname(tcp_sock, (struct sockaddr *) &stLclAddr, &namelen) < 0) return(0); /* Open data socket */ if ((data_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) return(0); stLclAddr.sin_family = AF_INET; /* Get the first free port */ for(i = 0; i < 0xC000; i++) { stLclAddr.sin_port = htons(0x4000 + i); if(bind(data_sock, (struct sockaddr *) &stLclAddr, sizeof(stLclAddr)) >= 0) break; } port = 0x4000 + i; if(listen(data_sock, 1) < 0) return(0); i = ntohl(stLclAddr.sin_addr.s_addr); sprintf(ftp_request, "PORT %d,%d,%d,%d,%d,%d\r\n", (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF, (port >> 8) & 0xFF, port & 0xFF); send(tcp_sock, ftp_request, strlen(ftp_request), 0); if(ftp_get_reply(tcp_sock) != 200) return(0); sprintf(ftp_request, "RETR %s\r\n", file); send(tcp_sock, ftp_request, strlen(ftp_request), 0); if(ftp_get_reply(tcp_sock) != 150) return(0); return(accept(data_sock, NULL, NULL)); }
void main() { int status; char buffer[2048]; longword ip; int i, dst, health; struct tm t; unsigned long longsec; // open connection to NIST server sock_init(); // Wait for the interface to come up while (ifpending(IF_DEFAULT) == IF_COMING_UP) { tcp_tick(NULL); } ip=resolve(NIST_SERVER_IP); tcp_open(&s, 0, ip, NIST_PORT, NULL); sock_wait_established(&s, NIST_TIMEOUT, NULL, &status); sock_mode(&s, TCP_MODE_ASCII); // receive and process data -- the server will close the connection, // which will cause execution to continue at sock_err below. while (tcp_tick(&s)) { sock_wait_input(&s, NIST_TIMEOUT, NULL, &status); sock_gets(&s, buffer, 48); } sock_err: if (status == -1) { printf("\nConnection timed out, exiting.\n"); exit(1); } if (status != 1) { printf("\nUnknown sock_err (%d), exiting.\n", status); exit(1); } sock_close(&s); // Dynamic C doesn't have a sscanf function, so we do // it this way instead... t.tm_year = 100 + 10*(buffer[6]-'0') + (buffer[7]-'0'); t.tm_mon = 10*(buffer[9]-'0') + (buffer[10]-'0'); t.tm_mday = 10*(buffer[12]-'0') + (buffer[13]-'0'); t.tm_hour = 10*(buffer[15]-'0') + (buffer[16]-'0'); t.tm_min = 10*(buffer[18]-'0') + (buffer[19]-'0'); t.tm_sec = 10*(buffer[21]-'0') + (buffer[22]-'0'); dst = 10*(buffer[24]-'0') + (buffer[25]-'0'); health = buffer[27]-'0'; // convert from tm_struct to seconds since Jan 1, 1980 // (much easier to adjust for DST and timezone this way) longsec = mktime(&t); longsec += 3600ul * TIMEZONE; // adjust for timezone dst = (dst >= 1 && dst <= 50 ); if (dst) longsec += 3600ul; // DST is in effect // convert back to tm struct for display to stdio mktm(&t, longsec); printf("Current time: %02d:%02d:%02d %02d/%02d/%04d\n", t.tm_hour, t.tm_min, t.tm_sec, t.tm_mon, t.tm_mday, 1900 + t.tm_year); if (dst) printf("Daylight Saving Time is in effect.\n"); switch (health) { case 0: printf("Server is healthy.\n"); break; case 1: printf("Server may be off by up to 5 seconds.\n"); break; case 2: printf("Server is off by more than 5 seconds; not setting RTC.\n"); break; default: printf("Server failure has occured; try another server (not setting RTC).\n"); break; } // finally, set the RTC if the results seems good if (health < 2) write_rtc(longsec); }
int ftpsession(struct Url *url,struct HTTPrecord *cache,char *uploadfile) { longword host; char str[256]; char buffer[BUFLEN+2]; tcp_Socket datasocket; word dataport=0; int rv=0,len; char *ptr,*datahostptr,datahost[80]; char isdir=0,retry=0;//,ascii=0; long total=0; //!!glennmcc: Nov 11, 2007 -- for 'dblp code' below int dblp=0; //!!glennmcc: end //!!glennmcc: Nov 13, 2007 -- for EZNOS2 fix below int eznos2=0; //!!glennmcc: end int log; if(!tcpip)return 0; free_socket(); if((!url->file[0] || url->file[strlen(url->file)-1]=='/') && !uploadfile) isdir=1; sprintf(str,msg_askdns,url->host); outs(str); GlobalLogoStyle=0; //SDL set resolve animation host=resolve_fn( url->host, (sockfunct_t) TcpIdleFunc ); //SDL // host=resolve( url->host ); if(!host) { DNSerr(url->host); return 0; } // if(!uploadfile) //!glennmcc: Oct 20, 2012 - commented-out to make upload log more verbose log=a_open("FTP.LOG",O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE); GlobalLogoStyle=2; //SDL set connect animation if (!tcp_open( socket, locport(), host, url->port, NULL )) { sprintf(str,msg_errcon,url->host); outs(str); return 0; } sprintf(str,msg_con,url->host,url->port); outs(str); write(log,str,strlen(str)); write(log,"\r\n",2); sock_wait_established(socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status); //SDL GlobalLogoStyle=1; //SDL set data animation sock_mode( socket, TCP_MODE_ASCII ); outs(MSG_LOGIN); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); write(log,buffer,strlen(buffer)); write(log,"\r\n",2); // printf("FTP daemon said>"); // puts(buffer); if ( *buffer != '2' && buffer[0]!=' ') goto quit; } while(buffer[3]=='-' || buffer[0]==' '); //continued message! if(!url->user[0]) ptr="anonymous"; else ptr=url->user; sprintf( str, "USER %s", ptr); write(log,str,strlen(str)); write(log,"\r\n",2); sock_puts(socket,(unsigned char *)str); sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); write(log,buffer,strlen(buffer)); write(log,"\r\n",2); // printf("FTP daemon said>"); // puts(buffer); //!!glennmcc: May 11, 2005 //removed due to the fact that not all sites use '3' //see additional info below with respect to anonymous password // if ( *buffer != '3' ) goto quit; //!!glennmcc: end //open cache filename: //!glennmcc: Oct 20, 2012 - commented-out to make upload log more verbose // if(uploadfile) // strcpy(cache->locname,"FTP.LOG"); // else //!glennmcc end: Oct 20, 2012 { //!!glennmcc: Oct 22, 2008 -- strchr() was preventing the use of 'CachePath .\cache\' // ptr=strchr(cache->locname,'.'); ptr=strrchr(cache->locname,'.'); //!!glennmcc: end if(ptr) { strcpy(&ptr[1],"FTP"); strcpy(cache->rawname,cache->locname); } } cache->handle=a_open(cache->locname,O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE); if(cache->handle<0) goto quit; strcpy(cache->mime,"text/plain"); if(url->password[0]) ptr=url->password; else { if(url->user[0] && !strcmp(url->host,AUTHENTICATION->host) && !strcmp(AUTHENTICATION->realm,"$ftp")) ptr=AUTHENTICATION->password; else { ptr=configvariable(&ARACHNEcfg,"FakeFTPeMail",NULL); if(!ptr || !strchr(ptr,'@')) { ptr=configvariable(&ARACHNEcfg,"eMail",NULL); if(!ptr) ptr="@"; } } } //!!glennmcc: May 11, 2005 //some sites do not require a password after 'anonymous' //therefer, this entire block is now within this 'if()' so that //the password (email address), will only be sent if asked for //!!glennmcc: Nov 13, 2007 -- EZNOS2 says "Enter PASS command" if (strstr(buffer,"sword") || strstr(buffer,"Enter PASS command")) //if (strstr(buffer,"sword"))//original line { sprintf( str, "PASS %s", ptr); sock_puts(socket,(unsigned char *)str); write(log,str,strlen(str)); write(log,"\r\n",2); }//!!glennmcc: inserted Mar 02, 2008 //Some servers need the following 'do/while' section, //therefore, only the section above for sending the password needs to be //'blocked' when no password was requested. do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); write(log,buffer,strlen(buffer)); write(log,"\r\n",2); // printf("FTP daemon said>"); // puts(buffer); if (strstr(buffer,"Enter PASS command")) eznos2=1; if (*buffer != '2' && buffer[0]!=' ' && !eznos2) { write(cache->handle,buffer,strlen(buffer)); rv=1; goto quit; } else if ((buffer[3]=='-' || buffer[0]==' ') && (isdir || uploadfile)) { strcat(buffer,"\r\n"); rv=1; write(cache->handle,buffer,strlen(buffer)); } } while(buffer[3]=='-' || buffer[0]==' ' || buffer[0]=='3'); //continued message! //}//!!glennmcc: end May 11, 2005 -- removed on Mar 02, 2008 //ask server where we have to connect: sock_puts(socket,(unsigned char *)"PASV"); sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); write(log,buffer,strlen(buffer)); write(log,"\r\n",2); // printf("FTP daemon said>"); // puts(buffer); //2xx Entering passive mode (a,b,c,d,x,y) if ( *buffer != '2' ) goto quit; datahostptr=strchr(buffer,'('); //!!glennmcc: Nov 13, 2007 -- EZNOS2 doesn't enclose the info in () //therefore, if '(' is not found... look for the last 'space'. if(!datahostptr) {datahostptr=strrchr(buffer,' '); eznos2=1;} //if that still fails... 'quit' //!!glennmcc: end if(!datahostptr) goto quit;//original line ptr=++datahostptr; { int carka=0; char *portptr=NULL; while(*ptr) { if(*ptr==',') { carka++; if(carka<4) *ptr='.'; else if(carka==4) { *ptr='\0'; portptr=ptr+1; } else if (carka==5) { *ptr='\0'; dataport=256*(word)atoi(portptr); // ,x,y -> 256*x+y portptr=ptr+1; //!!glennmcc: Nov 13, 2007 -- part of above fix for EZNO2 info not in () if(eznos2) dataport+=atoi(portptr); // ,x,y -> 256*x+y //!!glennmcc: end } } else if(*ptr==')' && portptr) { //!!glennmcc: Nov 11, 2007 -- some servers have double ')' // at the end of the port address info... // this 'dblp code' will prevent that from adding the final set twice //eg: (99,167,219,186,234,255)) instead of.... (99,167,219,186,234,255) //without this fix ... 255 gets added a 2nd time and //we end-up-with... port 60414 instead of the correct port of 60159 *ptr='\0'; if(!dblp)//!!glennmcc: Nov 11, 2007 dataport+=atoi(portptr); // ,x,y -> 256*x+y dblp=1;//!!glennmcc: Nov 11, 2007 } ptr++; } } if(!dataport) goto quit; //!!glennmcc: Aug 31, 2009 //EZNOS2 sends the IP of the machine on a router as datahost //therefore we need to go back to the original host if(eznos2) { makestr(datahost,url->host,79); outs(datahost); Piip(); } else //!!glennmcc:end makestr(datahost,datahostptr,79);//original line retry: if(isdir) { if(url->file[0]) { //!!glennmcc: Oct 15, 2007 -- fix problems with CWD on FTP servers //which interpret the leading '/' as an attempted CD to 'root' if(url->file[0]=='/') sprintf( str, "CWD %s", url->file+1); else //!!glennmcc: end Oct 15, 2007 sprintf( str, "CWD %s", url->file); sock_puts(socket,(unsigned char *)str); do { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); //!!glennmcc: Apr 08, 2005 -- commented-out this block // to fix the problem of 'broken dir listing' when the // 'FTP welcome message' contains linefeeds // such as at ftp://ftp.cdrom.com/.2/simtelnet/ /* if ( *buffer != '2' && buffer[0]!=' ') { write(cache->handle,buffer,strlen(buffer)); rv=1; goto quit; } else if (buffer[3]=='-' || buffer[0]==' ') */ //!!glennmcc: end { strcat(buffer,"\r\n"); rv=1; write(cache->handle,buffer,strlen(buffer)); } } //!!glennmcc: Apr 08, 2005 -- added a test for !=' ' which is also // needed for the same fix at ftp://ftp.cdrom.com/.2/simtelnet/ while(buffer[3]=='-' || buffer[3]!=' ' || buffer[0]==' '); //continued message! // while(buffer[3]=='-' || buffer[0]==' '); //continued message! //!!glennmcc: end } strcpy(cache->mime,"ftp/list"); sprintf( str, "LIST"); } else { char *fnameptr; char mimestr[80]="ftp/binary"; fnameptr=strrchr(url->file,'/'); if(!fnameptr) { fnameptr=strrchr(url->file,'\\'); if(!fnameptr) fnameptr=url->file; else fnameptr++; } else fnameptr++; sprintf( str, "TYPE I"); if(fnameptr) { char ext[5]; strcpy(mimestr,"file/"); strncat(mimestr,fnameptr,70); mimestr[79]='\0'; get_extension(mimestr,ext); if(!strncmpi(ext,"TXT",3) || !strncmpi(ext,"HTM",3)) { //!!glennmcc: begin June 09, 2002 //optionally upload TXT and HTM in binary mode ptr=configvariable(&ARACHNEcfg,"UseBinaryFTP",NULL); if(!ptr || toupper(*ptr)=='N') //!!glennmcc: end sprintf( str, "TYPE A"); // ascii=1; } } strcpy(cache->mime,mimestr); sock_puts(socket,(unsigned char *)str); write(log,str,strlen(str)); write(log,"\r\n",2); sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); write(log,buffer,strlen(buffer)); write(log,"\r\n",2); // printf("FTP daemon said>"); // puts(buffer); if ( *buffer != '2' || uploadfile) { strcat(buffer,"\n"); write(cache->handle,buffer,strlen(buffer)); } if ( *buffer != '2' ) { rv=1; goto quit; } if(!uploadfile) //!!glennmcc: Oct 17, 2007 -- fix problems with FTP servers //which interpret the leading '/' as an attempted CD to 'root' if(url->file[0]=='/') sprintf( str, "RETR %s", url->file+1); else sprintf( str, "RETR %s", url->file); //original single line above this comment //!!glennmcc: end else sprintf( str, "STOR %s", url->file); } sock_puts(socket,(unsigned char *)str); write(log,str,strlen(str)); write(log,"\r\n",2); //!!glennmcc: Oct 19, 2008 -- back to original fix //!!glennmcc: Nov 15, 2007 -- always 'close' the connection when done //with both dir listings and file downloads //Apr 10, 2007 fix did it only for dir listings if(isdir || strstr(str,"RETR")) //if(isdir) sock_puts(socket,(unsigned char *)"QUIT");//!!glennmcc: Apr 10, 2007 //!!glennmcc: end if(!retry) { //get file using datahost & dataport GlobalLogoStyle=0; //SDL set resolve animation host=resolve_fn( datahost, (sockfunct_t) TcpIdleFunc ); //SDL // host=resolve( datahost ); if(!host) goto quit; GlobalLogoStyle=2; //SDL set connect animation if (!tcp_open( &datasocket, locport(), host, dataport, NULL )) { sprintf(str,msg_errcon,datahost); outs(str); goto quit; } sprintf(str,msg_con,datahost,dataport); outs(str); write(log,str,strlen(str)); write(log,"\r\n",2); //wait for datasocket to open: sock_wait_established(&datasocket, sock_delay, (sockfunct_t) TcpIdleFunc, &status); //SDL //!!glennmcc: Sep 27, 2008 -- increase D/L speed on cable & DSL //many thanks to 'mik' for pointing me in the right direction. :) { #ifdef DEBUG char sp[80]; sprintf(sp,"Available stack = %u bytes",_SP); outs(sp); Piip(); Piip(); #endif if(_SP>(1024*SETBUFSIZE)) { char setbuf[1024*SETBUFSIZE]; sock_setbuf(&datasocket, (unsigned char *)setbuf, 1024*SETBUFSIZE); } } //!!glennmcc: end GlobalLogoStyle=1; //SDL set data animation } //wait for "110 openning connection" (or "550 ....error....") sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); write(log,buffer,strlen(buffer)); write(log,"\r\n",2); // printf("FTP daemon said>"); // puts(buffer); if ( *buffer != '1' || uploadfile) { strcat(buffer,"\n"); write(cache->handle,buffer,strlen(buffer)); } if ( *buffer != '1' ) { if(!strncmp(buffer,"550",3) && !retry) { retry=1; isdir=1-isdir; if(isdir) strcat(url->file,"/"); else { int i=strlen(url->file); if(i>0 && url->file[i-1]=='/') url->file[i-1]='\0'; } goto retry; } strcpy(cache->mime,"text/plain"); rv=1; goto dataquit; } if(!uploadfile) //-------------------------------------- download --------------- { while ( 1 ) { xChLogoTICK(1); if(GUITICK()) if(GLOBAL.gotolocation || GLOBAL.abort) goto dataquit; if (sock_dataready( &datasocket )) { len = sock_fastread( &datasocket, (unsigned char*)buffer, BUFLEN ); write(cache->handle,buffer,len); total+=len; sprintf(str,MSG_BYTESR,MSG_DOWNLD,total); outs(str); } else sock_tick( &datasocket, &status ); //shift TCP/IP } } else //-------------------------------------- upload ------------------ { int f,lenread,done; long length; char pom[256]; /* if(ascii) f=a_sopen(uploadfile,O_RDONLY|O_TEXT, SH_DENYNO, S_IREAD); else*/ f=a_sopen(uploadfile,O_RDONLY|O_BINARY, SH_DENYNO, S_IREAD); if(f<0) goto dataquit; lenread=done=0; length=0l; { long filel=a_filelength(f); while(1) { sprintf(pom,MSG_UPLOAD,length,filel); outs(pom); //!!glennmcc:Oct 23, 2008 -- 'reversed the logic' // to keep from overflowing at 21megs if(filel>100) percentbar((int)(length/(filel/100))); // percentbar((int)(100*length/filel)); lenread=a_read(f,buffer,BUFLEN); length+=lenread; if(lenread<=0) done=1; //wait until we can write to socket: while(sock_tbleft(&datasocket)<lenread) //SDL // while( datasocket.datalen > 1024) { sock_tick(&datasocket,&status); xChLogoTICK(1); // animation of logo if(GUITICK()) goto dataquit; } if(done) { sock_close( &datasocket ); a_close(f); goto dataclose; } sock_fastwrite(&datasocket,(unsigned char *)buffer,lenread); sock_tick(&datasocket,&status); }//loop } } dataquit: //!!glennmcc: Nov 15, 2007 -- removed sock_abort because it was // sometimes preventing the connection from being closed, // therefore preventing access to several files within a short time // due to too many connections open from the same IP // sock_abort( &datasocket );//original line //!!glennmcc: end dataclose: outs(MSG_CLOSE); sock_puts(socket,(unsigned char *)"QUIT");//!!glennmcc: Dec 04, 2006 sock_wait_closed( &datasocket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL if(uploadfile) { sock_wait_input( socket, sock_delay, (sockfunct_t) TcpIdleFunc, &status ); //SDL sock_gets( socket, (unsigned char *)buffer, sizeof( buffer )); outs(buffer); } quit: sock_puts(socket,(unsigned char *)"QUIT"); sock_close( socket ); closing[socknum]=1; sock_keepalive[socknum][0]='\0'; // sock_wait_closed( socket, sock_delay, NULL, &status ); //we will better wait because we are about to deallocate datasocket sock_err: switch (status) { case 1 : /* foreign host closed */ write(log,MSG_CLOSE,strlen(MSG_CLOSE)); write(log,"\r\n",2); close(log); break; case -1: /* timeout */ sprintf(str,MSG_TCPERR, sockerr(socket)); outs(str); write(log,str,strlen(str)); write(log,"\r\n",2); close(log); break; } if(total) { cache->knowsize=1; cache->size=total; rv=1; } if(cache->handle>=0) { a_close(cache->handle); rv=1; } return rv; }
static void start_daemon() { // Capture USB device struct usb_sock_t *usb_sock = usb_open(); if (usb_sock == NULL) goto cleanup_usb; // Capture a socket uint32_t desired_port = g_options.desired_port; struct tcp_sock_t *tcp_socket = tcp_open(desired_port); if (tcp_socket == NULL) goto cleanup_tcp; uint32_t real_port = tcp_port_number_get(tcp_socket); if (desired_port != 0 && desired_port != real_port) { ERR("Received port number did not match requested port number." " The requested port number may be too high."); goto cleanup_tcp; } printf("%u\n", real_port); // Lose connection to caller if (!g_options.nofork_mode && fork() > 0) exit(0); for (;;) { struct service_thread_param *args = calloc(1, sizeof(*args)); if (args == NULL) { ERR("Failed to alloc space for thread args"); goto cleanup_thread; } args->usb_sock = usb_sock; args->tcp = tcp_conn_accept(tcp_socket); if (args->tcp == NULL) { ERR("Failed to open tcp connection"); goto cleanup_thread; } int status = pthread_create(&args->thread_handle, NULL, &service_connection, args); if (status) { ERR("Failed to spawn thread, error %d", status); goto cleanup_thread; } continue; cleanup_thread: if (args != NULL) { if (args->tcp != NULL) tcp_conn_close(args->tcp); free(args); } break; } cleanup_tcp: if (tcp_socket!= NULL) tcp_close(tcp_socket); cleanup_usb: if (usb_sock != NULL) usb_close(usb_sock); return; }
static int name_server_send (int ns, struct sockaddr_in *nsap) { int resplen = 0; if (badns & (1 << ns)) /* this NameServer already marked bad */ { resolve_close(); return (NEXT_NS); } if (Qhook) { int done = 0; int loops = 0; do { res_sendhookact act = (*Qhook) (&nsap, (const u_char**)&ns_buf, &ns_buflen, ns_ans, ns_anssiz, &resplen); switch (act) { case res_goahead: done = 1; break; case res_nextns: resolve_close(); return (NEXT_NS); case res_done: return (resplen); case res_modified: /* give the hook another try */ if (++loops < 42) break; /* fallthrough */ case res_error: /* fallthrough */ default: return (-1); } } while (!done); } Dprint (_res.options & RES_DEBUG, (";; Querying server (# %d) address = %s\n", ns + 1, inet_ntoa(nsap->sin_addr))); if (v_circuit) /* i.e. TCP */ { int truncated; u_short len; u_char *cp; /* Use virtual circuit; at most one attempt per server. */ Try = _res.retry; truncated = 0; if (!sock || !vc) { DWORD his_ip = ntohl (nsap->sin_addr.s_addr); WORD his_port = ntohs (nsap->sin_port); if (sock) resolve_close(); sock = (sock_type*) calloc (sizeof(_tcp_Socket), 1); if (!sock) { Perror ("calloc(vc)", "no memory"); return (-1); } if (!tcp_open(&sock->tcp,0,his_ip,his_port,NULL) || !tcp_conn(&sock->tcp,&errno,dns_timeout)) { Aerror ("tcp_open/vc", "failed/timeout", *nsap); badns |= (1 << ns); resolve_close(); return (NEXT_NS); } vc = 1; } /* Send length & message */ { int send_len = INT16SZ + ns_buflen; BYTE *send_buf = (BYTE*) alloca (send_len); PUTSHORT (ns_buflen, send_buf); memcpy (send_buf + INT16SZ, ns_buf, ns_buflen); if (sock_write(sock,send_buf,send_len) != send_len) { Perror ("sock_write() failed", sockerr(sock)); badns |= (1 << ns); resolve_close(); return (NEXT_NS); } } /* Receive length & response */ cp = ns_ans; len = INT16SZ; while ((n = tcp_read(&sock->tcp,cp,len,&errno,dns_timeout)) > 0) { cp += n; len -= n; if ((signed)len <= 0) break; } if (n <= 0) { Perror ("tcp_read() failed", sockerr(sock)); resolve_close(); return (NEXT_NS); } resplen = _getshort (ns_ans); if (resplen > ns_anssiz) { Dprint (_res.options & RES_DEBUG,(";; response truncated\n")); truncated = 1; len = ns_anssiz; } else len = resplen; cp = ns_ans; while (len && (n = tcp_read(&sock->tcp,cp,len,&errno,dns_timeout)) > 0) { cp += n; len -= n; } if (n <= 0) { Perror ("tcp_read(vc)",sockerr(sock)); resolve_close(); return (NEXT_NS); } if (truncated) { /* Flush rest of answer so connection stays in synch. */ anhp->tc = 1; len = resplen - ns_anssiz; while (len) { u_char junk[PACKETSZ]; n = (len > sizeof(junk) ? sizeof(junk) : len); n = tcp_read (&sock->tcp,junk,n,&errno,dns_timeout); if (n > 0) len -= n; else break; } } } else /* !v_circuit, i.e. UDP */ { DWORD timeout; if (!sock || vc) { if (vc) resolve_close(); sock = (sock_type*) calloc (sizeof(_udp_Socket), 1); if (!sock) { Perror ("calloc(dg)", "no memory"); return (-1); } connected = 0; } /* Connect only if we are sure we won't * receive a response from another server. */ if (!connected) { DWORD his_ip = ntohl (nsap->sin_addr.s_addr); WORD his_port = ntohs (nsap->sin_port); if (!udp_open(&sock->udp,0,his_ip,his_port,NULL)) { Aerror ("connect/dg", "ARP failed", *nsap); badns |= (1 << ns); resolve_close(); return (NEXT_NS); } connected = 1; } if (sock_write(sock,(const BYTE*)ns_buf,ns_buflen) != ns_buflen) { Perror ("sock_write() failed", ""); badns |= (1 << ns); resolve_close(); return (NEXT_NS); } /* Wait for reply */ timeout = (unsigned)_res.retrans << Try; if (Try > 0) timeout /= _res.nscount; if ((long)timeout <= 0) timeout = 1; wait: n = udp_read (&sock->udp, ns_ans, ns_anssiz, &errno, timeout); if (n == 0) { Dprint (_res.options & RES_DEBUG, (";; timeout\n")); gotsomewhere = 1; resolve_close(); return (NEXT_NS); } gotsomewhere = 1; if (hp->id != anhp->id) { /* response from old query, ignore it. * XXX - potential security hazard could be detected here. */ DprintQ ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_REPLY), (";; old answer:\n"), ns_ans, resplen); goto wait; } if (!(_res.options & RES_INSECURE2) && !res_queriesmatch(ns_buf, ns_buf+ns_buflen, ns_ans, ns_ans+ns_anssiz)) { /* response contains wrong query? ignore it. * XXX - potential security hazard could be detected here. */ DprintQ ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_REPLY), (";; wrong query name:\n"), ns_ans, resplen); goto wait; } if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) { DprintQ (_res.options & RES_DEBUG,("server rejected query:\n"), ns_ans,resplen); badns |= (1 << ns); resolve_close(); /* don't retry if called from dig */ if (!_res.pfcode) return (NEXT_NS); } if (!(_res.options & RES_IGNTC) && anhp->tc) { /* get rest of answer; use TCP with same server. */ Dprint (_res.options & RES_DEBUG, (";; truncated answer\n")); v_circuit = 1; resolve_close(); return (SAME_NS); } } /* if vcicuit / dg */ Dprint ((_res.options & RES_DEBUG) || ((_res.pfcode & RES_PRF_REPLY) && (_res.pfcode & RES_PRF_HEAD1)), (";; got answer:\n")); DprintQ ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_REPLY), (" \b"), ns_ans, resplen); /* * If using virtual circuits (TCP), we assume that the first server * is preferred over the rest (i.e. it is on the local machine) and * only keep that one open. If we have temporarily opened a virtual * circuit, or if we haven't been asked to keep a socket open, * close the socket. */ if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) || !(_res.options & RES_STAYOPEN)) resolve_close(); if (Rhook) { int done = 0, loops = 0; do { res_sendhookact act = (*Rhook) (nsap, ns_buf, ns_buflen, ns_ans, ns_anssiz, &resplen); switch (act) { case res_goahead: case res_done: done = 1; break; case res_nextns: resolve_close(); return (NEXT_NS); case res_modified: /* give the hook another try */ if (++loops < 42) break; /* fallthrough */ case res_error: /* fallthrough */ default: return (-1); } } while (!done); } return (resplen); }